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> :host { display: inline-block; } :host ::slotted(*) { padding: var(--cr-radio-group-item-padding, 12px); } :host([disabled]) { cursor: initial; pointer-events: none; user-select: none; } :host([disabled]) ::slotted(*) { opacity: var(--cr-disabled-opacity); } </style> <slot></slot>
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_radio_group/cr_radio_group.html
HTML
unknown
401
// 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 '../cr_radio_button/cr_radio_button.js'; import '../cr_shared_vars.css.js'; import {assert} from '//resources/js/assert_ts.js'; import {EventTracker} from '//resources/js/event_tracker.js'; import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {CrRadioButtonElement} from '../cr_radio_button/cr_radio_button.js'; import {getTemplate} from './cr_radio_group.html.js'; function isEnabled(radio: HTMLElement): boolean { return radio.matches(':not([disabled]):not([hidden])') && radio.style.display !== 'none' && radio.style.visibility !== 'hidden'; } export class CrRadioGroupElement extends PolymerElement { static get is() { return 'cr-radio-group'; } static get template() { return getTemplate(); } static get properties() { return { disabled: { type: Boolean, value: false, reflectToAttribute: true, observer: 'update_', }, selected: { type: String, notify: true, observer: 'update_', }, selectableElements: { type: String, value: 'cr-radio-button, cr-card-radio-button, controlled-radio-button', }, selectableRegExp_: { value: Object, computed: 'computeSelectableRegExp_(selectableElements)', }, }; } disabled: boolean; selected: string; selectableElements: string; private selectableRegExp_: RegExp; private buttons_: CrRadioButtonElement[]|null = null; private buttonEventTracker_: EventTracker|null = null; private deltaKeyMap_: Map<string, number>|null = null; private isRtl_: boolean = false; private populateBound_: (() => void)|null = null; override ready() { super.ready(); this.addEventListener( 'keydown', e => this.onKeyDown_(/** @type {!KeyboardEvent} */ (e))); this.addEventListener('click', this.onClick_.bind(this)); if (!this.hasAttribute('role')) { this.setAttribute('role', 'radiogroup'); } this.setAttribute('aria-disabled', 'false'); } override connectedCallback() { super.connectedCallback(); this.isRtl_ = this.matches(':host-context([dir=rtl]) cr-radio-group'); this.deltaKeyMap_ = new Map([ ['ArrowDown', 1], ['ArrowLeft', this.isRtl_ ? 1 : -1], ['ArrowRight', this.isRtl_ ? -1 : 1], ['ArrowUp', -1], ['PageDown', 1], ['PageUp', -1], ]); this.buttonEventTracker_ = new EventTracker(); this.populateBound_ = () => this.populate_(); assert(this.populateBound_); this.shadowRoot!.querySelector('slot')!.addEventListener( 'slotchange', this.populateBound_); this.populate_(); } override disconnectedCallback() { super.disconnectedCallback(); assert(this.populateBound_); this.shadowRoot!.querySelector('slot')!.removeEventListener( 'slotchange', this.populateBound_); assert(this.buttonEventTracker_); this.buttonEventTracker_.removeAll(); } override focus() { if (this.disabled || !this.buttons_) { return; } const radio = this.buttons_.find(radio => this.isButtonEnabledAndSelected_(radio)); if (radio) { radio.focus(); } } private onKeyDown_(event: KeyboardEvent) { if (this.disabled) { return; } if (event.ctrlKey || event.shiftKey || event.metaKey || event.altKey) { return; } const targetElement = event.target as CrRadioButtonElement; if (!this.buttons_ || !this.buttons_.includes(targetElement)) { return; } if (event.key === ' ' || event.key === 'Enter') { event.preventDefault(); this.select_(targetElement); return; } const enabledRadios = this.buttons_.filter(isEnabled); if (enabledRadios.length === 0) { return; } assert(this.deltaKeyMap_); let selectedIndex; const max = enabledRadios.length - 1; if (event.key === 'Home') { selectedIndex = 0; } else if (event.key === 'End') { selectedIndex = max; } else if (this.deltaKeyMap_.has(event.key)) { const delta = this.deltaKeyMap_.get(event.key)!; // If nothing selected, start from the first radio then add |delta|. const lastSelection = enabledRadios.findIndex(radio => radio.checked); selectedIndex = Math.max(0, lastSelection) + delta; // Wrap the selection, if needed. if (selectedIndex > max) { selectedIndex = 0; } else if (selectedIndex < 0) { selectedIndex = max; } } else { return; } const radio = enabledRadios[selectedIndex]!; const name = `${radio.name}`; if (this.selected !== name) { event.preventDefault(); this.selected = name; radio.focus(); } } private computeSelectableRegExp_(): RegExp { const tags = this.selectableElements.split(', ').join('|'); return new RegExp(`^(${tags})$`, 'i'); } private onClick_(event: Event) { const path = event.composedPath(); if (path.some(target => /^a$/i.test((target as HTMLElement).tagName))) { return; } const target = path.find( n => this.selectableRegExp_.test((n as HTMLElement).tagName)) as CrRadioButtonElement; if (target && this.buttons_ && this.buttons_.includes(target)) { this.select_(target); } } private populate_() { const nodes = this.shadowRoot!.querySelector('slot')!.assignedNodes({flatten: true}); this.buttons_ = Array.from(nodes).filter( node => node.nodeType === Node.ELEMENT_NODE && (node as HTMLElement).matches(this.selectableElements)) as CrRadioButtonElement[]; assert(this.buttonEventTracker_); this.buttonEventTracker_.removeAll(); this.buttons_!.forEach(el => { this.buttonEventTracker_!.add( el, 'disabled-changed', () => this.populate_()); this.buttonEventTracker_!.add(el, 'name-changed', () => this.populate_()); }); this.update_(); } private select_(button: CrRadioButtonElement) { if (!isEnabled(button)) { return; } const name = `${button.name}`; if (this.selected !== name) { this.selected = name; } } private isButtonEnabledAndSelected_(button: CrRadioButtonElement): boolean { return !this.disabled && button.checked && isEnabled(button); } private update_() { if (!this.buttons_) { return; } let noneMadeFocusable = true; this.buttons_.forEach(radio => { radio.checked = this.selected !== undefined && `${radio.name}` === `${this.selected}`; const disabled = this.disabled || !isEnabled(radio); const canBeFocused = radio.checked && !disabled; if (canBeFocused) { radio.focusable = true; noneMadeFocusable = false; } else { radio.focusable = false; } radio.setAttribute('aria-disabled', `${disabled}`); }); this.setAttribute('aria-disabled', `${this.disabled}`); if (noneMadeFocusable && !this.disabled) { const radio = this.buttons_.find(isEnabled); if (radio) { radio.focusable = true; } } } } declare global { interface HTMLElementTagNameMap { 'cr-radio-group': CrRadioGroupElement; } } customElements.define(CrRadioGroupElement.is, CrRadioGroupElement);
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_radio_group/cr_radio_group.ts
TypeScript
unknown
7,483
// 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. /** * @fileoverview Mixin for scrollable containers with <iron-list>. * * Any containers with the 'scrollable' attribute set will have the following * classes toggled appropriately: can-scroll, is-scrolled, scrolled-to-bottom. * These classes are used to style the container div and list elements * appropriately, see cr_shared_style.css. * * The associated HTML should look something like: * <div id="container" scrollable> * <iron-list items="[[items]]" scroll-target="container"> * <template> * <my-element item="[[item]] tabindex$="[[tabIndex]]"></my-element> * </template> * </iron-list> * </div> * * In order to get correct keyboard focus (tab) behavior within the list, * any elements with tabbable sub-elements also need to set tabindex, e.g: * * <dom-module id="my-element> * <template> * ... * <paper-icon-button toggles active="{{opened}}" tabindex$="[[tabindex]]"> * </template> * </dom-module> * * NOTE: If 'container' is not fixed size, it is important to call * updateScrollableContents() when [[items]] changes, otherwise the container * will not be sized correctly. */ // clang-format off import {beforeNextRender, dedupingMixin, microTask, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {IronListElement} from '//resources/polymer/v3_0/iron-list/iron-list.js'; // clang-format on type IronListElementWithExtras = IronListElement&{ savedScrollTops: number[], }; type Constructor<T> = new (...args: any[]) => T; export const CrScrollableMixin = dedupingMixin( <T extends Constructor<PolymerElement>>(superClass: T): T& Constructor<CrScrollableMixinInterface> => { class CrScrollableMixin extends superClass implements CrScrollableMixinInterface { private resizeObserver_: ResizeObserver; constructor(...args: any[]) { super(...args); this.resizeObserver_ = new ResizeObserver((entries) => { requestAnimationFrame(() => { for (const entry of entries) { this.onScrollableContainerResize_(entry.target as HTMLElement); } }); }); } override ready() { super.ready(); beforeNextRender(this, () => { this.requestUpdateScroll(); // Listen to the 'scroll' event for each scrollable container. const scrollableElements = this.shadowRoot!.querySelectorAll('[scrollable]'); for (const scrollableElement of scrollableElements) { scrollableElement.addEventListener( 'scroll', this.updateScrollEvent_.bind(this)); } }); } override disconnectedCallback() { super.disconnectedCallback(); this.resizeObserver_.disconnect(); } /** * Called any time the contents of a scrollable container may have * changed. This ensures that the <iron-list> contents of dynamically * sized containers are resized correctly. */ updateScrollableContents() { this.requestUpdateScroll(); const ironLists = this.shadowRoot!.querySelectorAll<IronListElement>( '[scrollable] iron-list'); for (const ironList of ironLists) { // When the scroll-container of an iron-list has scrollHeight of 1, // the iron-list will default to showing a minimum of 3 items. // After an iron-resize is fired, it will resize to have the correct // scrollHeight, but another iron-resize is required to render all // the items correctly. // If the scrollHeight of the scroll-container is 0, the element is // not yet rendered, and we must wait until its scrollHeight becomes // 1, then fire the first iron-resize event. const scrollContainer = ironList.parentElement!; const scrollHeight = scrollContainer.scrollHeight; if (scrollHeight <= 1 && ironList.items!.length > 0 && window.getComputedStyle(scrollContainer).display !== 'none') { // The scroll-container does not have a proper scrollHeight yet. // An additional iron-resize is needed, which will be triggered by // the observer after scrollHeight changes. // Do not observe for resize if there are no items, or if the // scroll-container is explicitly hidden, as in those cases there // will not be any future resizes. this.resizeObserver_.observe(scrollContainer); } if (scrollHeight !== 0) { // If the iron-list is already rendered, fire an initial // iron-resize event. Otherwise, the resizeObserver_ will handle // firing the iron-resize event, upon its scrollHeight becoming 1. ironList.notifyResize(); } } } /** * Setup the initial scrolling related classes for each scrollable * container. Called from ready() and updateScrollableContents(). May * also be called directly when the contents change (e.g. when not using * iron-list). */ requestUpdateScroll() { requestAnimationFrame(() => { const scrollableElements = this.shadowRoot!.querySelectorAll<HTMLElement>('[scrollable]'); for (const scrollableElement of scrollableElements) { this.updateScroll_(scrollableElement); } }); } saveScroll(list: IronListElementWithExtras) { // Store a FIFO of saved scroll positions so that multiple updates in // a frame are applied correctly. Specifically we need to track when // '0' is saved (but not apply it), and still handle patterns like // [30, 0, 32]. list.savedScrollTops = list.savedScrollTops || []; list.savedScrollTops.push(list.scrollTarget!.scrollTop); } restoreScroll(list: IronListElementWithExtras) { microTask.run(() => { const scrollTop = list.savedScrollTops.shift(); // Ignore scrollTop of 0 in case it was intermittent (we do not need // to explicitly scroll to 0). if (scrollTop !== 0) { list.scroll(0, scrollTop!); } }); } /** * Event wrapper for updateScroll_. */ private updateScrollEvent_(event: Event) { const scrollable = event.target as HTMLElement; this.updateScroll_(scrollable); } /** * This gets called once initially and any time a scrollable container * scrolls. */ private updateScroll_(scrollable: HTMLElement) { scrollable.classList.toggle( 'can-scroll', scrollable.clientHeight < scrollable.scrollHeight); scrollable.classList.toggle('is-scrolled', scrollable.scrollTop > 0); scrollable.classList.toggle( 'scrolled-to-bottom', scrollable.scrollTop + scrollable.clientHeight >= scrollable.scrollHeight); } /** * This gets called upon a resize event on the scrollable element */ private onScrollableContainerResize_(scrollable: HTMLElement) { const nodeList = scrollable.querySelectorAll<IronListElement>('iron-list'); if (nodeList.length === 0 || scrollable.scrollHeight > 1) { // Stop observing after the scrollHeight has its correct value, or // if somehow there are no more iron-lists in the scrollable. this.resizeObserver_.unobserve(scrollable); } if (scrollable.scrollHeight !== 0) { // Fire iron-resize event only if scrollHeight has changed from 0 to // 1 or from 1 to the correct size. ResizeObserver doesn't exactly // observe scrollHeight and may fire despite it staying at 0, so // we can ignore those events. for (const node of nodeList) { node.notifyResize(); } } } } return CrScrollableMixin; }); export interface CrScrollableMixinInterface { updateScrollableContents(): void; requestUpdateScroll(): void; saveScroll(list: IronListElement): void; restoreScroll(list: IronListElement): void; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_scrollable_mixin.ts
TypeScript
unknown
8,720
<style include="cr-shared-style cr-input-style"> :host { display: flex; user-select: none; --cr-search-field-clear-icon-fill: var(--google-grey-700); --cr-search-field-clear-icon-margin-end : -4px; --cr-search-field-input-border-bottom: 1px solid var(--cr-secondary-text-color); } #searchIcon { align-self: center; display: var(--cr-search-field-search-icon-display, inherit); height: 16px; padding: 4px; vertical-align: middle; width: 16px; } #searchIconInline { --iron-icon-fill-color: var(--cr-search-field-search-icon-fill, inherit); display: var(--cr-search-field-search-icon-inline-display, none); margin-inline-start: var(--cr-search-field-search-icon-inline-margin-start, 0); } #searchInput { --cr-input-background-color: transparent; --cr-input-border-bottom: var(--cr-search-field-input-border-bottom); --cr-input-border-radius: 0; --cr-input-error-display: none; --cr-input-min-height: var(--cr-search-field-input-min-height, 24px); --cr-input-padding-end: 0; --cr-input-padding-start: var(--cr-search-field-input-padding-start, 0); --cr-input-padding-bottom: var(--cr-search-field-input-padding-bottom, 2px); --cr-input-padding-top: var(--cr-search-field-input-padding-top, 2px); --cr-input-placeholder-color: var(--cr-search-field-placeholder-color); --cr-input-underline-display: var(--cr-search-field-underline-display); --cr-input-underline-border-radius: var(--cr-search-field-input-underline-border-radius, 0); --cr-input-underline-height: var(--cr-search-field-input-underline-height, 0); align-self: stretch; color: var(--cr-primary-text-color); display: block; font-size: 92.3076923%; /* To 12px from 13px. */ width: var(--cr-search-field-input-width, 160px); } :host([has-search-text]) #searchInput { --cr-input-padding-end: calc(24px + var(--cr-search-field-clear-icon-margin-end)); } #clearSearch { --cr-icon-button-fill-color: var(--cr-search-field-clear-icon-fill); /* A 16px icon that fits on the input line. */ --cr-icon-button-icon-size: var(--cr-search-field-clear-icon-size, 16px); --cr-icon-button-size: 24px; margin-inline-end: var(--cr-search-field-clear-icon-margin-end); margin-inline-start: 4px; position: absolute; right: 0; } :host-context([dir='rtl']) #clearSearch { left: 0; right: auto; } </style> <iron-icon id="searchIcon" icon="cr:search" part="searchIcon"></iron-icon> <cr-input id="searchInput" part="searchInput" on-search="onSearchTermSearch" on-input="onSearchTermInput" aria-label$="[[label]]" type="search" autofocus="[[autofocus]]" placeholder="[[label]]" spellcheck="false"> <iron-icon id="searchIconInline" slot="inline-prefix" icon="cr:search"></iron-icon> <cr-icon-button id="clearSearch" class="icon-cancel" hidden$="[[!hasSearchText]]" slot="suffix" on-click="onTapClear_" title="[[clearLabel]]"> </cr-icon-button> </cr-input>
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_search_field/cr_search_field.html
HTML
unknown
3,305
// 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-search-field' is a simple implementation of a polymer component that * uses CrSearchFieldMixin. */ import '../cr_icon_button/cr_icon_button.js'; import '../cr_input/cr_input.js'; import '../cr_input/cr_input_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 {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {CrInputElement} from '../cr_input/cr_input.js'; import {getTemplate} from './cr_search_field.html.js'; import {CrSearchFieldMixin} from './cr_search_field_mixin.js'; const CrSearchFieldElementBase = CrSearchFieldMixin(PolymerElement); export interface CrSearchFieldElement { $: { clearSearch: HTMLElement, searchInput: CrInputElement, }; } export class CrSearchFieldElement extends CrSearchFieldElementBase { static get is() { return 'cr-search-field'; } static get template() { return getTemplate(); } static get properties() { return { autofocus: { type: Boolean, value: false, }, }; } override autofocus: boolean; override getSearchInput(): CrInputElement { return this.$.searchInput; } private onTapClear_() { this.setValue(''); setTimeout(() => { this.$.searchInput.focus(); }); } } declare global { interface HTMLElementTagNameMap { 'cr-search-field': CrSearchFieldElement; } } customElements.define(CrSearchFieldElement.is, CrSearchFieldElement);
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_search_field/cr_search_field.ts
TypeScript
unknown
1,725
// 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 */ function CrSearchFieldMixinInterface() {} /** @return {!HTMLInputElement} */ CrSearchFieldMixinInterface.prototype.getSearchInput = function() {}; /** @return {string} */ CrSearchFieldMixinInterface.prototype.getValue = function() {}; /** * @constructor * @extends {HTMLElement} * @implements {CrSearchFieldMixinInterface} */ function CrSearchFieldElement() {}
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_search_field/cr_search_field_externs.js
JavaScript
unknown
655
// 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. /** * Helper functions for implementing an incremental search field. See * <settings-subpage-search> for a simple implementation. */ import {assertNotReached} from '//resources/js/assert_ts.js'; import {dedupingMixin, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {CrInputElement} from '../cr_input/cr_input.js'; type Constructor<T> = new (...args: any[]) => T; export const CrSearchFieldMixin = dedupingMixin( <T extends Constructor<PolymerElement>>(superClass: T): T& Constructor<CrSearchFieldMixinInterface> => { class CrSearchFieldMixin extends superClass implements CrSearchFieldMixinInterface { static get properties() { return { // Prompt text to display in the search field. label: { type: String, value: '', }, // Tooltip to display on the clear search button. clearLabel: { type: String, value: '', }, hasSearchText: { type: Boolean, reflectToAttribute: true, value: false, }, }; } label: string; clearLabel: string; hasSearchText: boolean; private effectiveValue_: string = ''; private searchDelayTimer_: number = -1; /** * @return The input field element the behavior should use. */ getSearchInput(): HTMLInputElement|CrInputElement { assertNotReached(); } /** * @return The value of the search field. */ getValue(): string { return this.getSearchInput().value; } private fire_(eventName: string, detail?: any) { this.dispatchEvent(new CustomEvent( eventName, {bubbles: true, composed: true, detail})); } /** * Sets the value of the search field. * @param noEvent Whether to prevent a 'search-changed' event * firing for this change. */ setValue(value: string, noEvent?: boolean) { const updated = this.updateEffectiveValue_(value); this.getSearchInput().value = this.effectiveValue_; if (!updated) { // If the input is only whitespace and value is empty, // |hasSearchText| needs to be updated. if (value === '' && this.hasSearchText) { this.hasSearchText = false; } return; } this.onSearchTermInput(); if (!noEvent) { this.fire_('search-changed', this.effectiveValue_); } } private scheduleSearch_() { if (this.searchDelayTimer_ >= 0) { clearTimeout(this.searchDelayTimer_); } // Dispatch 'search' event after: // 0ms if the value is empty // 500ms if the value length is 1 // 400ms if the value length is 2 // 300ms if the value length is 3 // 200ms if the value length is 4 or greater. // The logic here was copied from WebKit's native 'search' event. const length = this.getValue().length; const timeoutMs = length > 0 ? (500 - 100 * (Math.min(length, 4) - 1)) : 0; this.searchDelayTimer_ = setTimeout(() => { this.getSearchInput().dispatchEvent(new CustomEvent( 'search', {composed: true, detail: this.getValue()})); this.searchDelayTimer_ = -1; }, timeoutMs); } onSearchTermSearch() { this.onValueChanged_(this.getValue(), false); } /** * Update the state of the search field whenever the underlying input * value changes. Unlike onsearch or onkeypress, this is reliably called * immediately after any change, whether the result of user input or JS * modification. */ onSearchTermInput() { this.hasSearchText = this.getSearchInput().value !== ''; this.scheduleSearch_(); } /** * Updates the internal state of the search field based on a change that * has already happened. * @param noEvent Whether to prevent a 'search-changed' event * firing for this change. */ private onValueChanged_(newValue: string, noEvent: boolean) { const updated = this.updateEffectiveValue_(newValue); if (updated && !noEvent) { this.fire_('search-changed', this.effectiveValue_); } } /** * Trim leading whitespace and replace consecutive whitespace with * single space. This will prevent empty string searches and searches * for effectively the same query. */ private updateEffectiveValue_(value: string): boolean { const effectiveValue = value.replace(/\s+/g, ' ').replace(/^\s/, ''); if (effectiveValue === this.effectiveValue_) { return false; } this.effectiveValue_ = effectiveValue; return true; } } return CrSearchFieldMixin; }); export interface CrSearchFieldMixinInterface { label: string; clearLabel: string; hasSearchText: boolean; getSearchInput(): HTMLInputElement|CrInputElement; getValue(): string; setValue(value: string, noEvent?: boolean): void; onSearchTermSearch(): void; onSearchTermInput(): void; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_search_field/cr_search_field_mixin.ts
TypeScript
unknown
5,686
<style include="cr-shared-style cr-hidden-style"> :host(:not([error-message-allowed])) cr-input { --cr-input-error-display: none; } :host([opened_]) cr-input { --cr-input-border-radius: 4px 4px 0 0; } iron-dropdown, cr-input { /* 472px is the max width of the input field for a dialog. */ width: var(--cr-searchable-drop-down-width, 472px); } cr-input { --cr-input-padding-start: 8px; } iron-dropdown { max-height: 270px; } iron-dropdown [slot='dropdown-content'] { background-color: var(--cr-searchable-drop-down-bg-color, white); border-radius: 0 0 4px 4px; box-shadow: var(--cr-searchable-drop-down-shadow, 0 2px 6px var(--paper-grey-500)); min-width: 128px; padding: 8px 0; } #input-overlay { border-radius: 4px; height: 100%; left: 0; overflow: hidden; pointer-events: none; position: absolute; top: 0; width: 100%; } #dropdown-icon { --iron-icon-height: 20px; --iron-icon-width: 20px; margin-top: -10px; padding-inline-end: 6px; position: absolute; right: 0; top: 50%; } :host-context([dir='rtl']) #dropdown-icon { left: 0; right: unset; } cr-input:focus-within #dropdown-icon { --iron-icon-fill-color: var(--cr-searchable-drop-down-icon-color-focus, var(--google-blue-600)); } #input-box { height: 100%; left: 0; pointer-events: none; top: 0; width: 100%; } #dropdown-box { pointer-events: initial; width: 100%; } #loading-box { align-items: center; box-sizing: border-box; display: flex; height: 32px; padding: 0 8px; text-align: start; width: 100%; } #loading-box div { font-size: 12px; padding: 0 16px; } #loading-box paper-spinner-lite { --paper-spinner-color: var(--cr-searchable-drop-down-spinner-color, var(--google-blue-600)); --paper-spinner-stroke-width: 2px; height: 16px; width: 16px; } .list-item { background: none; border: none; box-sizing: border-box; color: var(--cr-searchable-drop-down-list-item-color, var(--paper-grey-900)); font: inherit; min-height: 32px; padding: 0 8px; text-align: start; width: 100%; } .list-item[selected_] { background-color: var(--cr-searchable-drop-down-list-bg-color-selected, rgba(0, 0, 0, .04)); outline: none; } .list-item:active { background-color: var(--cr-searchable-drop-down-list-bg-color-active, rgba(0, 0, 0, .12)); outline: none; } </style> <!-- |value| is one-way binding on purpose so that it doesn't change immediately as the user types unless the update-value-on-input flag is explicitly used. --> <cr-input part="input" label="[[label]]" on-focus="onFocus_" on-keydown="onKeyDown_" value="[[value]]" on-input="onInput_" id="search" autofocus="[[autofocus]]" placeholder="[[placeholder]]" readonly="[[readonly]]" error-message="[[getErrorMessage_(errorMessage, errorMessageAllowed)]]" invalid="[[shouldShowErrorMessage_(errorMessage, errorMessageAllowed)]]" on-blur="onBlur_"> <div id="input-overlay" slot="suffix"> <div id="input-box"> <iron-icon id="dropdown-icon" icon="cr:arrow-drop-down"></iron-icon> </div> <div id="dropdown-box"> <iron-dropdown id="dropdown" horizontal-align="left" vertical-align="top" vertical-offset="0" no-cancel-on-outside-click no-cancel-on-esc-key> <div slot="dropdown-content"> <div id="loading-box" hidden="[[!showLoading]]"> <paper-spinner-lite active></paper-spinner-lite> <div class="cr-secondary-text">[[loadingMessage]]</div> </div> <template is="dom-repeat" items="[[items]]" filter="[[filterItems_(searchTerm_)]]"> <button class="list-item" on-click="onSelect_" tabindex="-1"> [[item]] </button> </template> </div> </iron-dropdown> </div> </div> </cr-input>
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_searchable_drop_down/cr_searchable_drop_down.html
HTML
unknown
4,649
// 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-searchable-drop-down' implements a search box with a * suggestions drop down. * * If the update-value-on-input flag is set, value will be set to whatever is * in the input box. Otherwise, value will only be set when an element in items * is clicked. * * The |invalid| property tracks whether the user's current text input in the * dropdown matches the previously saved dropdown value. This property can be * used to disable certain user actions when the dropdown is invalid. */ import '../cr_input/cr_input.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-dropdown/iron-dropdown.js'; import '//resources/polymer/v3_0/iron-icon/iron-icon.js'; import '//resources/polymer/v3_0/paper-spinner/paper-spinner-lite.js'; import {IronDropdownElement} from '//resources/polymer/v3_0/iron-dropdown/iron-dropdown.js'; import {DomRepeatEvent, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {CrInputElement} from '../cr_input/cr_input.js'; import {getTemplate} from './cr_searchable_drop_down.html.js'; export interface CrSearchableDropDownElement { $: { search: CrInputElement, dropdown: IronDropdownElement, }; } export class CrSearchableDropDownElement extends PolymerElement { static get is() { return 'cr-searchable-drop-down'; } static get template() { return getTemplate(); } static get properties() { return { autofocus: { type: Boolean, value: false, reflectToAttribute: true, }, readonly: { type: Boolean, reflectToAttribute: true, }, /** * Whether space should be left below the text field to display an error * message. Must be true for |errorMessage| to be displayed. */ errorMessageAllowed: { type: Boolean, value: false, reflectToAttribute: true, }, /** * When |errorMessage| is set, the text field is highlighted red and * |errorMessage| is displayed beneath it. */ errorMessage: String, /** * Message to display next to the loading spinner. */ loadingMessage: String, placeholder: String, /** * Used to track in real time if the |value| in cr-searchable-drop-down * matches the value in the underlying cr-input. These values will differ * after a user types in input that does not match a valid dropdown * option. |invalid| is always false when |updateValueOnInput| is set to * true. This is because when |updateValueOnInput| is set to true, we are * not setting a restrictive set of valid options. */ invalid: { type: Boolean, value: false, notify: true, }, items: { type: Array, observer: 'onItemsChanged_', }, value: { type: String, notify: true, observer: 'updateInvalid_', }, label: { type: String, value: '', }, updateValueOnInput: Boolean, showLoading: { type: Boolean, value: false, }, searchTerm_: String, dropdownRefitPending_: Boolean, /** * Whether the dropdown is currently open. Should only be used by CSS * privately. */ opened_: { type: Boolean, value: false, reflectToAttribute: true, }, }; } override autofocus: boolean; readonly: boolean; errorMessageAllowed: boolean; errorMessage: string; loadingMessage: string; placeholder: string; invalid: boolean; items: string[]; value: string; label: string; updateValueOnInput: boolean; showLoading: boolean; private searchTerm_: string; private dropdownRefitPending_: boolean; private opened_: boolean; private openDropdownTimeoutId_: number = 0; private resizeObserver_: ResizeObserver|null = null; private pointerDownListener_: (e: Event) => void; override connectedCallback() { super.connectedCallback(); this.pointerDownListener_ = this.onPointerDown_.bind(this); document.addEventListener('pointerdown', this.pointerDownListener_); this.resizeObserver_ = new ResizeObserver(() => { this.resizeDropdown_(); }); this.resizeObserver_.observe(this.$.search); } override ready() { super.ready(); this.addEventListener('mousemove', this.onMouseMove_.bind(this)); } override disconnectedCallback() { super.disconnectedCallback(); document.removeEventListener('pointerdown', this.pointerDownListener_); this.resizeObserver_!.unobserve(this.$.search); } /** * Enqueues a task to refit the iron-dropdown if it is open. */ private enqueueDropdownRefit_() { const dropdown = this.$.dropdown; if (!this.dropdownRefitPending_ && dropdown.opened) { this.dropdownRefitPending_ = true; setTimeout(() => { dropdown.refit(); this.dropdownRefitPending_ = false; }, 0); } } /** * Keeps the dropdown from expanding beyond the width of the search input when * its width is specified as a percentage. */ private resizeDropdown_() { const dropdown = this.$.dropdown.containedElement; const dropdownWidth = Math.max(dropdown.offsetWidth, this.$.search.offsetWidth); dropdown.style.width = `${dropdownWidth}px`; this.enqueueDropdownRefit_(); } private openDropdown_() { this.$.dropdown.open(); this.opened_ = true; } private closeDropdown_() { if (this.openDropdownTimeoutId_) { clearTimeout(this.openDropdownTimeoutId_); } this.$.dropdown.close(); this.opened_ = false; } /** * Enqueues a task to open the iron-dropdown. Any pending task is canceled and * a new task is enqueued. */ private enqueueOpenDropdown_() { if (this.opened_) { return; } if (this.openDropdownTimeoutId_) { clearTimeout(this.openDropdownTimeoutId_); } this.openDropdownTimeoutId_ = setTimeout(this.openDropdown_.bind(this)); } private onItemsChanged_() { // Refit the iron-dropdown so that it can expand as neccessary to // accommodate new items. Refitting is done on a new task because the change // notification might not yet have propagated to the iron-dropdown. this.enqueueDropdownRefit_(); } private onFocus_() { if (this.readonly) { return; } this.openDropdown_(); } private onMouseMove_(event: Event) { const item = event.composedPath().find(elm => { const element = elm as HTMLElement; return element.classList && element.classList.contains('list-item'); }) as HTMLElement | undefined; if (!item) { return; } // Select the item the mouse is hovering over. If the user uses the // keyboard, the selection will shift. But once the user moves the mouse, // selection should be updated based on the location of the mouse cursor. const selectedItem = this.findSelectedItem_(); if (item === selectedItem) { return; } if (selectedItem) { selectedItem.removeAttribute('selected_'); } item.setAttribute('selected_', ''); } private onPointerDown_(event: Event) { if (this.readonly) { return; } const paths = event.composedPath(); const searchInput = this.$.search.inputElement; if (paths.includes(this.$.dropdown)) { // At this point, the search input field has lost focus. Since the user // is still interacting with this element, give the search field focus. searchInput.focus(); // Prevent any other field from gaining focus due to this event. event.preventDefault(); } else if (paths.includes(searchInput)) { // A click on the search input should open the dropdown. Opening the // dropdown is done on a new task because when the IronDropdown element is // opened, it may capture and cancel the touch event, preventing the // searchInput field from receiving focus. Replacing iron-dropdown // (crbug.com/1013408) will eliminate the need for this work around. this.enqueueOpenDropdown_(); } else { // A click outside either the search input or dropdown should close the // dropdown. Implicitly, the search input has lost focus at this point. this.closeDropdown_(); } } private onKeyDown_(event: KeyboardEvent) { const dropdown = this.$.dropdown; if (!dropdown.opened) { if (this.readonly) { return; } if (event.key === 'Enter') { this.openDropdown_(); // Stop the default submit action. event.preventDefault(); } return; } event.stopPropagation(); switch (event.key) { case 'Tab': // Pressing tab will cause the input field to lose focus. Since the // dropdown visibility is tied to focus, close the dropdown. this.closeDropdown_(); break; case 'ArrowUp': case 'ArrowDown': { const selected = this.findSelectedItemIndex_(); const items = dropdown.querySelectorAll<HTMLElement>('.list-item'); if (items.length === 0) { break; } this.updateSelected_(items, selected, event.key === 'ArrowDown'); break; } case 'Enter': { const selected = this.findSelectedItem_(); if (!selected) { break; } selected.removeAttribute('selected_'); this.value = (dropdown.querySelector('dom-repeat')!.modelForElement( selected) as unknown as { item: string, }).item; this.searchTerm_ = ''; this.closeDropdown_(); // Stop the default submit action. event.preventDefault(); break; } } } /** * Finds the currently selected dropdown item. * @return Currently selected dropdown item, or undefined if no item is * selected. */ private findSelectedItem_(): HTMLElement|undefined { const items = Array.from(this.$.dropdown.querySelectorAll<HTMLElement>('.list-item')); return items.find(item => item.hasAttribute('selected_')); } /** * Finds the index of currently selected dropdown item. * @return Index of the currently selected dropdown item, or -1 if no item is * selected. */ private findSelectedItemIndex_(): number { const items = Array.from(this.$.dropdown.querySelectorAll<HTMLElement>('.list-item')); return items.findIndex(item => item.hasAttribute('selected_')); } /** * Updates the currently selected element based on keyboard up/down movement. */ private updateSelected_( items: NodeListOf<HTMLElement>, currentIndex: number, moveDown: boolean) { const numItems = items.length; let nextIndex = 0; if (currentIndex === -1) { nextIndex = moveDown ? 0 : numItems - 1; } else { const delta = moveDown ? 1 : -1; nextIndex = (numItems + currentIndex + delta) % numItems; items[currentIndex]!.removeAttribute('selected_'); } items[nextIndex]!.setAttribute('selected_', ''); // The newly selected item might not be visible because the dropdown needs // to be scrolled. So scroll the dropdown if necessary. items[nextIndex]!.scrollIntoViewIfNeeded(); } private onInput_() { this.searchTerm_ = this.$.search.value; if (this.updateValueOnInput) { this.value = this.$.search.value; } // If the user makes a change, ensure the dropdown is open. The dropdown is // closed when the user makes a selection using the mouse or keyboard. // However, focus remains on the input field. If the user makes a further // change, then the dropdown should be shown. this.openDropdown_(); // iron-dropdown sets its max-height when it is opened. If the current value // results in no filtered items in the drop down list, the iron-dropdown // will have a max-height for 0 items. If the user then clears the input // field, a non-zero number of items might be displayed in the drop-down, // but the height is still limited based on 0 items. This results in a tiny, // but scollable dropdown. Refitting the dropdown allows it to expand to // accommodate the new items. this.enqueueDropdownRefit_(); // Need check to if the input is valid when the user types. this.updateInvalid_(); } private onSelect_(event: DomRepeatEvent<string>) { this.closeDropdown_(); this.value = event.model.item; this.searchTerm_ = ''; const selected = this.findSelectedItem_(); if (selected) { // Reset the selection state. selected.removeAttribute('selected_'); } } private filterItems_(searchTerm: string): ((s: string) => boolean)|null { if (!searchTerm) { return null; } return function(item) { return item.toLowerCase().includes(searchTerm.toLowerCase()); }; } private shouldShowErrorMessage_( errorMessage: string, errorMessageAllowed: boolean): boolean { return !!this.getErrorMessage_(errorMessage, errorMessageAllowed); } private getErrorMessage_(errorMessage: string, errorMessageAllowed: boolean): string { if (!errorMessageAllowed) { return ''; } return errorMessage; } /** * This makes sure to reset the text displayed in the dropdown to the actual * value in the cr-input for the use case where a user types in an invalid * option then changes focus from the dropdown. This behavior is only for when * updateValueOnInput is false. When updateValueOnInput is true, it is ok to * leave the user's text in the dropdown search bar when focus is changed. */ private onBlur_() { if (!this.updateValueOnInput) { this.$.search.value = this.value; } // Need check to if the input is valid when the dropdown loses focus. this.updateInvalid_(); } /** * If |updateValueOnInput| is true then any value is allowable so always set * |invalid| to false. */ private updateInvalid_() { this.invalid = !this.updateValueOnInput && (this.value !== this.$.search.value); } } declare global { interface HTMLElementTagNameMap { 'cr-searchable-drop-down': CrSearchableDropDownElement; } } customElements.define( CrSearchableDropDownElement.is, CrSearchableDropDownElement);
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_searchable_drop_down/cr_searchable_drop_down.ts
TypeScript
unknown
14,699
/* 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_hidden_style.css.js * #import=./cr_icons.css.js * #scheme=relative * #include=cr-hidden-style cr-icons * #css_wrapper_metadata_end */ html, :host { --scrollable-border-color: var(--google-grey-300); } @media (prefers-color-scheme: dark) { html, :host { --scrollable-border-color: var(--google-grey-700); } } [actionable] { cursor: pointer; } /* Horizontal rule line. */ .hr { border-top: var(--cr-separator-line); } iron-list.cr-separators > *:not([first]) { border-top: var(--cr-separator-line); } [scrollable] { border-color: transparent; border-style: solid; border-width: 1px 0; overflow-y: auto; } [scrollable].is-scrolled { border-top-color: var(--scrollable-border-color); } [scrollable].can-scroll:not(.scrolled-to-bottom) { border-bottom-color: var(--scrollable-border-color); } [scrollable] iron-list > :not(.no-outline):focus, [selectable]:focus, [selectable] > :focus { background-color: var(--cr-focused-item-color); outline: none; } .scroll-container { display: flex; flex-direction: column; min-height: 1px; } [selectable] > * { cursor: pointer; } .cr-centered-card-container { box-sizing: border-box; display: block; height: inherit; margin: 0 auto; max-width: var(--cr-centered-card-max-width); min-width: 550px; position: relative; width: calc(100% * var(--cr-centered-card-width-percentage)); } .cr-container-shadow { box-shadow: inset 0 5px 6px -3px rgba(0, 0, 0, .4); height: var(--cr-container-shadow-height); left: 0; margin: 0 0 var(--cr-container-shadow-margin); opacity: 0; pointer-events: none; position: relative; right: 0; top: 0; transition: opacity 500ms; z-index: 1; } /** Styles for elements that implement the CrContainerShadowBehavior */ #cr-container-shadow-bottom { margin-bottom: 0; margin-top: var(--cr-container-shadow-margin); transform: scaleY(-1); } #cr-container-shadow-top.has-shadow, #cr-container-shadow-bottom.has-shadow { opacity: var(--cr-container-shadow-max-opacity); } .cr-row { align-items: center; border-top: var(--cr-separator-line); display: flex; min-height: var(--cr-section-min-height); padding: 0 var(--cr-section-padding); } .cr-row.first, .cr-row.continuation { border-top: none; } .cr-row-gap { padding-inline-start: 16px; } .cr-button-gap { margin-inline-start: 8px; } paper-tooltip::part(tooltip) { border-radius: var(--paper-tooltip-border-radius, 2px); font-size: 92.31%; /* Effectively 12px if the host default is 13px. */ font-weight: 500; max-width: 330px; min-width: var(--paper-tooltip-min-width, 200px); padding: var(--paper-tooltip-padding, 10px 8px); } /* Typography */ .cr-padded-text { padding-block-end: var(--cr-section-vertical-padding); padding-block-start: var(--cr-section-vertical-padding); } .cr-title-text { color: var(--cr-title-text-color); font-size: 107.6923%; /* Go to 14px from 13px. */ font-weight: 500; } .cr-secondary-text { color: var(--cr-secondary-text-color); font-weight: 400; } .cr-form-field-label { color: var(--cr-form-field-label-color); display: block; font-size: var(--cr-form-field-label-font-size); font-weight: 500; letter-spacing: .4px; line-height: var(--cr-form-field-label-line-height); margin-bottom: 8px; } .cr-vertical-tab { align-items: center; display: flex; } .cr-vertical-tab::before { border-radius: 0 3px 3px 0; content: ''; display: block; flex-shrink: 0; height: var(--cr-vertical-tab-height, 100%); width: 4px; } .cr-vertical-tab.selected::before { background: var(--cr-vertical-tab-selected-color, var(--cr-checked-color)); } :host-context([dir=rtl]) .cr-vertical-tab::before { /* Border-radius based on block/inline is not yet supported. */ transform: scaleX(-1); } .iph-anchor-highlight { background-color: var(--cr-iph-anchor-highlight-color); }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_shared_style.css
CSS
unknown
4,122
/* 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=//resources/polymer/v3_0/paper-styles/color.js * #scheme=relative * #css_wrapper_metadata_end */ /* Common css variables for Material Design WebUI */ html { --google-blue-50-rgb: 232, 240, 254; /* #e8f0fe */ --google-blue-50: rgb(var(--google-blue-50-rgb)); --google-blue-100-rgb: 210, 227, 252; /* #d2e3fc */ --google-blue-100: rgb(var(--google-blue-100-rgb)); --google-blue-200-rgb: 174, 203, 250; /* #aecbfa */ --google-blue-200: rgb(var(--google-blue-200-rgb)); --google-blue-300-rgb: 138, 180, 248; /* #8ab4f8 */ --google-blue-300: rgb(var(--google-blue-300-rgb)); --google-blue-400-rgb: 102, 157, 246; /* #669df6 */ --google-blue-400: rgb(var(--google-blue-400-rgb)); --google-blue-500-rgb: 66, 133, 244; /* #4285f4 */ --google-blue-500: rgb(var(--google-blue-500-rgb)); --google-blue-600-rgb: 26, 115, 232; /* #1a73e8 */ --google-blue-600: rgb(var(--google-blue-600-rgb)); --google-blue-700-rgb: 25, 103, 210; /* #1967d2 */ --google-blue-700: rgb(var(--google-blue-700-rgb)); --google-blue-800-rgb: 24, 90, 188; /* #185abc */ --google-blue-800: rgb(var(--google-blue-800-rgb)); --google-blue-900-rgb: 23, 78, 166; /* #174ea6 */ --google-blue-900: rgb(var(--google-blue-900-rgb)); --google-green-50-rgb: 230, 244, 234; /* #e6f4ea */ --google-green-50: rgb(var(--google-green-50-rgb)); --google-green-200-rgb: 168, 218, 181; /* #a8dab5 */ --google-green-200: rgb(var(--google-green-200-rgb)); --google-green-300-rgb: 129, 201, 149; /* #81c995 */ --google-green-300: rgb(var(--google-green-300-rgb)); --google-green-400-rgb: 91, 185, 116; /* #5bb974 */ --google-green-400: rgb(var(--google-green-400-rgb)); --google-green-500-rgb: 52, 168, 83; /* #34a853 */ --google-green-500: rgb(var(--google-green-500-rgb)); --google-green-600-rgb: 30, 142, 62; /* #1e8e3e */ --google-green-600: rgb(var(--google-green-600-rgb)); --google-green-700-rgb: 24, 128, 56; /* #188038 */ --google-green-700: rgb(var(--google-green-700-rgb)); --google-green-800-rgb: 19, 115, 51; /* #137333 */ --google-green-800: rgb(var(--google-green-800-rgb)); --google-green-900-rgb: 13, 101, 45; /* #0d652d */ --google-green-900: rgb(var(--google-green-900-rgb)); --google-grey-50-rgb: 248, 249, 250; /* #f8f9fa */ --google-grey-50: rgb(var(--google-grey-50-rgb)); --google-grey-100-rgb: 241, 243, 244; /* #f1f3f4 */ --google-grey-100: rgb(var(--google-grey-100-rgb)); --google-grey-200-rgb: 232, 234, 237; /* #e8eaed */ --google-grey-200: rgb(var(--google-grey-200-rgb)); --google-grey-300-rgb: 218, 220, 224; /* #dadce0 */ --google-grey-300: rgb(var(--google-grey-300-rgb)); --google-grey-400-rgb: 189, 193, 198; /* #bdc1c6 */ --google-grey-400: rgb(var(--google-grey-400-rgb)); --google-grey-500-rgb: 154, 160, 166; /* #9aa0a6 */ --google-grey-500: rgb(var(--google-grey-500-rgb)); --google-grey-600-rgb: 128, 134, 139; /* #80868b */ --google-grey-600: rgb(var(--google-grey-600-rgb)); --google-grey-700-rgb: 95, 99, 104; /* #5f6368 */ --google-grey-700: rgb(var(--google-grey-700-rgb)); --google-grey-800-rgb: 60, 64, 67; /* #3c4043 */ --google-grey-800: rgb(var(--google-grey-800-rgb)); --google-grey-900-rgb: 32, 33, 36; /* #202124 */ --google-grey-900: rgb(var(--google-grey-900-rgb)); /* --google-grey-900 + 4% white blended together. */ --google-grey-900-white-4-percent: #292a2d; --google-purple-200-rgb: 215, 174, 251; /* #d7aefb */ --google-purple-200: rgb(var(--google-purple-200-rgb)); --google-purple-900-rgb: 104, 29, 168; /* #681da8 */ --google-purple-900: rgb(var(--google-purple-900-rgb)); --google-red-300-rgb: 242, 139, 130; /* #f28b82 */ --google-red-300: rgb(var(--google-red-300-rgb)); --google-red-500-rgb: 234, 67, 53; /* #ea4335 */ --google-red-500: rgb(var(--google-red-500-rgb)); --google-red-600-rgb: 217, 48, 37; /* #d93025 */ --google-red-600: rgb(var(--google-red-600-rgb)); --google-yellow-50-rgb: 254, 247, 224; /* #fef7e0 */ --google-yellow-50: rgb(var(--google-yellow-50-rgb)); --google-yellow-200-rgb: 253, 226, 147; /* #fde293 */ --google-yellow-200: rgb(var(--google-yellow-200-rgb)); --google-yellow-300-rgb: 253, 214, 51; /* #fdd633 */ --google-yellow-300: rgb(var(--google-yellow-300-rgb)); --google-yellow-400-rgb: 252, 201, 52; /* #fcc934 */ --google-yellow-400: rgb(var(--google-yellow-400-rgb)); --google-yellow-500-rgb: 251, 188, 4; /* #fbbc04 */ --google-yellow-500: rgb(var(--google-yellow-500-rgb)); --cr-primary-text-color: var(--google-grey-900); --cr-secondary-text-color: var(--google-grey-700); --cr-card-background-color: white; --cr-card-shadow-color-rgb: var(--google-grey-800-rgb); --cr-elevation-1: rgba(var(--cr-card-shadow-color-rgb), .3) 0 1px 2px 0, rgba(var(--cr-card-shadow-color-rgb), .15) 0 1px 3px 1px; --cr-elevation-2: rgba(var(--cr-card-shadow-color-rgb), .3) 0 1px 2px 0, rgba(var(--cr-card-shadow-color-rgb), .15) 0 2px 6px 2px; --cr-elevation-3: rgba(var(--cr-card-shadow-color-rgb), .3) 0 1px 3px 0, rgba(var(--cr-card-shadow-color-rgb), .15) 0 4px 8px 3px; --cr-elevation-4: rgba(var(--cr-card-shadow-color-rgb), .3) 0 2px 3px 0, rgba(var(--cr-card-shadow-color-rgb), .15) 0 6px 10px 4px; --cr-elevation-5: rgba(var(--cr-card-shadow-color-rgb), .3) 0 4px 4px 0, rgba(var(--cr-card-shadow-color-rgb), .15) 0 8px 12px 6px; --cr-card-shadow: var(--cr-elevation-2); --cr-checked-color: var(--google-blue-600); --cr-focused-item-color: var(--google-grey-300); --cr-form-field-label-color: var(--google-grey-700); --cr-hairline-rgb: 0, 0, 0; --cr-iph-anchor-highlight-color: rgba(var(--google-blue-600-rgb), 0.1); --cr-link-color: var(--google-blue-700); --cr-menu-background-color: white; --cr-menu-background-focus-color: var(--google-grey-400); --cr-menu-shadow: 0 2px 6px var(--paper-grey-500); --cr-separator-color: rgba(0, 0, 0, .06); --cr-title-text-color: rgb(90, 90, 90); --cr-toolbar-background-color: white; --cr-hover-background-color: rgba(var(--google-grey-900-rgb), .1); --cr-active-background-color: rgba(var(--google-grey-900-rgb), .16); --cr-focus-outline-color: rgba(var(--google-blue-600-rgb), .4); } @media (prefers-color-scheme: dark) { html { --cr-primary-text-color: var(--google-grey-200); --cr-secondary-text-color: var(--google-grey-500); --cr-card-background-color: var(--google-grey-900-white-4-percent); --cr-card-shadow-color-rgb: 0, 0, 0; --cr-checked-color: var(--google-blue-300); --cr-focused-item-color: var(--google-grey-800); --cr-form-field-label-color: var(--dark-secondary-color); --cr-hairline-rgb: 255, 255, 255; --cr-iph-anchor-highlight-color: rgba(var(--google-grey-100-rgb), 0.1); --cr-link-color: var(--google-blue-300); --cr-menu-background-color: var(--google-grey-900); --cr-menu-background-focus-color: var(--google-grey-700); --cr-menu-background-sheen: rgba(255, 255, 255, .06); /* Only dark mode. */ --cr-menu-shadow: rgba(0, 0, 0, .3) 0 1px 2px 0, rgba(0, 0, 0, .15) 0 3px 6px 2px; --cr-separator-color: rgba(255, 255, 255, .1); --cr-title-text-color: var(--cr-primary-text-color); --cr-toolbar-background-color: var(--google-grey-900-white-4-percent); --cr-hover-background-color: rgba(255, 255, 255, .1); --cr-active-background-color: rgba(var(--google-grey-200-rgb), .16); --cr-focus-outline-color: rgba(var(--google-blue-300-rgb), .4); } } @media (forced-colors: active) { html { /* In Windows HCM, |box-shadow| is not showing. The suggested workaround is to use |outline| or |border| instead. The color does not matter, since it is forced by the OS so using 'transparent'. */ --cr-focus-outline-hcm: 2px solid transparent; --cr-border-hcm: 2px solid transparent; } } /* Don't use color values past this point. Instead, create a variable that's * set for both light and dark modes and use a single variable below. */ html { --cr-button-edge-spacing: 12px; --cr-button-height: 32px; /* Spacing between policy (controlledBy) indicator and control. */ --cr-controlled-by-spacing: 24px; /* Default max-width for input fields */ --cr-default-input-max-width: 264px; /* The inner icon is 20px in size. The button has 8px * 2 padding. */ --cr-icon-ripple-size: 36px; --cr-icon-ripple-padding: 8px; --cr-icon-size: 20px; --cr-icon-button-margin-start: 16px; /* Shift button so ripple overlaps the end of the row. */ --cr-icon-ripple-margin: calc(var(--cr-icon-ripple-padding) * -1); /* TODO (johntlee): re-implement with paddings instead; */ /* These are used for row items such as radio buttons, check boxes, list * items etc. */ --cr-section-min-height: 48px; --cr-section-two-line-min-height: 64px; --cr-section-padding: 20px; --cr-section-vertical-padding: 12px; --cr-section-indent-width: 40px; --cr-section-indent-padding: calc( var(--cr-section-padding) + var(--cr-section-indent-width)); --cr-section-vertical-margin: 21px; --cr-centered-card-max-width: 680px; --cr-centered-card-width-percentage: 0.96; --cr-hairline: 1px solid rgba(var(--cr-hairline-rgb), .14); --cr-separator-height: 1px; --cr-separator-line: var(--cr-separator-height) solid var(--cr-separator-color); --cr-toolbar-overlay-animation-duration: 150ms; --cr-toolbar-height: 56px; --cr-container-shadow-height: 6px; --cr-container-shadow-margin: calc(-1 * var(--cr-container-shadow-height)); --cr-container-shadow-max-opacity: 1; /** MD Refresh Styles */ --cr-card-border-radius: 8px; --cr-disabled-opacity: .38; --cr-form-field-bottom-spacing: 16px; --cr-form-field-label-font-size: .625rem; --cr-form-field-label-height: 1em; --cr-form-field-label-line-height: 1; } html[chrome-refresh-2023] { /* Colors: These variables should never be overridden and should only be used as fallback values for shared cr_elements or in UIs that do not have the color pipeline. */ --cr-fallback-color-outline: rgb(116, 119, 117); --cr-fallback-color-primary: rgb(11, 87, 208); --cr-fallback-color-on-primary: rgb(255, 255, 255); --cr-fallback-color-primary-container: rgb(211, 227, 253); --cr-fallback-color-on-primary-container: rgb(4, 30, 73); --cr-fallback-color-secondary-container: rgb(194, 231, 255); --cr-fallback-color-on-secondary-container: rgb(0, 29, 53); --cr-fallback-color-neutral-container: rgb(242, 242, 242); --cr-fallback-color-surface: rgb(255, 255, 255); --cr-fallback-color-on-surface-rgb: 31, 31, 31; --cr-fallback-color-on-surface: rgb(var(--cr-fallback-color-on-surface-rgb)); --cr-fallback-color-surface-variant: rgb(225, 227, 225); --cr-fallback-color-on-surface-variant: rgb(68, 71, 70); --cr-fallback-color-tonal-outline: rgb(168, 199, 250); /* States */ --cr-hover-background-color: var(--color-sys-state-hover, rgba(var(--cr-fallback-color-on-surface-rgb), .08)); --cr-active-background-color: var(--color-sys-state-pressed, rgba(var(--cr-fallback-color-on-surface-rgb), .12)); --cr-focus-outline-color: var(--color-sys-state-focus-ring, var(--cr-fallback-color-primary)); /* Typography */ --cr-primary-text-color: var(--color-primary-foreground, var(--cr-fallback-color-on-surface)); --cr-secondary-text-color: var(--color-secondary-foreground, var(--cr-fallback-color-on-surface-variant)); /* Layout */ --cr-button-height: 36px; } @media (prefers-color-scheme: dark) { html[chrome-refresh-2023] { /* Colors */ --cr-fallback-color-outline: rgb(142, 145, 143); --cr-fallback-color-primary: rgb(168, 199, 250); --cr-fallback-color-on-primary: rgb(6, 46, 111); --cr-fallback-color-primary-container: rgb(8, 66, 160); --cr-fallback-color-on-primary-container: rgb(211, 227, 253); --cr-fallback-color-secondary-container: rgb(0, 74, 119); --cr-fallback-color-on-secondary-container: rgb(194, 231, 255); --cr-fallback-color-neutral-container: rgb(42, 42, 42); --cr-fallback-color-surface: rgb(26, 27, 30); --cr-fallback-color-on-surface-rgb: 227, 227, 227; --cr-fallback-color-surface-variant: rgb(68, 71, 70); --cr-fallback-color-on-surface-variant: rgb(196, 199, 197); --cr-fallback-color-tonal-outline: rgb(0, 99, 155); } }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_shared_vars.css
CSS
unknown
12,685
<style include="cr-hidden-style"> :host { --cr-slider-active-color: var(--google-blue-600); --cr-slider-container-color: rgba(var(--google-blue-600-rgb), .24); --cr-slider-container-disabled-color: rgba(var(--google-grey-600-rgb), .24); --cr-slider-disabled-color: var(--google-grey-600); --cr-slider-knob-color-rgb: var(--google-blue-600-rgb); --cr-slider-knob-disabled-color: white; --cr-slider-marker-active-color: rgba(255, 255, 255, .54); --cr-slider-marker-color: rgba(26, 115, 232, .54); --cr-slider-marker-disabled-color: rgba(128, 134, 139, .54); --cr-slider-position-transition: 80ms ease; --cr-slider-ripple-color: rgba(var(--cr-slider-knob-color-rgb), .25); -webkit-tap-highlight-color: rgba(0, 0, 0, 0); cursor: default; height: 32px; outline: none; padding: 0 16px; user-select: none; } @media (prefers-color-scheme: dark) { :host { --cr-slider-active-color: var(--google-blue-300); --cr-slider-container-color: rgba(var(--google-blue-500-rgb), .48); --cr-slider-container-disabled-color: rgba(var(--google-grey-600-rgb), .48); /* --cr-slider-disabled-color is the same in dark mode (GG600). */ --cr-slider-knob-color-rgb: var(--google-blue-300-rgb); --cr-slider-knob-disabled-color: var(--google-grey-900-white-4-percent); --cr-slider-marker-active-color: var(--google-blue-300); --cr-slider-marker-color: var(--google-blue-300); --cr-slider-marker-disabled-color: rgba(255, 255, 255, .54); --cr-slider-ripple-color: rgba(var(--cr-slider-knob-color-rgb), .4); } } /* Disable browser touch actions so that dragging via touch works correctly. */ /* TODO(crbug/1068914): For reasons I don't understand we need to set touch-action: none on the container for sliders inside dialogs and on the host for sliders not in dialogs. If we don't, then you can't drag the slider via touch (mouse works fine).*/ :host, :host > #container { touch-action: none; } #container, #bar { /* Using border instead of background-color to address pixel rounding at low zoom levels (e.g. 33%). The browser will round border widths to a minimum of 1px.*/ border-top-style: solid; border-top-width: 2px; } #container { border-top-color: var(--cr-slider-container-color); position: relative; top: 16px; } #container > div { position: absolute; } #markers, #bar { top: -2px; } #markers { display: flex; flex-direction: row; left: 0; pointer-events: none; right: 0; } .active-marker, .inactive-marker { flex: 1; } #markers::before, #markers::after, .active-marker::after, .inactive-marker::after { border-radius: 50%; content: ''; display: block; height: 2px; margin-inline-start: -1px; width: 2px; } #markers::before, .active-marker::after { background-color: var(--cr-slider-marker-active-color); } #markers::after, .inactive-marker::after { background-color: var(--cr-slider-marker-color); } #bar { border-top-color: var(--cr-slider-active-color); } :host([transiting_]) #bar { transition: width var(--cr-slider-position-transition); } #knobAndLabel { top: -1px; } :host([transiting_]) #knobAndLabel { transition: margin-inline-start var(--cr-slider-position-transition); } #knob { background-color: rgb(var(--cr-slider-knob-color-rgb)); border-radius: 50%; box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .4); height: 10px; outline: none; transform: translate(-50%, -50%); width: 10px; } :host([is-rtl_]) #knob { transform: translate(50%, -50%); } #label { background: rgb(var(--cr-slider-knob-color-rgb)); border-radius: .75em; bottom: 22px; color: white; /* Same for dark and light mode. */ font-size: 12px; line-height: 1.5em; opacity: 0; /* TODO(crbug.com/980856): Remove workaround after rendering bug is * fixed. */ outline: 1px transparent solid; padding: 0 .67em; position: absolute; transform: translateX(-50%); transition: opacity 80ms ease-in-out; white-space: nowrap; } :host([is-rtl_]) #label { transform: translateX(50%); } :host(:hover) #label, :host([show-label_]) #label { opacity: 1; } paper-ripple { --paper-ripple-opacity: 1; /* Opacity in each color's alpha. */ color: var(--cr-slider-ripple-color); height: 32px; left: -11px; pointer-events: none; top: -11px; transition: color linear 80ms; width: 32px; } :host([is-rtl_]) paper-ripple { left: auto; right: -11px; } :host([disabled_]) { pointer-events: none; } :host([disabled_]) #container { border-top-color: var(--cr-slider-container-disabled-color); } :host([disabled_]) #bar { border-top-color: var(--cr-slider-disabled-color); } :host([disabled_]) .inactive-marker::after, :host([disabled_]) #markers::after { background-color: var(--cr-slider-marker-disabled-color); } :host([disabled_]) #knob { background-color: var(--cr-slider-disabled-color); border: 2px solid var(--cr-slider-knob-disabled-color); box-shadow: unset; } </style> <div id="container" hidden> <div id="bar"></div> <div id="markers" hidden$="[[!markerCount]]"> <template is="dom-repeat" items="[[getMarkers_(markerCount)]]"> <div class$="[[getMarkerClass_(index, value, min, max, markerCount)]]"></div> </template> </div> <div id="knobAndLabel" on-transitionend="onTransitionEnd_"> <div id="knob" part="knob"></div> <div id="label" part="label">[[label_]]</div> </div> </div>
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_slider/cr_slider.html
HTML
unknown
6,589
// 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-slider' is a slider component used to select a number from * a continuous or discrete range of numbers. */ import '../cr_hidden_style.css.js'; import '../cr_shared_vars.css.js'; import {assert} from '//resources/js/assert_ts.js'; import {EventTracker} from '//resources/js/event_tracker.js'; import {PaperRippleBehavior} from '//resources/polymer/v3_0/paper-behaviors/paper-ripple-behavior.js'; import {Debouncer, microTask, mixinBehaviors, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {getTemplate} from './cr_slider.html.js'; /** * The |value| is the corresponding value that the current slider tick is * associated with. The string |label| is shown in the UI as the label for the * current slider value. The |ariaValue| number is used for aria-valuemin, * aria-valuemax, and aria-valuenow, and is optional. If missing, |value| will * be used instead. */ export interface SliderTick { value: number; label: string; ariaValue?: number; } function clamp(min: number, max: number, value: number): number { return Math.min(max, Math.max(min, value)); } function getAriaValue(tick: SliderTick|number): number { if (Number.isFinite(tick as number)) { return tick as number; } const sliderTick = tick as SliderTick; return sliderTick.ariaValue !== undefined ? sliderTick.ariaValue! : sliderTick.value; } const CrSliderElementBase = mixinBehaviors([PaperRippleBehavior], PolymerElement) as {new (): PolymerElement & PaperRippleBehavior}; /** * The following are the events emitted from cr-slider. * * cr-slider-value-changed: fired when updating slider via the UI. * dragging-changed: fired on pointer down and on pointer up. */ export interface CrSliderElement { $: { bar: HTMLElement, container: HTMLElement, knobAndLabel: HTMLElement, knob: HTMLElement, }; } export class CrSliderElement extends CrSliderElementBase { static get is() { return 'cr-slider'; } static get template() { return getTemplate(); } static get properties() { return { disabled: { type: Boolean, value: false, }, /** * Internal representation of disabled depending on |disabled| and * |ticks|. */ disabled_: { type: Boolean, computed: 'computeDisabled_(disabled, ticks.*)', reflectToAttribute: true, observer: 'onDisabledChanged_', }, dragging: { type: Boolean, value: false, notify: true, }, updatingFromKey: { type: Boolean, value: false, notify: true, }, /** * The amount the slider value increments by when pressing any of the keys * from `deltaKeyMap_`. Defaults to 1. */ keyPressSliderIncrement: { type: Number, value: 1, }, markerCount: { type: Number, value: 0, }, max: { type: Number, value: 100, }, min: { type: Number, value: 0, }, /** * When set to false, the keybindings are not handled by this component, * for example when the owner of the component wants to set up its own * keybindings. */ noKeybindings: { type: Boolean, value: false, }, snaps: { type: Boolean, value: false, }, /** * The data associated with each tick on the slider. Each element in the * array contains a value and the label corresponding to that value. */ ticks: { type: Array, value: () => [], }, value: Number, label_: { type: String, value: '', }, showLabel_: { type: Boolean, value: false, reflectToAttribute: true, }, isRtl_: { type: Boolean, value: false, reflectToAttribute: true, }, /** * |transiting_| is set to true when bar is touched or clicked. This * triggers a single position transition effect to take place for the * knob, bar and label. When the transition is complete, |transiting_| is * set to false resulting in no transition effect during dragging, manual * value updates and keyboard events. */ transiting_: { type: Boolean, value: false, reflectToAttribute: true, }, }; } static get observers() { return [ 'onTicksChanged_(ticks.*)', 'updateUi_(ticks.*, value, min, max)', 'onValueMinMaxChange_(value, min, max)', 'buildDeltaKeyMap_(isRtl_, keyPressSliderIncrement)', ]; } disabled: boolean; dragging: boolean; updatingFromKey: boolean; keyPressSliderIncrement: number; markerCount: number; max: number; min: number; noKeybindings: boolean; snaps: boolean; ticks: SliderTick[]|number[]; value: number; private disabled_: boolean; private label_: string; private showLabel_: boolean; private isRtl_: boolean; private transiting_: boolean; private deltaKeyMap_: Map<string, number>|null = null; private draggingEventTracker_: EventTracker|null = null; private debouncer_: Debouncer; /* eslint-disable-next-line @typescript-eslint/naming-convention */ override _rippleContainer: Element; override ready() { super.ready(); this.setAttribute('role', 'slider'); this.addEventListener('blur', this.hideRipple_); this.addEventListener('focus', this.showRipple_); this.addEventListener('keydown', this.onKeyDown_); this.addEventListener('keyup', this.onKeyUp_); this.addEventListener('pointerdown', this.onPointerDown_.bind(this)); } override connectedCallback() { super.connectedCallback(); this.isRtl_ = window.getComputedStyle(this)['direction'] === 'rtl'; this.draggingEventTracker_ = new EventTracker(); } private fire_(eventName: string, detail?: any) { this.dispatchEvent( new CustomEvent(eventName, {bubbles: true, composed: true, detail})); } private computeDisabled_(): boolean { return this.disabled || this.ticks.length === 1; } /** * When markers are displayed on the slider, they are evenly spaced across * the entire slider bar container and are rendered on top of the bar and * bar container. The location of the marks correspond to the discrete * values that the slider can have. * @return The array items have no type since this is used to * create |markerCount| number of markers. */ private getMarkers_<T>(): T[] { return new Array(Math.max(0, this.markerCount - 1)); } private getMarkerClass_(index: number): string { const currentStep = (this.markerCount - 1) * this.getRatio(); return index < currentStep ? 'active-marker' : 'inactive-marker'; } /** * The ratio is a value from 0 to 1.0 corresponding to a location along the * slider bar where 0 is the minimum value and 1.0 is the maximum value. * This is a helper function used to calculate the bar width, knob location * and label location. */ getRatio(): number { return (this.value - this.min) / (this.max - this.min); } /** * Removes all event listeners related to dragging, and cancels ripple. */ private stopDragging_(pointerId: number) { this.draggingEventTracker_!.removeAll(); this.releasePointerCapture(pointerId); this.dragging = false; this.hideRipple_(); } private hideRipple_() { this.getRipple().clear(); this.showLabel_ = false; } private showRipple_() { this.getRipple().showAndHoldDown(); this.showLabel_ = true; } private onDisabledChanged_() { this.setAttribute('tabindex', this.disabled_ ? '-1' : '0'); this.blur(); } private onKeyDown_(event: KeyboardEvent) { if (this.disabled_ || this.noKeybindings) { return; } if (event.metaKey || event.shiftKey || event.altKey || event.ctrlKey) { return; } let newValue: number|undefined; if (event.key === 'Home') { newValue = this.min; } else if (event.key === 'End') { newValue = this.max; } else if (this.deltaKeyMap_!.has(event.key)) { newValue = this.value + this.deltaKeyMap_!.get(event.key)!; } if (newValue === undefined) { return; } this.updatingFromKey = true; if (this.updateValue_(newValue)) { this.fire_('cr-slider-value-changed'); } event.preventDefault(); event.stopPropagation(); this.showRipple_(); } private onKeyUp_(event: KeyboardEvent) { if (event.key === 'Home' || event.key === 'End' || this.deltaKeyMap_!.has(event.key)) { setTimeout(() => { this.updatingFromKey = false; }); } } /** * When the left-mouse button is pressed, the knob location is updated and * dragging starts. */ private onPointerDown_(event: PointerEvent) { if (this.disabled_ || event.buttons !== 1 && event.pointerType === 'mouse') { return; } this.dragging = true; this.transiting_ = true; this.updateValueFromClientX_(event.clientX); this.showRipple_(); this.setPointerCapture(event.pointerId); const stopDragging = this.stopDragging_.bind(this, event.pointerId); assert(!!this.draggingEventTracker_); this.draggingEventTracker_.add(this, 'pointermove', (e: PointerEvent) => { // Prevent unwanted text selection to occur while moving the pointer, // this is important. e.preventDefault(); // If the left-button on the mouse is pressed by itself, then update. // Otherwise stop capturing the mouse events because the drag operation // is complete. if (e.buttons !== 1 && e.pointerType === 'mouse') { stopDragging(); return; } this.updateValueFromClientX_(e.clientX); }); this.draggingEventTracker_.add(this, 'pointercancel', stopDragging); this.draggingEventTracker_.add(this, 'pointerdown', stopDragging); this.draggingEventTracker_.add(this, 'pointerup', stopDragging); this.draggingEventTracker_.add(this, 'keydown', (e: KeyboardEvent) => { if (e.key === 'Escape' || e.key === 'Tab' || e.key === 'Home' || e.key === 'End' || this.deltaKeyMap_!.has(e.key)) { stopDragging(); } }); } private onTicksChanged_() { if (this.ticks.length > 1) { this.snaps = true; this.max = this.ticks.length - 1; this.min = 0; } if (this.value !== undefined) { this.updateValue_(this.value); } } private onTransitionEnd_() { this.transiting_ = false; } private onValueMinMaxChange_() { this.debouncer_ = Debouncer.debounce(this.debouncer_, microTask, () => { if (this.value === undefined || this.min === undefined || this.max === undefined) { return; } this.updateValue_(this.value); }); } private updateUi_() { const percent = `${this.getRatio() * 100}%`; this.$.bar.style.width = percent; this.$.knobAndLabel.style.marginInlineStart = percent; const ticks = this.ticks; const value = this.value; if (ticks && ticks.length > 0 && Number.isInteger(value) && value >= 0 && value < ticks.length) { const tick = ticks[this.value]!; this.label_ = Number.isFinite(tick) ? '' : (tick as SliderTick).label; const ariaValueNow = getAriaValue(tick); this.setAttribute('aria-valuetext', String(this.label_ || ariaValueNow)); this.setAttribute('aria-valuenow', ariaValueNow.toString()); this.setAttribute('aria-valuemin', getAriaValue(ticks[0]!).toString()); this.setAttribute( 'aria-valuemax', getAriaValue(ticks.slice(-1)[0]!).toString()); } else { this.setAttribute( 'aria-valuetext', value !== undefined ? value.toString() : ''); this.setAttribute( 'aria-valuenow', value !== undefined ? value.toString() : ''); this.setAttribute('aria-valuemin', this.min.toString()); this.setAttribute('aria-valuemax', this.max.toString()); } } private updateValue_(value: number): boolean { this.$.container.hidden = false; if (this.snaps) { // Skip update if |value| has not passed the next value .8 units away. // The value will update as the drag approaches the next value. if (Math.abs(this.value - value) < .8) { return false; } value = Math.round(value); } value = clamp(this.min, this.max, value); if (this.value === value) { return false; } this.value = value; return true; } private updateValueFromClientX_(clientX: number) { const rect = this.$.container.getBoundingClientRect(); let ratio = (clientX - rect.left) / rect.width; if (this.isRtl_) { ratio = 1 - ratio; } if (this.updateValue_(ratio * (this.max - this.min) + this.min)) { this.fire_('cr-slider-value-changed'); } } private buildDeltaKeyMap_() { const increment = this.keyPressSliderIncrement; const decrement = -this.keyPressSliderIncrement; this.deltaKeyMap_ = new Map([ ['ArrowDown', decrement], ['ArrowUp', increment], ['PageDown', decrement], ['PageUp', increment], ['ArrowLeft', this.isRtl_ ? increment : decrement], ['ArrowRight', this.isRtl_ ? decrement : increment], ]); } // Overridden from PaperRippleBehavior /* eslint-disable-next-line @typescript-eslint/naming-convention */ override _createRipple() { this._rippleContainer = this.$.knob; const ripple = super._createRipple(); ripple.id = 'ink'; ripple.setAttribute('recenters', ''); ripple.classList.add('circle', 'toggle-ink'); return ripple; } } declare global { interface HTMLElementTagNameMap { 'cr-slider': CrSliderElement; } } customElements.define(CrSliderElement.is, CrSliderElement);
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_slider/cr_slider.ts
TypeScript
unknown
14,141
// 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 {{ * value: number, * label: string, * ariaValue: (number|undefined), * }} */ let SliderTick; /** * @constructor * @extends {HTMLElement} */ function CrSliderElement() {} /** @type {number} */ CrSliderElement.prototype.value; /** @type {!Array<!SliderTick>|!Array<number>} */ CrSliderElement.prototype.ticks;
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_slider/cr_slider_externs.js
JavaScript
unknown
611
// 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 {assert} from '//resources/js/assert_ts.js'; export class CrSplitterElement extends HTMLElement { static get is() { return 'cr-splitter'; } private handlers_: Map<string, (e: any) => void>|null = null; private startX_: number = 0; private startWidth_: number = -1; resizeNextElement: boolean = false; constructor() { super(); this.addEventListener('mousedown', e => this.onMouseDown_(e)); this.addEventListener('touchstart', e => this.onTouchStart_(e)); } connectedCallback() { this.handlers_ = new Map(); } disconnectedCallback() { this.removeAllHandlers_(); this.handlers_ = null; } /** * Starts the dragging of the splitter. Adds listeners for mouse or touch * events and calls splitter drag start handler. * @param clientX X position of the mouse or touch event that started the * drag. * @param isTouchEvent True if the drag started by touch event. */ startDrag(clientX: number, isTouchEvent: boolean) { assert(!!this.handlers_); if (this.handlers_.size > 0) { // Concurrent drags this.endDrag_(); } if (isTouchEvent) { const endDragBound = this.endDrag_.bind(this); this.handlers_.set('touchmove', this.handleTouchMove_.bind(this)); this.handlers_.set('touchend', endDragBound); this.handlers_.set('touchcancel', endDragBound); // Another touch start (we somehow missed touchend or touchcancel). this.handlers_.set('touchstart', endDragBound); } else { this.handlers_.set('mousemove', this.handleMouseMove_.bind(this)); this.handlers_.set('mouseup', this.handleMouseUp_.bind(this)); } const doc = this.ownerDocument; // Use capturing events on the document to get events when the mouse // leaves the document. for (const [eventType, handler] of this.handlers_) { doc.addEventListener( /** @type {string} */ (eventType), /** @type {Function} */ (handler), true); } this.startX_ = clientX; this.handleSplitterDragStart_(); } private removeAllHandlers_() { const doc = this.ownerDocument; assert(!!this.handlers_); for (const [eventType, handler] of this.handlers_) { doc.removeEventListener( /** @type {string} */ (eventType), /** @type {Function} */ (handler), true); } this.handlers_.clear(); } /** * Ends the dragging of the splitter. Removes listeners set in startDrag * and calls splitter drag end handler. */ private endDrag_() { this.removeAllHandlers_(); this.handleSplitterDragEnd_(); } private getResizeTarget_(): HTMLElement { const target = this.resizeNextElement ? this.nextElementSibling : this.previousElementSibling; return target as HTMLElement; } /** * Calculate width to resize target element. * @param deltaX horizontal drag amount */ private calcDeltaX_(deltaX: number): number { return this.resizeNextElement ? -deltaX : deltaX; } /** * Handles the mousedown event which starts the dragging of the splitter. */ private onMouseDown_(e: MouseEvent) { if (e.button) { return; } this.startDrag(e.clientX, false); // Default action is to start selection and to move focus. e.preventDefault(); } /** * Handles the touchstart event which starts the dragging of the splitter. */ private onTouchStart_(e: TouchEvent) { if (e.touches.length === 1) { this.startDrag(e.touches[0]!.clientX, true); e.preventDefault(); } } /** * Handles the mousemove event which moves the splitter as the user moves * the mouse. */ private handleMouseMove_(e: MouseEvent) { this.handleMove_(e.clientX); } /** * Handles the touch move event. */ private handleTouchMove_(e: TouchEvent) { if (e.touches.length === 1) { this.handleMove_(e.touches[0]!.clientX); } } /** * Common part of handling mousemove and touchmove. Calls splitter drag * move handler. * @param clientX X position of the mouse or touch event. */ private handleMove_(clientX: number) { const deltaX = this.matches(':host-context([dir=rtl]) cr-splitter') ? this.startX_ - clientX : clientX - this.startX_; this.handleSplitterDragMove_(deltaX); } /** * Handles the mouse up event which ends the dragging of the splitter. */ private handleMouseUp_(_e: MouseEvent) { this.endDrag_(); } /** * Handles start of the splitter dragging. Saves current width of the * element being resized. */ private handleSplitterDragStart_() { // Use the computed width style as the base so that we can ignore what // box sizing the element has. Add the difference between offset and // client widths to account for any scrollbars. const targetElement = this.getResizeTarget_(); const doc = targetElement.ownerDocument; this.startWidth_ = parseFloat(doc.defaultView!.getComputedStyle(targetElement).width) + targetElement.offsetWidth - targetElement.clientWidth; this.classList.add('splitter-active'); } /** * Handles splitter moves. Updates width of the element being resized. * @param deltaX The change of splitter horizontal position. */ private handleSplitterDragMove_(deltaX: number) { const targetElement = this.getResizeTarget_(); const newWidth = this.startWidth_ + this.calcDeltaX_(deltaX); targetElement.style.width = newWidth + 'px'; this.dispatchEvent(new CustomEvent('dragmove')); } /** * Handles end of the splitter dragging. This fires a 'resize' event if the * size changed. */ private handleSplitterDragEnd_() { // Check if the size changed. const targetElement = this.getResizeTarget_(); const doc = targetElement.ownerDocument; const computedWidth = parseFloat(doc.defaultView!.getComputedStyle(targetElement).width); if (this.startWidth_ !== computedWidth) { this.dispatchEvent(new CustomEvent('resize')); } this.classList.remove('splitter-active'); } } customElements.define(CrSplitterElement.is, CrSplitterElement);
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_splitter/cr_splitter.ts
TypeScript
unknown
6,339
<style> :host { display: flex; flex-direction: column; width: fit-content; --tabs-background-color: #fbfbfb; --tabs-border-color: #c8c8c8; --tabs-hover-text-color: black; --tabs-unselected-text-color: #646464; } #tablist { background: var(--tabs-background-color); border-bottom: 1px solid var(--tabs-border-color); display: flex; margin: 0; padding-inline-start: 9px; padding-top: 14px; } :host([sticky-tabs]) #tablist { position: sticky; top: 0; z-index: var(--cr-tab-box-tabs-z-index, 1); } #tablist ::slotted(*) { background: var(--tabs-background-color); border: 1px solid var(--tabs-background-color); border-bottom: 0; border-radius: 0; cursor: default; display: block; margin-inline-start: 0; padding: 4px 9px 4px 10px; text-align: center; transition: none; } #tablist ::slotted(:not([selected])) { color: var(--tabs-unselected-text-color); } #tablist ::slotted(:not([selected]):hover) { color: var(--tabs-hover-text-color); } #tablist ::slotted([selected]) { border-color: var(--tabs-border-color); font-weight: bold; margin-bottom: -1px; position: relative; transition: none; z-index: 0; } #tablist:focus { outline: none; } html.focus-outline-visible #tablist:focus ::slotted([selected]) { outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; } #tabpanels { background: var(--tabs-background-color); box-shadow: none; display: flex; flex: 1; overflow: hidden; padding: 0 20px; } #tabpanels ::slotted([slot=panel]) { display: none; flex: 1; } #tabpanels ::slotted([slot=panel][selected]) { display: block; } </style> <div id="tablist"> <slot name="tab"></slot> </div> <div id="tabpanels"> <slot name="panel"></slot> </div>
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_tab_box/cr_tab_box.html
HTML
unknown
1,893
// 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 {assert} from '//resources/js/assert_ts.js'; import {CustomElement} from '//resources/js/custom_element.js'; import {FocusOutlineManager} from '//resources/js/focus_outline_manager.js'; import {getTemplate} from './cr_tab_box.html.js'; declare global { interface HTMLElementEventMap { 'selected-index-change': CustomEvent<number>; } } export class CrTabBoxElement extends CustomElement { static override get template() { return getTemplate(); } static get observedAttributes() { return ['selected-index']; } private tabs_: HTMLElement; private panels_: HTMLElement; private focusOutlineManager_: FocusOutlineManager; constructor() { super(); const tabs = this.$<HTMLElement>('#tablist'); assert(tabs); this.tabs_ = tabs; this.tabs_.addEventListener('keydown', e => this.onKeydown_(e)); this.tabs_.addEventListener('click', (e: MouseEvent) => { const tabs = this.getTabs_(); for (let i = 0; i < e.composedPath().length; i++) { const el = e.composedPath()[i] as HTMLElement; const index = tabs.findIndex(tab => tab === el); if (index !== -1) { this.setAttribute('selected-index', index.toString()); break; } } }); const panels = this.$<HTMLElement>('#tabpanels'); assert(panels); this.panels_ = panels; this.focusOutlineManager_ = FocusOutlineManager.forDocument(document); } connectedCallback() { this.setAttribute('selected-index', '0'); } attributeChangedCallback(name: string, _oldValue: string, newValue: string) { assert(name === 'selected-index'); const newIndex = Number(newValue); assert(!Number.isNaN(newIndex)); this.getPanels_().forEach((panel: Element, index: number) => { panel.toggleAttribute('selected', index === newIndex); }); this.getTabs_().forEach((tab: HTMLElement, index: number) => { const isSelected = index === newIndex; tab.toggleAttribute('selected', isSelected); // Update tabIndex for a11y tab.setAttribute('tabindex', isSelected ? '0' : '-1'); // Update aria-selected attribute for a11y const firstSelection = !tab.hasAttribute('aria-selected'); tab.setAttribute('aria-selected', isSelected ? 'true' : 'false'); // Update focus, but don't override initial focus. if (isSelected && !firstSelection) { tab.focus(); } }); this.dispatchEvent(new CustomEvent( 'selected-index-change', {bubbles: true, composed: true, detail: newIndex})); } private getTabs_(): HTMLElement[] { return Array.from(this.tabs_.querySelector('slot')!.assignedElements()) as HTMLElement[]; } private getPanels_(): Element[] { return Array.from(this.panels_.querySelector('slot')!.assignedElements()); } private onKeydown_(e: KeyboardEvent) { let delta = 0; switch (e.key) { case 'ArrowLeft': case 'ArrowUp': delta = -1; break; case 'ArrowRight': case 'ArrowDown': delta = 1; break; } if (!delta) { return; } if (document.documentElement.dir === 'rtl') { delta *= -1; } const count = this.getTabs_().length; const newIndex = (Number(this.getAttribute('selected-index')) + delta + count) % count; this.setAttribute('selected-index', newIndex.toString()); // Show focus outline since we used the keyboard. this.focusOutlineManager_.visible = true; } } declare global { interface HTMLElementTagNameMap { 'cr-tab-box': CrTabBoxElement; } } customElements.define('cr-tab-box', CrTabBoxElement);
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_tab_box/cr_tab_box.ts
TypeScript
unknown
3,802
<style include="cr-hidden-style"> :host { cursor: pointer; display: flex; flex-direction: row; font-size: var(--cr-tabs-font-size, 14px); font-weight: 500; height: var(--cr-tabs-height, 48px); user-select: none; } .tab { align-items: center; color: var(--cr-secondary-text-color); display: flex; flex: auto; height: 100%; justify-content: center; opacity: .8; outline: none; padding: 0 var(--cr-tabs-tab-inline-padding, 0); position: relative; transition: opacity 100ms cubic-bezier(.4, 0, 1, 1); } :host-context(.focus-outline-visible) .tab:focus { outline: var(--cr-tabs-focus-outline, auto); } .selected { color: var(--cr-tabs-selected-color, var(--google-blue-600)); opacity: 1; } @media (prefers-color-scheme: dark) { .selected { color: var(--cr-tabs-selected-color, var(--google-blue-300)); } } .selected:focus { font-weight: var(--cr-tabs-selected-tab-focused-font-weight, 700); } .tab-icon { -webkit-mask-position: center; -webkit-mask-repeat: no-repeat; -webkit-mask-size: var(--cr-tabs-icon-size, var(--cr-icon-size)); background-color: var(--cr-secondary-text-color); display: none; height: var(--cr-tabs-icon-size, var(--cr-icon-size)); margin-inline-end: var(--cr-tabs-icon-margin-end, var(--cr-icon-size)); width: var(--cr-tabs-icon-size, var(--cr-icon-size)); } .selected .tab-icon { background-color: var(--cr-tabs-selected-color, var(--google-blue-600)); } @media (prefers-color-scheme: dark) { .selected .tab-icon { background-color: var(--cr-tabs-selected-color, var(--google-blue-300)); } } .tab-indicator { background: var(--cr-tabs-selected-color, var(--google-blue-600)); border-top-left-radius: var(--cr-tabs-selection-bar-width, 2px); border-top-right-radius: var(--cr-tabs-selection-bar-width, 2px); bottom: 0; height: var(--cr-tabs-selection-bar-width, 2px); left: var(--cr-tabs-tab-inline-padding, 0); opacity: 0; position: absolute; right: var(--cr-tabs-tab-inline-padding, 0); transform-origin: left center; transition: transform; } .selected .tab-indicator { opacity: 1; } .tab-indicator.expand { transition-duration: 150ms; transition-timing-function: cubic-bezier(.4, 0, 1, 1); } .tab-indicator.contract { transition-duration: 180ms; transition-timing-function: cubic-bezier(0, 0, .2, 1); } @media (prefers-color-scheme: dark) { .tab-indicator { background: var(--cr-tabs-selected-color, var(--google-blue-300)); } } @media (forced-colors: active) { .tab-indicator { background: SelectedItem; } } </style> <template is="dom-repeat" items="[[tabNames]]"> <div role="tab" class$="tab [[getSelectedClass_(index, selected)]]" on-click="onTabClick_" aria-selected$="[[getAriaSelected_(index, selected)]]" tabindex$="[[getTabindex_(index, selected)]]"> <div class="tab-icon" style$="[[getIconStyle_(index)]]"> </div> [[item]] <div class="tab-indicator"></div> </div> </template>
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_tabs/cr_tabs.html
HTML
unknown
3,590
// 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-tabs' is a control used for selecting different sections or * tabs. cr-tabs was created to replace paper-tabs and paper-tab. cr-tabs * displays the name of each tab provided by |tabs|. A 'selected-changed' event * is fired any time |selected| is changed. * * cr-tabs takes its #selectionBar animation from paper-tabs. * * Keyboard behavior * - Home, End, ArrowLeft and ArrowRight changes the tab selection * * Known limitations * - no "disabled" state for the cr-tabs as a whole or individual tabs * - cr-tabs does not accept any <slot> (not necessary as of this writing) * - no horizontal scrolling, it is assumed that tabs always fit in the * available space */ import '../cr_hidden_style.css.js'; import '../cr_shared_vars.css.js'; import {DomRepeatEvent, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {getTemplate} from './cr_tabs.html.js'; export class CrTabsElement extends PolymerElement { static get is() { return 'cr-tabs'; } static get template() { return getTemplate(); } static get properties() { return { // Optional icon urls displayed in each tab. tabIcons: { type: Array, value: () => [], }, // Tab names displayed in each tab. tabNames: { type: Array, value: () => [], }, /** Index of the selected tab. */ selected: { type: Number, notify: true, observer: 'onSelectedChanged_', }, }; } tabIcons: string[]; tabNames: string[]; selected: number; private isRtl_: boolean = false; private lastSelected_: number|null = null; override connectedCallback() { super.connectedCallback(); this.isRtl_ = this.matches(':host-context([dir=rtl]) cr-tabs'); } override ready() { super.ready(); this.setAttribute('role', 'tablist'); this.addEventListener('keydown', this.onKeyDown_.bind(this)); } private getAriaSelected_(index: number): string { return index === this.selected ? 'true' : 'false'; } private getIconStyle_(index: number): string { const icon = this.tabIcons[index]; return icon ? `-webkit-mask-image: url(${icon}); display: block;` : ''; } private getTabindex_(index: number): string { return index === this.selected ? '0' : '-1'; } private getSelectedClass_(index: number): string { return index === this.selected ? 'selected' : ''; } private onSelectedChanged_(newSelected: number, oldSelected: number) { const tabs = this.shadowRoot!.querySelectorAll('.tab'); if (tabs.length === 0 || oldSelected === undefined) { // Tabs are not rendered yet. return; } const oldTabRect = tabs[oldSelected]!.getBoundingClientRect(); const newTabRect = tabs[newSelected]!.getBoundingClientRect(); const newIndicator = tabs[newSelected]!.querySelector<HTMLElement>('.tab-indicator')!; newIndicator.classList.remove('expand', 'contract'); // Make new indicator look like it is the old indicator. this.updateIndicator_( newIndicator, newTabRect, oldTabRect.left, oldTabRect.width); newIndicator.getBoundingClientRect(); // Force repaint. // Expand to cover both the previous selected tab, the newly selected tab, // and everything in between. newIndicator.classList.add('expand'); newIndicator.addEventListener( 'transitionend', e => this.onIndicatorTransitionEnd_(e), {once: true}); const leftmostEdge = Math.min(oldTabRect.left, newTabRect.left); const fullWidth = newTabRect.left > oldTabRect.left ? newTabRect.right - oldTabRect.left : oldTabRect.right - newTabRect.left; this.updateIndicator_(newIndicator, newTabRect, leftmostEdge, fullWidth); } private onKeyDown_(e: KeyboardEvent) { const count = this.tabNames.length; let newSelection; if (e.key === 'Home') { newSelection = 0; } else if (e.key === 'End') { newSelection = count - 1; } else if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') { const delta = e.key === 'ArrowLeft' ? (this.isRtl_ ? 1 : -1) : (this.isRtl_ ? -1 : 1); newSelection = (count + this.selected + delta) % count; } else { return; } e.preventDefault(); e.stopPropagation(); this.selected = newSelection; this.shadowRoot!.querySelector<HTMLElement>('.tab.selected')!.focus(); } private onIndicatorTransitionEnd_(event: Event) { const indicator = event.target as HTMLElement; indicator.classList.replace('expand', 'contract'); indicator.style.transform = `translateX(0) scaleX(1)`; } private onTabClick_(e: DomRepeatEvent<string>) { this.selected = e.model.index; } private updateIndicator_( indicator: HTMLElement, originRect: ClientRect, newLeft: number, newWidth: number) { const leftDiff = 100 * (newLeft - originRect.left) / originRect.width; const widthRatio = newWidth / originRect.width; const transform = `translateX(${leftDiff}%) scaleX(${widthRatio})`; indicator.style.transform = transform; } } declare global { interface HTMLElementTagNameMap { 'cr-tabs': CrTabsElement; } } customElements.define(CrTabsElement.is, CrTabsElement);
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_tabs/cr_tabs.ts
TypeScript
unknown
5,462
<style include="cr-hidden-style cr-input-style cr-shared-style"> textarea { display: block; resize: none; } #input-container { background-color: var(--cr-input-background-color); } :host([autogrow][has-max-height]) #input-container { box-sizing: content-box; max-height: var(--cr-textarea-autogrow-max-height); min-height: 1lh; } :host([invalid]) #underline { border-color: var(--cr-input-error-color); } #footerContainer { border-top: 0; /* Components that use the footer should set this to "flex". */ display: var(--cr-textarea-footer-display, none); font-size: var(--cr-form-field-label-font-size); height: var(--cr-form-field-label-height); justify-content: space-between; line-height: var(--cr-form-field-label-line-height); margin: 8px 0; min-height: 0; padding: 0; white-space: var(--cr-input-error-white-space); } :host([invalid]) #label, :host([invalid]) #footerContainer { color: var(--cr-input-error-color); } #mirror { display: none; } :host([autogrow]) #mirror { display: block; visibility: hidden; white-space: pre-wrap; word-wrap: break-word; } :host([autogrow]) #mirror, :host([autogrow]) textarea { border: 0; box-sizing: border-box; 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); } :host([autogrow]) textarea { height: 100%; left: 0; overflow: hidden; position: absolute; resize: none; top: 0; width: 100%; } :host([autogrow][has-max-height]) #mirror, :host([autogrow][has-max-height]) textarea { overflow-x: hidden; overflow-y: auto; } </style> <div id="label" class="cr-form-field-label" hidden="[[!label]]"> [[label]] </div> <div id="input-container"> <!-- The mirror div is used to take up the required space when autogrow is set. --> <div id="mirror">[[calculateMirror_(value)]]</div> <!-- The textarea is limited to |rows| height. If the content exceeds the bounds, it scrolls by default unless autogrow is set. No space or comments are allowed before the closing tag. --> <textarea id="input" autofocus="[[autofocus]]" rows="[[rows]]" value="{{value::input}}" aria-label$="[[label]]" on-focus="onInputFocusChange_" on-blur="onInputFocusChange_" on-change="onInputChange_" disabled="[[disabled]]" maxlength$="[[maxlength]]" readonly$="[[readonly]]" required$="[[required]]"></textarea> <div id="underline"></div> </div> <div id="footerContainer" class="cr-row"> <div id="firstFooter" aria-live="[[getFooterAria_(invalid)]]"> [[firstFooter]] </div> <div id="secondFooter" aria-live="[[getFooterAria_(invalid)]]"> [[secondFooter]] </div> </div>
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_textarea/cr_textarea.html
HTML
unknown
2,927
// 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-textarea' is a component similar to native textarea, * and inherits styling from cr-input. */ import '../cr_hidden_style.css.js'; import '../cr_shared_style.css.js'; import '../cr_input/cr_input_style.css.js'; import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {getTemplate} from './cr_textarea.html.js'; export interface CrTextareaElement { $: { firstFooter: HTMLElement, footerContainer: HTMLElement, input: HTMLTextAreaElement, label: HTMLElement, mirror: HTMLElement, secondFooter: HTMLElement, underline: HTMLElement, }; } export class CrTextareaElement extends PolymerElement { static get is() { return 'cr-textarea'; } static get template() { return getTemplate(); } static get properties() { return { /** * Whether the text area should automatically get focus when the page * loads. */ autofocus: { type: Boolean, value: false, reflectToAttribute: true, }, /** * Whether the text area is disabled. When disabled, the text area loses * focus and is not reachable by tabbing. */ disabled: { type: Boolean, value: false, reflectToAttribute: true, observer: 'onDisabledChanged_', }, /** Whether the text area is required. */ required: { type: Boolean, value: false, reflectToAttribute: true, }, /** Maximum length (in characters) of the text area. */ maxlength: { type: Number, }, /** * Whether the text area is read only. If read-only, content cannot be * changed. */ readonly: Boolean, /** Number of rows (lines) of the text area. */ rows: { type: Number, value: 3, reflectToAttribute: true, }, /** Caption of the text area. */ label: { type: String, value: '', }, /** * Text inside the text area. If the text exceeds the bounds of the text * area, i.e. if it has more than |rows| lines, a scrollbar is shown by * default when autogrow is not set. */ value: { type: String, value: '', notify: true, }, /** Whether the textarea can auto-grow vertically or not. */ autogrow: { type: Boolean, value: false, reflectToAttribute: true, }, /** * Attribute to enable limiting the maximum height of a autogrow textarea. * Use --cr-textarea-autogrow-max-height to set the height. */ hasMaxHeight: { type: Boolean, value: false, reflectToAttribute: true, }, /** Whether the textarea is invalid or not. */ invalid: { type: Boolean, value: false, reflectToAttribute: true, }, /** * First footer text below the text area. Can be used to warn user about * character limits. */ firstFooter: { type: String, value: '', }, /** * Second footer text below the text area. Can be used to show current * character count. */ secondFooter: { type: String, value: '', }, }; } override autofocus: boolean; disabled: boolean; readonly: boolean; required: boolean; rows: number; label: string; value: string; autogrow: boolean; hasMaxHeight: boolean; invalid: boolean; firstFooter: string; secondFooter: string; focusInput() { this.$.input.focus(); } /** * '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 calculateMirror_(): string { if (!this.autogrow) { return ''; } // Browsers do not render empty divs. The extra space is used to render the // div when empty. const tokens = this.value ? this.value.split('\n') : ['']; while (this.rows > 0 && tokens.length < this.rows) { tokens.push(''); } return tokens.join('\n') + '&nbsp;'; } private onInputFocusChange_() { // focused_ is used instead of :focus-within, so focus on elements within // the suffix slot does not trigger a change in input styles. if (this.shadowRoot!.activeElement === this.$.input) { this.setAttribute('focused_', ''); } else { this.removeAttribute('focused_'); } } private onDisabledChanged_() { this.setAttribute('aria-disabled', this.disabled ? 'true' : 'false'); } private getFooterAria_(): string { return this.invalid ? 'assertive' : 'polite'; } } declare global { interface HTMLElementTagNameMap { 'cr-textarea': CrTextareaElement; } } customElements.define(CrTextareaElement.is, CrTextareaElement);
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_textarea/cr_textarea.ts
TypeScript
unknown
5,269
<style> :host { --cr-toast-background: #323232; --cr-toast-button-color: var(--google-blue-300); --cr-toast-text-color: #fff; } @media (prefers-color-scheme: dark) { :host { --cr-toast-background: var(--google-grey-900) linear-gradient(rgba(255, 255, 255, .06), rgba(255, 255, 255, .06)); --cr-toast-button-color: var(--google-blue-300); --cr-toast-text-color: var(--google-grey-200); } } :host { align-items: center; background: var(--cr-toast-background); border-radius: 4px; bottom: 0; box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.28); box-sizing: border-box; display: flex; margin: 24px; max-width: 568px; min-height: 52px; min-width: 288px; opacity: 0; padding: 0 24px; position: fixed; transform: translateY(100px); transition: opacity 300ms, transform 300ms; visibility: hidden; z-index: 1; } :host-context([dir=ltr]) { left: 0; } :host-context([dir=rtl]) { right: 0; } :host([open]) { opacity: 1; transform: translateY(0); visibility: visible; } /* Note: this doesn't work on slotted text nodes. Something like * <cr-toast>hey!</cr-toast> wont get the right text color. */ :host ::slotted(*) { color: var(--cr-toast-text-color); } :host ::slotted(cr-button) { background-color: transparent !important; border: none !important; color: var(--cr-toast-button-color) !important; margin-inline-start: 32px !important; min-width: 52px !important; padding: 8px !important; } :host ::slotted(cr-button:hover) { background-color: transparent !important; } </style> <slot></slot>
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_toast/cr_toast.html
HTML
unknown
1,946
// 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 lightweight toast. */ import '//resources/polymer/v3_0/paper-styles/color.js'; import '../cr_shared_vars.css.js'; import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {getTemplate} from './cr_toast.html.js'; export interface CrToastElement { _setOpen(open: boolean): void; } export class CrToastElement extends PolymerElement { static get is() { return 'cr-toast'; } static get template() { return getTemplate(); } static get properties() { return { duration: { type: Number, value: 0, }, open: { readOnly: true, type: Boolean, value: false, reflectToAttribute: true, }, }; } duration: number; open: boolean; private hideTimeoutId_: number|null = null; static get observers() { return ['resetAutoHide_(duration, open)']; } /** * Cancels existing auto-hide, and sets up new auto-hide. */ private resetAutoHide_() { if (this.hideTimeoutId_ !== null) { window.clearTimeout(this.hideTimeoutId_); this.hideTimeoutId_ = null; } if (this.open && this.duration !== 0) { this.hideTimeoutId_ = window.setTimeout(() => { this.hide(); }, this.duration); } } /** * Shows the toast and auto-hides after |this.duration| milliseconds has * passed. If the toast is currently being shown, any preexisting auto-hide * is cancelled and replaced with a new auto-hide. */ show() { // Force autohide to reset if calling show on an already shown toast. const shouldResetAutohide = this.open; // The role attribute is removed first so that screen readers to better // ensure that screen readers will read out the content inside the toast. // If the role is not removed and re-added back in, certain screen readers // do not read out the contents, especially if the text remains exactly // the same as a previous toast. this.removeAttribute('role'); // Reset the aria-hidden attribute as screen readers need to access the // contents of an opened toast. this.removeAttribute('aria-hidden'); this._setOpen(true); this.setAttribute('role', 'alert'); if (shouldResetAutohide) { this.resetAutoHide_(); } } /** * Hides the toast and ensures that screen readers cannot its contents while * hidden. */ hide() { this.setAttribute('aria-hidden', 'true'); this._setOpen(false); } } declare global { interface HTMLElementTagNameMap { 'cr-toast': CrToastElement; } } customElements.define(CrToastElement.is, CrToastElement);
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_toast/cr_toast.ts
TypeScript
unknown
2,806
// 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 CrToastElement() {} CrToastElement.prototype.hide = function() {};
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_toast/cr_toast_externs.js
JavaScript
unknown
396
<style include="cr-hidden-style"> #content { display: flex; flex: 1; } .collapsible { overflow: hidden; text-overflow: ellipsis; } span { white-space: pre; } .elided-text { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } </style> <cr-toast id="toast" duration="[[duration]]"> <div id="content" class="elided-text"></div> <slot id="slotted"></slot> </cr-toast>
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_toast/cr_toast_manager.html
HTML
unknown
521
// 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 Element which shows toasts with optional undo button. */ import '../cr_hidden_style.css.js'; import './cr_toast.js'; import {assert} from '//resources/js/assert_ts.js'; import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {CrToastElement} from './cr_toast.js'; import {getTemplate} from './cr_toast_manager.html.js'; let toastManagerInstance: CrToastManagerElement|null = null; export function getToastManager(): CrToastManagerElement { assert(toastManagerInstance); return toastManagerInstance; } function setInstance(instance: CrToastManagerElement|null) { assert(!instance || !toastManagerInstance); toastManagerInstance = instance; } export interface CrToastManagerElement { $: { content: HTMLElement, slotted: HTMLSlotElement, toast: CrToastElement, }; } export class CrToastManagerElement extends PolymerElement { static get is() { return 'cr-toast-manager'; } static get template() { return getTemplate(); } static get properties() { return { duration: { type: Number, value: 0, }, }; } duration: number; get isToastOpen(): boolean { return this.$.toast.open; } get slottedHidden(): boolean { return this.$.slotted.hidden; } override connectedCallback() { super.connectedCallback(); setInstance(this); } override disconnectedCallback() { super.disconnectedCallback(); setInstance(null); } /** * @param label The label to display inside the toast. */ show(label: string, hideSlotted: boolean = false) { this.$.content.textContent = label; this.showInternal_(hideSlotted); } /** * Shows the toast, making certain text fragments collapsible. */ showForStringPieces( pieces: Array<{value: string, collapsible: boolean}>, hideSlotted: boolean = false) { const content = this.$.content; content.textContent = ''; pieces.forEach(function(p) { if (p.value.length === 0) { return; } const span = document.createElement('span'); span.textContent = p.value; if (p.collapsible) { span.classList.add('collapsible'); } content.appendChild(span); }); this.showInternal_(hideSlotted); } private showInternal_(hideSlotted: boolean) { this.$.slotted.hidden = hideSlotted; this.$.toast.show(); } hide() { this.$.toast.hide(); } } declare global { interface HTMLElementTagNameMap { 'cr-toast-manager': CrToastManagerElement; } } customElements.define(CrToastManagerElement.is, CrToastManagerElement);
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_toast/cr_toast_manager.ts
TypeScript
unknown
2,790
<style> :host { --cr-toggle-checked-bar-color: var(--google-blue-600); --cr-toggle-checked-button-color: var(--google-blue-600); --cr-toggle-checked-ripple-color: rgba(var(--google-blue-600-rgb), .2); --cr-toggle-ripple-diameter: 40px; --cr-toggle-unchecked-bar-color: var(--google-grey-400); --cr-toggle-unchecked-button-color: white; --cr-toggle-unchecked-ripple-color: rgba(var(--google-grey-600-rgb), .15); -webkit-tap-highlight-color: transparent; cursor: pointer; display: block; min-width: 34px; outline: none; position: relative; width: 34px; } :host-context([chrome-refresh-2023]):host { --cr-toggle-checked-bar-color: var(--color-toggle-button-track-on, var(--cr-fallback-color-primary)); --cr-toggle-checked-button-color: var(--color-toggle-button-thumb-on, var(--cr-fallback-color-on-primary)); --cr-toggle-unchecked-bar-color: var(--color-toggle-button-track-off, var(--cr-fallback-color-surface-variant)); --cr-toggle-unchecked-button-color: var(--color-toggle-button-thumb-off, var(--cr-fallback-color-outline)); --cr-toggle-checked-ripple-color: var(--cr-active-background-color); --cr-toggle-unchecked-ripple-color: var(--cr-active-background-color); --cr-toggle-ripple-diameter: 20px; height: fit-content; min-width: initial; width: fit-content; } @media (forced-colors: active) { :host { /* TODO(crbug.com/1176612): cr-toggle heavily relies on background-color to convey various states (on/off, enabled/disabled). Until proper specs for HCM exist, turn off forced-colors automatic adjustments so that the cr-toggle is at least visible. Replace with a HCM compliant implementation once specs exist.*/ forced-color-adjust: none; } } @media (prefers-color-scheme: dark) { :host { --cr-toggle-checked-bar-color: var(--google-blue-300); --cr-toggle-checked-button-color: var(--google-blue-300); --cr-toggle-checked-ripple-color: rgba(var(--google-blue-300-rgb), .4); --cr-toggle-unchecked-bar-color: var(--google-grey-500); --cr-toggle-unchecked-button-color: var(--google-grey-300); --cr-toggle-unchecked-ripple-color: rgba(var(--google-grey-300-rgb), .4); } } /* Keep the prefers-color-scheme and [dark] rules the same. */ :host([dark]) { --cr-toggle-checked-bar-color: var(--google-blue-300); --cr-toggle-checked-button-color: var(--google-blue-300); --cr-toggle-checked-ripple-color: rgba(var(--google-blue-300-rgb), .4); --cr-toggle-unchecked-bar-color: var(--google-grey-500); --cr-toggle-unchecked-button-color: var(--google-grey-300); --cr-toggle-unchecked-ripple-color: rgba(var(--google-grey-300-rgb), .4); } :host([disabled]) { cursor: initial; opacity: var(--cr-disabled-opacity); pointer-events: none; } :host-context([chrome-refresh-2023]):host([disabled]) { --cr-toggle-checked-bar-color: var(--color-toggle-button-track-on-disabled, rgba(var(--cr-fallback-color-on-surface-rgb), .12)); --cr-toggle-checked-button-color: var(--color-toggle-button-thumb-on-disabled, var(--cr-fallback-color-surface)); --cr-toggle-unchecked-bar-color: transparent; --cr-toggle-unchecked-button-color: var(--color-toggle-button-thumb-off-disabled, rgba(var(--cr-fallback-color-on-surface-rgb), var(--cr-disabled-opacity))); opacity: 1; } #bar { background-color: var(--cr-toggle-unchecked-bar-color); border-radius: 8px; height: 12px; left: 3px; position: absolute; top: 2px; transition: background-color linear 80ms; width: 28px; z-index: 0; } :host([checked]) #bar { background-color: var(--cr-toggle-checked-bar-color); opacity: var(--cr-toggle-checked-bar-opacity, 0.5); } :host-context([chrome-refresh-2023]) #bar { border: 1px solid var(--cr-toggle-unchecked-button-color); border-radius: 50px; box-sizing: border-box; display: block; height: 16px; opacity: 1; position: initial; width: 26px; } :host-context([chrome-refresh-2023]):host([checked]) #bar { border-color: var(--cr-toggle-checked-bar-color); } :host-context([chrome-refresh-2023]):host([disabled]) #bar { border-color: var(--cr-toggle-unchecked-button-color); } :host-context([chrome-refresh-2023]):host([disabled][checked]) #bar { border: none; } :host-context([chrome-refresh-2023]):host(:focus-visible) #bar { background-clip: padding-box; border-color: transparent; outline: 2px solid var(--cr-toggle-checked-bar-color); } #knob { background-color: var(--cr-toggle-unchecked-button-color); border-radius: 50%; box-shadow: var(--cr-toggle-box-shadow, 0 1px 3px 0 rgba(0, 0, 0, .4)); display: block; height: 16px; position: relative; transition: transform linear 80ms, background-color linear 80ms; width: 16px; z-index: 1; } :host([checked]) #knob { background-color: var(--cr-toggle-checked-button-color); transform: translate3d(18px, 0, 0); } :host-context([dir=rtl]):host([checked]) #knob { transform: translate3d(-18px, 0, 0); } :host-context([chrome-refresh-2023]) #knob { --cr-toggle-knob-diameter_: 8px; /* Distance between knob center to the edge of the control is the same for both checked and unchecked. */ --cr-toggle-knob-center-edge-distance_: 8px; box-shadow: none; height: var(--cr-toggle-knob-diameter_); left: var(--cr-toggle-knob-center-edge-distance_); position: absolute; top: 50%; transform: translate(-50%, -50%); transition: left linear 80ms, background-color linear 80ms, width linear 80ms, height linear 80ms; width: var(--cr-toggle-knob-diameter_); } :host-context([chrome-refresh-2023]):host(:active) #knob { --cr-toggle-knob-diameter_: 10px; } :host-context([chrome-refresh-2023]):host([checked]) #knob { --cr-toggle-knob-diameter_: 12px; left: calc(100% - var(--cr-toggle-knob-center-edge-distance_)); } :host-context([chrome-refresh-2023]):host([checked]:active) #knob { --cr-toggle-knob-diameter_: 14px; } :host-context([chrome-refresh-2023]):host([checked]:active) #knob, :host-context([chrome-refresh-2023]):host([checked]:hover) #knob { --cr-toggle-checked-button-color: var(--color-toggle-button-thumb-on-hover-pressed, var(--cr-fallback-color-primary-container)); } :host-context([chrome-refresh-2023]):host(:hover) #knob::before { background-color: var(--cr-hover-background-color); border-radius: 50%; content: ''; height: var(--cr-toggle-ripple-diameter); left: calc(var(--cr-toggle-knob-diameter_) / 2); position: absolute; top: calc(var(--cr-toggle-knob-diameter_) / 2); transform: translate(-50%, -50%); width: var(--cr-toggle-ripple-diameter); } paper-ripple { --paper-ripple-opacity: 1; color: var(--cr-toggle-unchecked-ripple-color); height: var(--cr-toggle-ripple-diameter); left: 50%; outline: var(--cr-toggle-ripple-ring, none); pointer-events: none; position: absolute; top: 50%; transform: translate(-50%, -50%); transition: color linear 80ms; width: var(--cr-toggle-ripple-diameter); } :host([checked]) paper-ripple { color: var(--cr-toggle-checked-ripple-color); } :host-context([dir=rtl]) paper-ripple { left: auto; right: 50%; transform: translate(50%, -50%); } </style> <span id="bar"></span> <span id="knob"></span>
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_toggle/cr_toggle.html
HTML
unknown
8,648
// 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. /** * Number of pixels required to move to consider the pointermove event as * intentional. */ export const MOVE_THRESHOLD_PX: number = 5; /** * @fileoverview 'cr-toggle' is a component for showing an on/off switch. It * fires a 'change' event *only* when its state changes as a result of a user * interaction. Besides just clicking the element, its state can be changed by * dragging (pointerdown+pointermove) the element towards the desired direction. */ 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 {assert} from '//resources/js/assert_ts.js'; import '../cr_shared_vars.css.js'; import {getTemplate} from './cr_toggle.html.js'; const CrToggleElementBase = mixinBehaviors([PaperRippleBehavior], PolymerElement) as {new (): PolymerElement & PaperRippleBehavior}; export interface CrToggleElement { $: { knob: HTMLElement, }; } export class CrToggleElement extends CrToggleElementBase { static get is() { return 'cr-toggle'; } static get template() { return getTemplate(); } static get properties() { return { checked: { type: Boolean, value: false, reflectToAttribute: true, observer: 'checkedChanged_', notify: true, }, dark: { type: Boolean, value: false, reflectToAttribute: true, }, disabled: { type: Boolean, value: false, reflectToAttribute: true, observer: 'disabledChanged_', }, }; } checked: boolean; dark: boolean; disabled: boolean; private boundPointerMove_: ((e: PointerEvent) => void)|null = null; /** * Whether the state of the toggle has already taken into account by * |pointeremove| handlers. Used in the 'click' handler. */ private handledInPointerMove_: boolean = false; private pointerDownX_: number = 0; /* eslint-disable-next-line @typescript-eslint/naming-convention */ override _rippleContainer: Element; override ready() { super.ready(); if (!this.hasAttribute('role')) { this.setAttribute('role', 'button'); } if (!this.hasAttribute('tabindex')) { this.setAttribute('tabindex', '0'); } this.setAttribute('aria-pressed', this.checked ? 'true' : 'false'); this.setAttribute('aria-disabled', this.disabled ? 'true' : 'false'); if (!document.documentElement.hasAttribute('chrome-refresh-2023')) { this.addEventListener('blur', this.hideRipple_.bind(this)); this.addEventListener('focus', this.onFocus_.bind(this)); } 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)); this.addEventListener('pointerup', this.onPointerUp_.bind(this)); } override connectedCallback() { super.connectedCallback(); const direction = this.matches(':host-context([dir=rtl]) cr-toggle') ? -1 : 1; this.boundPointerMove_ = (e: PointerEvent) => { // Prevent unwanted text selection to occur while moving the pointer, this // is important. e.preventDefault(); const diff = e.clientX - this.pointerDownX_; if (Math.abs(diff) < MOVE_THRESHOLD_PX) { return; } this.handledInPointerMove_ = true; const shouldToggle = (diff * direction < 0 && this.checked) || (diff * direction > 0 && !this.checked); if (shouldToggle) { this.toggleState_(/* fromKeyboard= */ false); } }; } private checkedChanged_() { this.setAttribute('aria-pressed', this.checked ? 'true' : 'false'); } private disabledChanged_() { this.setAttribute('tabindex', this.disabled ? '-1' : '0'); this.setAttribute('aria-disabled', this.disabled ? 'true' : 'false'); } private onFocus_() { this.getRipple().showAndHoldDown(); } private hideRipple_() { this.getRipple().clear(); } private onPointerUp_() { assert(this.boundPointerMove_); this.removeEventListener('pointermove', this.boundPointerMove_); this.hideRipple_(); } private onPointerDown_(e: PointerEvent) { // Don't do anything if this was not a primary button click or touch event. if (e.button !== 0) { return; } // This is necessary to have follow up pointer events fire on |this|, even // if they occur outside of its bounds. this.setPointerCapture(e.pointerId); this.pointerDownX_ = e.clientX; this.handledInPointerMove_ = false; assert(this.boundPointerMove_); this.addEventListener('pointermove', this.boundPointerMove_); } private onClick_(e: Event) { // Prevent |click| event from bubbling. It can cause parents of this // elements to erroneously re-toggle this control. e.stopPropagation(); e.preventDefault(); // User gesture has already been taken care of inside |pointermove| // handlers, Do nothing here. if (this.handledInPointerMove_) { return; } // If no pointermove event fired, then user just clicked on the // toggle button and therefore it should be toggled. this.toggleState_(/* fromKeyboard= */ false); } private toggleState_(fromKeyboard: boolean) { // Ignore cases where the 'click' or 'keypress' handlers are triggered while // disabled. if (this.disabled) { return; } if (!fromKeyboard) { this.hideRipple_(); } 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.toggleState_(/* fromKeyboard= */ true); } } private onKeyUp_(e: KeyboardEvent) { if (e.key !== ' ' && e.key !== 'Enter') { return; } e.preventDefault(); e.stopPropagation(); if (e.key === ' ') { this.toggleState_(/* fromKeyboard= */ true); } } // Overridden from PaperRippleBehavior /* eslint-disable-next-line @typescript-eslint/naming-convention */ override _createRipple() { this._rippleContainer = this.$.knob; const ripple = super._createRipple(); ripple.id = 'ink'; ripple.setAttribute('recenters', ''); ripple.classList.add('circle', 'toggle-ink'); return ripple; } } declare global { interface HTMLElementTagNameMap { 'cr-toggle': CrToggleElement; } } customElements.define(CrToggleElement.is, CrToggleElement);
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_toggle/cr_toggle.ts
TypeScript
unknown
7,001
// 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 CrToggleElement() {}
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_toggle/cr_toggle_externs.js
JavaScript
unknown
349
<style include="cr-icons cr-hidden-style"> :host { align-items: center; background-color: var(--cr-toolbar-background-color); color: var(--google-grey-900); display: flex; height: var(--cr-toolbar-height); } @media (prefers-color-scheme: dark) { :host { border-bottom: var(--cr-separator-line); box-sizing: border-box; color: var(--cr-secondary-text-color); } } h1 { flex: 1; font-size: 170%; font-weight: var(--cr-toolbar-header-font-weight, 500); letter-spacing: .25px; line-height: normal; margin-inline-start: 6px; padding-inline-end: 12px; white-space: var(--cr-toolbar-header-white-space, normal); } @media (prefers-color-scheme: dark) { h1 { color: var(--cr-primary-text-color); } } #leftContent { position: relative; transition: opacity 100ms; } #leftSpacer { align-items: center; box-sizing: border-box; display: flex; /* 12px to match #rightSpacer + 6px to align with icons in menus. */ padding-inline-start: calc(12px + 6px); width: var(--cr-toolbar-left-spacer-width, auto); /* OHOS_ARKWEB_EXTENSIONS */ min-width: 160px; } cr-icon-button { --cr-icon-button-size: 32px; min-width: 32px; } @media (prefers-color-scheme: light) { cr-icon-button { --cr-icon-button-fill-color: currentColor; --cr-icon-button-focus-outline-color: var(--cr-focus-outline-color); } } #centeredContent { display: flex; flex: 1 1 0; justify-content: center; } #rightSpacer { padding-inline-end: 12px; } :host([narrow]) #centeredContent { justify-content: flex-end; } :host([has-overlay]) { transition: visibility var(--cr-toolbar-overlay-animation-duration); visibility: hidden; } :host([narrow][showing-search_]) #leftContent { opacity: 0; position: absolute; } :host(:not([narrow])) #leftContent { flex: 1 1 var(--cr-toolbar-field-margin, 0); } :host(:not([narrow])) #centeredContent { flex-basis: var(--cr-toolbar-center-basis, 0); } :host(:not([narrow])[disable-right-content-grow]) #centeredContent { justify-content: start; padding-inline-start: 12px; } :host(:not([narrow])) #rightContent { flex: 1 1 0; text-align: end; } :host(:not([narrow])[disable-right-content-grow]) #rightContent { flex: 0 1 0; } picture { display: none; } #menuButton { margin-inline-end: 9px; } #menuButton ~ h1 { margin-inline-start: 0; } :host([always-show-logo]) picture, :host(:not([narrow])) picture { display: initial; margin-inline-end: 16px; } :host([always-show-logo]) #leftSpacer, :host(:not([narrow])) #leftSpacer { /* 12px to match #rightSpacer + 9px to align with icons in menus. */ padding-inline-start: calc(12px + 9px); } :host([always-show-logo]) :is(picture, #product-logo), :host(:not([narrow])) :is(picture, #product-logo) { height: 24px; width: 24px; } </style> <div id="leftContent"> <div id="leftSpacer"> <template is="dom-if" if="[[showMenu]]" restamp> <cr-icon-button id="menuButton" class="no-overlap" iron-icon="cr20:menu" on-click="onMenuTap_" aria-label$="[[menuLabel]]" title="[[menuLabel]]"> </cr-icon-button> </template> <slot name="product-logo"> <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> <h1>[[pageName]]</h1> </div> </div> <div id="centeredContent" hidden$="[[!showSearch]]"> <cr-toolbar-search-field id="search" narrow="[[narrow]]" label="[[searchPrompt]]" clear-label="[[clearLabel]]" spinner-active="[[spinnerActive]]" showing-search="{{showingSearch_}}" autofocus$="[[autofocus]]"> </cr-toolbar-search-field> <iron-media-query query="(max-width: [[narrowThreshold]]px)" query-matches="{{narrow}}"> </iron-media-query> </div> <div id="rightContent"> <div id="rightSpacer"> <slot></slot> </div> </div>
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_toolbar/cr_toolbar.html
HTML
unknown
4,924
// 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_icon_button/cr_icon_button.js'; import '../cr_icons.css.js'; import '../cr_hidden_style.css.js'; import '../cr_shared_vars.css.js'; import '../icons.html.js'; import '//resources/polymer/v3_0/iron-media-query/iron-media-query.js'; import './cr_toolbar_search_field.js'; import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {getTemplate} from './cr_toolbar.html.js'; import {CrToolbarSearchFieldElement} from './cr_toolbar_search_field.js'; export interface CrToolbarElement { $: { search: CrToolbarSearchFieldElement, }; } export class CrToolbarElement extends PolymerElement { static get is() { return 'cr-toolbar'; } static get template() { return getTemplate(); } static get properties() { return { // Name to display in the toolbar, in titlecase. pageName: String, // Prompt text to display in the search field. searchPrompt: String, // Tooltip to display on the clear search button. clearLabel: String, // Tooltip to display on the menu button. menuLabel: String, // Value is proxied through to cr-toolbar-search-field. When true, // the search field will show a processing spinner. spinnerActive: Boolean, // Controls whether the menu button is shown at the start of the menu. showMenu: {type: Boolean, value: false}, // Controls whether the search field is shown. showSearch: {type: Boolean, value: true}, // Controls whether the search field is autofocused. autofocus: { type: Boolean, value: false, reflectToAttribute: true, }, // True when the toolbar is displaying in narrow mode. narrow: { type: Boolean, reflectToAttribute: true, readonly: true, notify: true, }, /** * The threshold at which the toolbar will change from normal to narrow * mode, in px. */ narrowThreshold: { type: Number, value: 900, }, alwaysShowLogo: { type: Boolean, value: false, reflectToAttribute: true, }, showingSearch_: { type: Boolean, reflectToAttribute: true, }, }; } pageName: string; searchPrompt: string; clearLabel: string; menuLabel: string; spinnerActive: boolean; showMenu: boolean; showSearch: boolean; override autofocus: boolean; narrow: boolean; narrowThreshold: number; alwaysShowLogo: boolean; private showingSearch_: boolean; getSearchField(): CrToolbarSearchFieldElement { return this.$.search; } private onMenuTap_() { this.dispatchEvent(new CustomEvent( 'cr-toolbar-menu-tap', {bubbles: true, composed: true})); } focusMenuButton() { requestAnimationFrame(() => { // Wait for next animation frame in case dom-if has not applied yet and // added the menu button. const menuButton = this.shadowRoot!.querySelector<HTMLElement>('#menuButton'); if (menuButton) { menuButton.focus(); } }); } isMenuFocused(): boolean { return !!this.shadowRoot!.activeElement && this.shadowRoot!.activeElement.id === 'menuButton'; } } declare global { interface HTMLElementTagNameMap { 'cr-toolbar': CrToolbarElement; } } customElements.define(CrToolbarElement.is, CrToolbarElement);
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_toolbar/cr_toolbar.ts
TypeScript
unknown
3,564
<style include="cr-shared-style cr-icons"> :host { align-items: center; display: flex; height: 40px; transition: background-color 150ms cubic-bezier(0.4, 0, 0.2, 1), width 150ms cubic-bezier(0.4, 0, 0.2, 1); width: 44px; } :host([disabled]) { opacity: var(--cr-disabled-opacity); } [hidden] { display: none !important; } cr-icon-button { --cr-icon-button-size: var(--cr-toolbar-icon-container-size, 32px); margin: var(--cr-toolbar-icon-margin, 6px); } :host-context([chrome-refresh-2023]) cr-icon-button { --cr-icon-button-fill-color: var(--cr-toolbar-search-field-icon-color, var(--color-toolbar-search-field-icon, var(--cr-secondary-text-color))); --cr-icon-button-size: var(--cr-toolbar-icon-container-size, 28px); --cr-icon-button-icon-size: 20px; margin: var(--cr-toolbar-icon-margin, 0); } @media (prefers-color-scheme: light) { cr-icon-button { --cr-icon-button-fill-color: var( --cr-toolbar-search-field-input-icon-color, var(--google-grey-700)); --cr-icon-button-focus-outline-color: var( --cr-toolbar-icon-button-focus-outline-color, var(--cr-focus-outline-color)); } } @media (prefers-color-scheme: dark) { cr-icon-button { --cr-icon-button-fill-color: var( --cr-toolbar-search-field-input-icon-color, var(--google-grey-500)); } } #icon { transition: margin 150ms, opacity 200ms; } #prompt { color: var(--cr-toolbar-search-field-prompt-color, var(--google-grey-700)); opacity: 0; } @media (prefers-color-scheme: dark) { #prompt { color: var(--cr-toolbar-search-field-prompt-color, white); } } @media (prefers-color-scheme: dark) { #prompt { --cr-toolbar-search-field-prompt-opacity: 1; color: var(--cr-secondary-text-color, white); } } :host-context([chrome-refresh-2023]) #prompt { color: var(--cr-toolbar-search-field-prompt-color, var(--color-toolbar-search-field-foreground-placeholder, var(--cr-secondary-text-color))); } paper-spinner-lite { --paper-spinner-color: var(--cr-toolbar-search-field-input-icon-color, var(--google-grey-700)); height: var(--cr-icon-size); margin: var(--cr-toolbar-search-field-paper-spinner-margin, 0 6px); opacity: 0; padding: 6px; position: absolute; width: var(--cr-icon-size); } @media (prefers-color-scheme: dark) { paper-spinner-lite { --paper-spinner-color: var( --cr-toolbar-search-field-input-icon-color, white); } } paper-spinner-lite[active] { opacity: 1; } #prompt, paper-spinner-lite { transition: opacity 200ms; } /* Input field. */ #searchTerm { -webkit-font-smoothing: antialiased; flex: 1; line-height: 185%; margin: var(--cr-toolbar-search-field-term-margin, 0 2px); position: relative; } :host-context([chrome-refresh-2023]) #searchTerm { margin: var(--cr-toolbar-search-field-term-margin, 0); } label { bottom: 0; cursor: var(--cr-toolbar-search-field-cursor, text); left: 0; overflow: hidden; position: absolute; right: 0; top: 0; white-space: nowrap; } :host([has-search-text]) label { visibility: hidden; } input { -webkit-appearance: none; background: transparent; border: none; caret-color: var(--cr-toolbar-search-field-input-caret-color, var(--google-blue-700)); color: var(--cr-toolbar-search-field-input-text-color, var(--google-grey-900)); cursor: var(--cr-toolbar-search-field-cursor, text); font: inherit; outline: none; padding: 0; position: relative; width: 100%; } @media (prefers-color-scheme: dark) { input { color: var(--cr-toolbar-search-field-input-text-color, white); } } :host-context([chrome-refresh-2023]) input { caret-color: var(--cr-toolbar-serch-field-input-caret-color, currentColor); color: var(--cr-toolbar-search-field-input-text-color, var(--color-toolbar-search-field-foreground, var(--cr-fallback-color-on-surface))); font-size: 12px; font-weight: 500; } input[type='search']::-webkit-search-cancel-button { display: none; } :host([narrow]) { border-radius: var(--cr-toolbar-search-field-border-radius, 0); } /** Wide layout. */ :host(:not([narrow])) { background: var(--cr-toolbar-search-field-background, var(--google-grey-100)); border-radius: var(--cr-toolbar-search-field-border-radius, 46px); cursor: var(--cr-toolbar-search-field-cursor, text); max-width: var(--cr-toolbar-field-max-width, none); padding-inline-end: 0; width: var(--cr-toolbar-field-width, 680px); } @media (prefers-color-scheme: dark) { :host(:not([narrow])) { background: var(--cr-toolbar-search-field-background, rgba(0, 0, 0, 0.22)); } } :host-context([chrome-refresh-2023]):host(:not([narrow])) { background: none; border-radius: 100px; height: 36px; overflow: hidden; padding: 0 6px; position: relative; } #background, #stateBackground { display: none; } :host-context([chrome-refresh-2023]):host(:not([narrow])) #background { background: var(--cr-toolbar-search-field-background, var(--color-toolbar-search-field-background, var(--cr-fallback-color-surface))); border: 2px solid transparent; border-radius: inherit; display: block; inset: 0; pointer-events: none; position: absolute; z-index: -1; } :host-context([chrome-refresh-2023].focus-outline-visible):host( [search-focused_]:not([narrow])) { outline: 2px solid var(--cr-focus-outline-color); } :host-context([chrome-refresh-2023].focus-outline-visible):host( [search-focused_]:not([narrow])) #background { background-clip: padding-box; } :host-context([chrome-refresh-2023]) #stateBackground { display: block; inset: 0; pointer-events: none; position: absolute; } :host-context([chrome-refresh-2023]):host(:hover) #stateBackground { background: var(--color-toolbar-search-field-background-hover, var(--cr-hover-background-color)); } :host(:not([narrow]):not([showing-search])) #icon { opacity: var(--cr-toolbar-search-field-icon-opacity, .7); } :host(:not([narrow])) #prompt { opacity: var(--cr-toolbar-search-field-prompt-opacity, 1); } :host([narrow]) #prompt { opacity: var(--cr-toolbar-search-field-narrow-mode-prompt-opacity, 0); } :host([narrow]:not([showing-search])) #searchTerm { display: none; } /* Search open. */ :host([showing-search][spinner-active]) #icon { opacity: 0; } :host([narrow][showing-search]) { width: 100%; } :host([narrow][showing-search]) #icon, :host([narrow][showing-search]) paper-spinner-lite { /* 18px to line up with the Menu icon by default. */ margin-inline-start: var(--cr-toolbar-search-icon-margin-inline-start, 18px); } paper-ripple { display: none; } :host-context([chrome-refresh-2023]):host paper-ripple { color: var(--color-toolbar-search-field-background-pressed, var(--cr-active-background-color)); display: block; --paper-ripple-opacity: 1; } </style> <div id="background"></div> <div id="stateBackground"></div> <template is="dom-if" id="spinnerTemplate"> <paper-spinner-lite active="[[isSpinnerShown_]]"> </paper-spinner-lite> </template> <cr-icon-button id="icon" iron-icon="cr:search" title="[[label]]" dir="ltr" tabindex$="[[computeIconTabIndex_(narrow, hasSearchText)]]" aria-hidden$="[[computeIconAriaHidden_(narrow, hasSearchText)]]" on-click="onSearchIconClicked_" disabled="[[disabled]]"> </cr-icon-button> <div id="searchTerm"> <label id="prompt" for="searchInput" aria-hidden="true">[[label]]</label> <input id="searchInput" aria-labelledby="prompt" autocapitalize="off" autocomplete="off" type="search" on-input="onSearchTermInput" on-search="onSearchTermSearch" on-keydown="onSearchTermKeydown_" on-focus="onInputFocus_" on-blur="onInputBlur_" autofocus$="[[autofocus]]" spellcheck="false" disabled="[[disabled]]"> </div> <template is="dom-if" if="[[hasSearchText]]"> <cr-icon-button id="clearSearch" iron-icon="cr:cancel" title="[[clearLabel]]" on-click="clearSearch_" disabled="[[disabled]]"></cr-icon-button> </template>
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_toolbar/cr_toolbar_search_field.html
HTML
unknown
9,738
// 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_icon_button/cr_icon_button.js'; import '../cr_icons.css.js'; import '../icons.html.js'; import '../cr_shared_style.css.js'; import '../cr_shared_vars.css.js'; import '//resources/polymer/v3_0/paper-ripple/paper-ripple.js'; import '//resources/polymer/v3_0/paper-spinner/paper-spinner-lite.js'; import {FocusOutlineManager} from '//resources/js/focus_outline_manager.js'; import {PaperRippleBehavior} from '//resources/polymer/v3_0/paper-behaviors/paper-ripple-behavior.js'; import {DomIf, mixinBehaviors, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {CrSearchFieldMixin, CrSearchFieldMixinInterface} from '../cr_search_field/cr_search_field_mixin.js'; import {getTemplate} from './cr_toolbar_search_field.html.js'; export interface CrToolbarSearchFieldElement { $: { searchInput: HTMLInputElement, searchTerm: HTMLElement, spinnerTemplate: DomIf, }; } const CrToolbarSearchFieldElementBase = mixinBehaviors([PaperRippleBehavior], CrSearchFieldMixin(PolymerElement)) as { new (): PolymerElement & CrSearchFieldMixinInterface & PaperRippleBehavior, }; export class CrToolbarSearchFieldElement extends CrToolbarSearchFieldElementBase { static get is() { return 'cr-toolbar-search-field'; } static get template() { return getTemplate(); } static get properties() { return { narrow: { type: Boolean, reflectToAttribute: true, }, showingSearch: { type: Boolean, value: false, notify: true, observer: 'showingSearchChanged_', reflectToAttribute: true, }, disabled: { type: Boolean, value: false, reflectToAttribute: true, }, autofocus: { type: Boolean, value: false, reflectToAttribute: true, }, // When true, show a loading spinner to indicate that the backend is // processing the search. Will only show if the search field is open. spinnerActive: {type: Boolean, reflectToAttribute: true}, isSpinnerShown_: { type: Boolean, computed: 'computeIsSpinnerShown_(spinnerActive, showingSearch)', }, searchFocused_: {reflectToAttribute: true, type: Boolean, value: false}, }; } narrow: boolean; showingSearch: boolean; disabled: boolean; override autofocus: boolean; spinnerActive: boolean; private isSpinnerShown_: boolean; private searchFocused_: boolean; override ready() { super.ready(); this.addEventListener('click', e => this.showSearch_(e)); if (document.documentElement.hasAttribute('chrome-refresh-2023')) { FocusOutlineManager.forDocument(document); this.addEventListener('pointerdown', this.onPointerDown_.bind(this)); } } override getSearchInput(): HTMLInputElement { return this.$.searchInput; } isSearchFocused(): boolean { return this.searchFocused_; } showAndFocus() { this.showingSearch = true; this.focus_(); } override onSearchTermInput() { super.onSearchTermInput(); this.showingSearch = this.hasSearchText || this.isSearchFocused(); } private onSearchIconClicked_() { this.dispatchEvent(new CustomEvent( 'search-icon-clicked', {bubbles: true, composed: true})); } private focus_() { this.getSearchInput().focus(); } private computeIconTabIndex_(narrow: boolean): number { return narrow && !this.hasSearchText ? 0 : -1; } private computeIconAriaHidden_(narrow: boolean): string { return Boolean(!narrow || this.hasSearchText).toString(); } private computeIsSpinnerShown_(): boolean { const showSpinner = this.spinnerActive && this.showingSearch; if (showSpinner) { this.$.spinnerTemplate.if = true; } return showSpinner; } private onInputFocus_() { this.searchFocused_ = true; } private onInputBlur_() { this.searchFocused_ = false; if (!this.hasSearchText) { this.showingSearch = false; } } private onSearchTermKeydown_(e: KeyboardEvent) { if (e.key === 'Escape') { this.showingSearch = false; } } private showSearch_(e: Event) { if (e.target !== this.shadowRoot!.querySelector('#clearSearch')) { this.showingSearch = true; } } private clearSearch_() { this.setValue(''); this.focus_(); this.spinnerActive = false; } private showingSearchChanged_(_current: boolean, previous?: boolean) { // Prevent unnecessary 'search-changed' event from firing on startup. if (previous === undefined) { return; } if (this.showingSearch) { this.focus_(); return; } this.setValue(''); this.getSearchInput().blur(); } private onPointerDown_(event: PointerEvent) { // Hide the paper-ripple if the pointerdown event happened on a // cr-icon-button. noink is a property inherited from PaperRippleBehavior. this.noink = event.composedPath().some(item => { return (item as HTMLElement).tagName === 'CR-ICON-BUTTON'; }); this.ensureRipple(); } } declare global { interface HTMLElementTagNameMap { 'cr-toolbar-search-field': CrToolbarSearchFieldElement; } } customElements.define( CrToolbarSearchFieldElement.is, CrToolbarSearchFieldElement);
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_toolbar/cr_toolbar_search_field.ts
TypeScript
unknown
5,473
// 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 */ function CrSearchFieldMixinInterface() {} /** * @param {string} value * @param {boolean=} noEvent */ CrSearchFieldMixinInterface.prototype.setValue = function(value, noEvent) {}; /** * @constructor * @extends {HTMLElement} * @implements {CrSearchFieldMixinInterface} */ function CrToolbarSearchFieldElement() {} /** @return {!HTMLInputElement} */ CrToolbarSearchFieldElement.prototype.getSearchInput = function() {}; CrToolbarSearchFieldElement.prototype.showAndFocus = function() {}; /** @return {boolean} */ CrToolbarSearchFieldElement.prototype.isSearchFocused = function() {};
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_toolbar/cr_toolbar_search_field_externs.js
JavaScript
unknown
880
<style> :host { background-color: white; border-bottom: 1px solid var(--google-grey-300); bottom: 0; color: var(--cr-primary-text-color); display: flex; left: 0; opacity: 0; padding-inline-start: var(--cr-toolbar-field-margin, 0); pointer-events: none; position: absolute; right: 0; top: 0; transition: opacity var(--cr-toolbar-overlay-animation-duration), visibility var(--cr-toolbar-overlay-animation-duration); visibility: hidden; } @media (prefers-color-scheme: dark) { :host { background-color: var(--google-grey-900); background-image: linear-gradient(rgba(255, 255, 255, .04), rgba(255, 255, 255, .04)); border-bottom-color: var(--cr-separator-color); } } :host([show]) { opacity: 1; pointer-events: initial; visibility: initial; } #overlay-content { align-items: center; display: flex; flex: 1; margin: 0 auto; max-width: var(--cr-toolbar-selection-overlay-max-width, initial); padding: 0 var(--cr-toolbar-selection-overlay-padding, 24px); } #number-selected { flex: 1; } cr-icon-button { height: 36px; margin-inline-end: 24px; margin-inline-start: 2px; width: 36px; } #slot { align-items: center; display: flex; gap: var(--cr-toolbar-selection-overlay-slot-gap, 16px); margin-inline-start: 8px; } </style> <template is="dom-if" if="[[hasShown_]]"> <div id="overlay-content"> <cr-icon-button part="clearIcon" title="[[cancelLabel]]" iron-icon="cr:clear" on-click="onClearSelectionClick_"></cr-icon-button> <div id="number-selected">[[selectionLabel_]]</div> <div id="slot"><slot></slot></div> </div> </template>
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_toolbar/cr_toolbar_selection_overlay.html
HTML
unknown
2,052
// 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 Element which displays the number of selected items with * Cancel/Delete buttons, designed to be used as an overlay on top of * <cr-toolbar>. See <history-toolbar> for an example usage. * * Note that the embedder is expected to set position: relative to make the * absolute positioning of this element work, and the cr-toolbar should have the * has-overlay attribute set when its overlay is shown to prevent access through * tab-traversal. */ import '../cr_button/cr_button.js'; import '../cr_icon_button/cr_icon_button.js'; import '../cr_shared_vars.css.js'; import '../icons.html.js'; import {IronA11yAnnouncer} from '//resources/polymer/v3_0/iron-a11y-announcer/iron-a11y-announcer.js'; import {Debouncer, microTask, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {CrButtonElement} from '../cr_button/cr_button.js'; import {getTemplate} from './cr_toolbar_selection_overlay.html.js'; export class CrToolbarSelectionOverlayElement extends PolymerElement { static get is() { return 'cr-toolbar-selection-overlay'; } static get template() { return getTemplate(); } static get properties() { return { show: { type: Boolean, observer: 'onShowChanged_', reflectToAttribute: true, }, cancelLabel: String, selectionLabel: String, hasShown_: Boolean, selectionLabel_: String, }; } static get observers() { return [ 'updateSelectionLabel_(show, selectionLabel)', ]; } show: boolean; cancelLabel: string; selectionLabel: string; private hasShown_: boolean; private selectionLabel_: string; private debouncer_: Debouncer; override ready() { super.ready(); this.setAttribute('role', 'toolbar'); } get deleteButton(): CrButtonElement { return this.shadowRoot!.querySelector<CrButtonElement>('#delete')!; } private fire_(eventName: string, detail?: any) { this.dispatchEvent( new CustomEvent(eventName, {bubbles: true, composed: true, detail})); } private onClearSelectionClick_() { this.fire_('clear-selected-items'); } private updateSelectionLabel_() { // Do this update in a microtask to ensure |show| and |selectionLabel| // are both updated. this.debouncer_ = Debouncer.debounce(this.debouncer_, microTask, () => { this.selectionLabel_ = this.show ? this.selectionLabel : this.selectionLabel_; this.setAttribute('aria-label', this.selectionLabel_); IronA11yAnnouncer.requestAvailability(); this.fire_('iron-announce', {text: this.selectionLabel}); }); } private onShowChanged_() { if (this.show) { this.hasShown_ = true; } } } declare global { interface HTMLElementTagNameMap { 'cr-toolbar-selection-overlay': CrToolbarSelectionOverlayElement; } } customElements.define( CrToolbarSelectionOverlayElement.is, CrToolbarSelectionOverlayElement);
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_toolbar/cr_toolbar_selection_overlay.ts
TypeScript
unknown
3,114
<style> :host { display: block; outline: none; overflow: auto; } </style>
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_tree/cr_tree.html
HTML
unknown
90
// 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 {assert, assertNotReached} from '//resources/js/assert_ts.js'; import {isMac} from '//resources/js/platform.js'; import {getTemplate} from './cr_tree.html.js'; import {CrTreeBaseElement} from './cr_tree_base.js'; import {CrTreeItemElement, SELECTED_ATTR} from './cr_tree_item.js'; /** * @fileoverview cr-tree is a container for a tree structure. Items can be added * or removed from the tree using the add/addAt/removeItem methods. Adding items * declaratively is not currently supported, as this class is primarily intended * to replace cr.ui.Tree, which is used for cases of creating trees at runtime * (e.g. from backend data). */ /** * Helper function that returns the next visible tree item. */ function getNext(item: CrTreeBaseElement): CrTreeBaseElement|null { if (item.expanded) { const firstChild = item.items[0]; if (firstChild) { return firstChild; } } return getNextHelper(item); } /** * Another helper function that returns the next visible tree item. */ function getNextHelper(item: CrTreeBaseElement|null): CrTreeBaseElement|null { if (!item) { return null; } const nextSibling = item.nextElementSibling; if (nextSibling) { assert(nextSibling.tagName === 'CR-TREE-ITEM'); return nextSibling as CrTreeBaseElement; } const parent = item.parentItem; if (!parent || parent.tagName === 'CR-TREE') { return null; } return getNextHelper(item.parentItem); } /** * Helper function that returns the previous visible tree item. */ function getPrevious(item: CrTreeBaseElement): CrTreeBaseElement|null { const previousSibling = item.previousElementSibling; if (previousSibling && previousSibling.tagName === 'CR-TREE-ITEM') { return getLastHelper(previousSibling as CrTreeBaseElement); } return item.parentItem; } /** * Helper function that returns the last visible tree item in the subtree. */ function getLastHelper(item: CrTreeBaseElement): CrTreeBaseElement|null { if (item.expanded && item.hasChildren) { const lastChild = item.items[item.items.length - 1]!; return getLastHelper(lastChild); } return item; } export class CrTreeElement extends CrTreeBaseElement { static override get template() { return getTemplate(); } private selectedItem_: CrTreeBaseElement|null = null; /** * Initializes the element. */ connectedCallback() { if (!this.hasAttribute('role')) { this.setAttribute('role', 'tree'); } this.addEventListener('keydown', this.handleKeyDown.bind(this)); } // CrTreeBase implementation: /** * The depth of the node. This is 0 for the tree itself. */ override get depth(): number { return 0; } override get itemsRoot(): DocumentFragment|HTMLElement { return this.shadowRoot!; } // These two methods should never be called for the tree itself. override set depth(_depth: number) { assertNotReached(); } override setParent(_parent: CrTreeBaseElement) { assertNotReached(); } /** * The selected tree item or null if none. */ override get selectedItem(): CrTreeBaseElement|null { return this.selectedItem_ || null; } override set selectedItem(item: CrTreeBaseElement|null) { const oldSelectedItem = this.selectedItem_; if (oldSelectedItem !== item) { // Set the selectedItem_ before deselecting the old item since we only // want one change when moving between items. this.selectedItem_ = item; if (oldSelectedItem) { oldSelectedItem.toggleAttribute(SELECTED_ATTR, false); } if (item) { item.toggleAttribute(SELECTED_ATTR, true); if (item.id) { this.setAttribute('aria-activedescendant', item.id); } if (this.matches(':focus-within') || this.shadowRoot!.activeElement) { (item as CrTreeItemElement).rowElement.focus(); } } else { this.removeAttribute('aria-activedescendant'); } this.dispatchEvent( new CustomEvent('cr-tree-change', {bubbles: true, composed: true})); } } override addAt(child: CrTreeBaseElement, index: number) { super.addAt(child, index); // aria-owns doesn't work well for the tree because the treeitem role is // set on the rowElement within cr-tree-item's shadow DOM. Set the size // here, so the correct number of items is read. this.setAttribute('aria-setsize', this.items.length.toString()); } /** * Handles keydown events on the tree and updates selection and exanding * of tree items. */ handleKeyDown(e: KeyboardEvent) { let itemToSelect: CrTreeBaseElement|null = null; if (e.ctrlKey) { return; } const item = this.selectedItem; if (!item) { return; } const rtl = getComputedStyle(item).direction === 'rtl'; switch (e.key) { case 'ArrowUp': itemToSelect = getPrevious(item); break; case 'ArrowDown': itemToSelect = getNext(item); break; case 'ArrowLeft': case 'ArrowRight': // Don't let back/forward keyboard shortcuts be used. if (!isMac && e.altKey || isMac && e.metaKey) { break; } if (e.key === 'ArrowLeft' && !rtl || e.key === 'ArrowRight' && rtl) { if (item.expanded) { item.expanded = false; } else { itemToSelect = item.parentItem; } } else { if (!item.expanded) { item.expanded = true; } else { itemToSelect = item.items[0] || null; } } break; case 'Home': itemToSelect = this.items[0] || null; break; case 'End': itemToSelect = this.items[this.items.length - 1] || null; break; } if (itemToSelect) { itemToSelect.toggleAttribute(SELECTED_ATTR, true); e.preventDefault(); } } setIconVisibility(visibility: string) { this.setAttribute('icon-visibility', visibility); } } declare global { interface HTMLElementTagNameMap { 'cr-tree': CrTreeElement; } } customElements.define('cr-tree', CrTreeElement);
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_tree/cr_tree.ts
TypeScript
unknown
6,284
// 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 {assert} from '//resources/js/assert_ts.js'; import {CustomElement} from '//resources/js/custom_element.js'; export const EXPANDED_ATTR: string = 'expanded'; // Encapuslates shared behavior of cr-trees and the cr-tree-items that they // contain. This reduces code duplication for e.g. adding/removing children and // facilitates writing methods navigating the full tree structure (cr-tree and // all cr-tree-item descendants), without introducing circular dependencies. export abstract class CrTreeBaseElement extends CustomElement { static override get template() { return window.trustedTypes ? window.trustedTypes.emptyHTML : ('' as string); } static get observedAttributes() { return ['icon-visibility']; } detail: object = {}; private parent_: CrTreeBaseElement|null = null; attributeChangedCallback(name: string, _oldValue: string, newValue: string) { assert(name === 'icon-visibility'); this.items.forEach(item => item.setAttribute(name, newValue)); } setParent(parent: CrTreeBaseElement) { this.parent_ = parent; } get items(): CrTreeBaseElement[] { return Array.from(this.itemsRoot.querySelectorAll('cr-tree-item')) as CrTreeBaseElement[]; } abstract get depth(): number; abstract set depth(depth: number); abstract get itemsRoot(): DocumentFragment|HTMLElement; abstract get selectedItem(): CrTreeBaseElement|null; abstract set selectedItem(item: CrTreeBaseElement|null); /** * Adds a tree item as a child. */ add(child: CrTreeBaseElement) { this.addAt(child, -1); } /** * Adds a tree item as a child at a given index. */ addAt(child: CrTreeBaseElement, index: number) { assert(child.tagName === 'CR-TREE-ITEM'); child.setParent(this); if (index === -1 || index >= this.items.length) { this.itemsRoot.appendChild(child); } else { this.itemsRoot.insertBefore(child, this.items[index] || null); } if (this.items.length === 1) { this.setHasChildren(true); } child.depth = this.depth + 1; child.setAttribute( 'icon-visibility', this.getAttribute('icon-visibility') || ''); } removeTreeItem(child: CrTreeBaseElement) { this.itemsRoot.removeChild(child); if (this.items.length === 0) { this.setHasChildren(false); } } get parentItem(): CrTreeBaseElement|null { return this.parent_; } /** * The tree that the tree item belongs to or null of no added to a tree. */ get tree(): CrTreeBaseElement|null { if (this.tagName === 'CR-TREE') { return this; } if (!this.parent_) { return null; } return this.parent_.tree; } get hasChildren(): boolean { return !!this.items[0]; } setHasChildren(b: boolean) { this.toggleAttribute('has-children', b); } get expanded() { return this.hasAttribute(EXPANDED_ATTR); } set expanded(expanded: boolean) { this.toggleAttribute(EXPANDED_ATTR, expanded); } }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_tree/cr_tree_base.ts
TypeScript
unknown
3,121
<style> :host { --white-100: rgba(255, 255, 255, 0); --white-80: rgba(255, 255, 255, .8); --leaf-icon: var(--cr-tree-item-leaf-icon, url(chrome://theme/IDR_FOLDER_CLOSED)); } :host .tree-row { align-items: center; background-color: var(--white-100); /* transparent white */ border: var(--cr-tree-row-border, 1px solid var(--white-100)); border-radius: var(--cr-tree-row-border-radius, 2px); color: black; cursor: default; display: flex; line-height: var(--cr-tree-row-line-height, 28px); padding: 0 3px; position: relative; user-select: none; white-space: nowrap; } .expand-icon { background: url(chrome://resources/images/tree_triangle.svg) no-repeat center center; background-size: 8px 5.5px; height: 16px; min-width: 16px; opacity: .6; transform: rotate(-90deg); transition: all 150ms; width: 16px; } :host-context([dir=rtl]) .expand-icon { transform: rotate(90deg); } :host([expanded]) .expand-icon { background-image: url(chrome://resources/images/tree_triangle.svg); opacity: .5; transform: rotate(0); } .tree-row .expand-icon { visibility: hidden; } :host(:not([has-children])) .tree-row .expand-icon { visibility: hidden; } :host([may-have-children]) .tree-row .expand-icon { visibility: visible; } :host([force-hover-style]) .tree-row, .tree-row:hover { background-color: hsl(214, 91%, 97%); border-color: hsl(214, 91%, 85%); z-index: 1; } :host([selected]) .tree-row { background-color: var(--cr-tree-row-selected-color, hsl(0, 0%, 90%)); background-image: var(--cr-tree-row-selected-image, linear-gradient(var(--white-80), var(--white-100))); border-color: hsl(0, 0%, 85%); z-index: 2; } :host([selected]) .tree-row:hover, :host([selected]) .tree-row:focus { background-color: hsl(214, 91%, 89%); border-color: rgb(125, 162, 206); } :host([expanded]) .tree-children { display: block; } .tree-children { display: none; } #extra-aria-label { clip: rect(0,0,0,0); display: inline-block; position: fixed; } :host .tree-row > * { box-sizing: border-box; display: inline-block; } .tree-label-icon { background-position: 0 50%; background-repeat: no-repeat; height: 20px; min-width: 20px; width: 20px; } .tree-label { user-select: var(--cr-tree-label-user-select, none); white-space: pre; } .tree-label-icon, :host([may-have-children]) .tree-row > .tree-label-icon { background-image: url(chrome://theme/IDR_FOLDER_CLOSED); } :host(:not([may-have-children])) .tree-row > .tree-label-icon { background-image: var(--leaf-icon); } <if expr="is_macosx or is_ios"> @media (prefers-color-scheme: dark) { .tree-label-icon, :host([may-have-children]) .tree-row > .tree-label-icon { background-image: url(chrome://theme/IDR_FOLDER_CLOSED_WHITE); } :host(:not([may-have-children])) .tree-row > .tree-label-icon { background-image: var(--leaf-icon); } } </if> <if expr="not is_macosx and not is_ios"> :host([expanded]) > .tree-row > .tree-label-icon { background-image: url(chrome://theme/IDR_FOLDER_OPEN); } </if> :host-context([dir=rtl]) .tree-label-icon, :host-context([dir=rtl]) :host([may-have-children]) .tree-row > .tree-label-icon, :host-context([dir=rtl]) :host([expanded]) > .tree-row > .tree-label-icon { transform: scaleX(-1); } :host([icon-visibility=hidden]) .tree-label-icon { display: none; } :host([icon-visibility=parent]) .tree-label-icon, :host([icon-visibility=parent]) .tree-row:not([has-children]) > .tree-label-icon { background-image: none; } /* We need to ensure that even empty labels take up space */ .tree-label:empty::after { content: ' '; white-space: pre; } @media(forced-colors) { :host([selected]) .tree-row, .tree-row:hover, :host([selected]) .tree-row:hover { background-color: Highlight; background-image: none; color: HighlightText; forced-color-adjust: none; } } </style> <div class="tree-row" role="treeitem" aria-owns="tree-children" aria-labelledby="label extra-aria-label"> <span class="expand-icon"></span> <span class="tree-label-icon"></span> <span class="tree-label" id="label"></span> <span id="extra-aria-label"></span> </div> <div class="tree-children" id="tree-children" role="group"></div>
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_tree/cr_tree_item.html
HTML
unknown
4,566
// 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 {assert, assertNotReached} from '//resources/js/assert_ts.js'; import {CrTreeBaseElement, EXPANDED_ATTR} from './cr_tree_base.js'; import {getTemplate} from './cr_tree_item.html.js'; /** * @fileoverview cr-tree-item represents a node in a tree structure. Child items * can be added or removed using the add/addAt/removeItem methods. A parent can * be set using the setParent() method; the parent may be a cr-tree or * cr-tree-item. Adding items declaratively is not currently supported, as this * class is primarily intended to replace cr.ui.TreeItem, which is used for * cases of creating trees at runtime (e.g. from backend data). */ export const SELECTED_ATTR: string = 'selected'; export const MAY_HAVE_CHILDREN_ATTR: string = 'may-have-children'; const INDENT_PX: number = 20; let treeItemAutoGeneratedIdCounter: number = 0; // Returns true if |root| has |el| as a descendant. function hasDescendant( root: CrTreeBaseElement, el: CrTreeBaseElement): boolean { const itemsToCheck = [root]; while (itemsToCheck.length > 0) { const item = itemsToCheck.shift()!; if (item === el) { return true; } if (item.items.includes(el)) { return true; } itemsToCheck.push(...item.items); } return false; } export class CrTreeItemElement extends CrTreeBaseElement { static override get template() { return getTemplate(); } static override get observedAttributes() { return super.observedAttributes.concat([SELECTED_ATTR, EXPANDED_ATTR]); } private label_: string = ''; private extraAriaLabel_: string = ''; private depth_: number = 0; private rowElement_: HTMLElement|null = null; connectedCallback() { this.id = 'tree-item-autogen-id-' + treeItemAutoGeneratedIdCounter++; this.labelElement.textContent = this.label_; const extraAriaLabel = this.shadowRoot!.querySelector<HTMLElement>('#extra-aria-label'); assert(extraAriaLabel); extraAriaLabel.textContent = this.extraAriaLabel_; this.toggleAttribute(SELECTED_ATTR, false); this.rowElement.setAttribute('aria-selected', 'false'); const expand = this.shadowRoot!.querySelector<HTMLElement>('.expand-icon'); assert(expand); expand.addEventListener('click', this.handleExpandClick_.bind(this)); expand.addEventListener( 'mousedown', this.handleExpandMouseDown_.bind(this)); this.addEventListener('click', this.handleClick_.bind(this)); this.addEventListener('mousedown', this.handleMouseDown_.bind(this)); this.addEventListener('dblclick', this.handleDblClick_.bind(this)); } override attributeChangedCallback( name: string, oldValue: string, newValue: string) { if (name === SELECTED_ATTR) { this.onSelectedChange_(newValue === ''); return; } if (name === EXPANDED_ATTR) { this.onExpandedChange_(newValue === ''); return; } super.attributeChangedCallback(name, oldValue, newValue); } forceHoverStyle(hover: boolean) { this.toggleAttribute('force-hover-style', hover); } private onSelectedChange_(selected: boolean) { const rowElement = this.rowElement; if (selected) { rowElement.setAttribute('tabIndex', '0'); this.reveal(); this.labelElement.scrollIntoViewIfNeeded(); if (this.tree) { this.tree.selectedItem = this; } rowElement.setAttribute('aria-selected', 'true'); } else if (this.tree && this.tree.selectedItem === this) { this.tree.selectedItem = null; rowElement.setAttribute('aria-selected', 'false'); rowElement.setAttribute('tabIndex', '-1'); } else { rowElement.setAttribute('aria-selected', 'false'); rowElement.setAttribute('tabIndex', '-1'); } } private onExpandedChange_(expanded: boolean) { const rowElement = this.rowElement; if (expanded) { if (this.hasAttribute(MAY_HAVE_CHILDREN_ATTR)) { rowElement.setAttribute('aria-expanded', 'true'); this.dispatchEvent(new CustomEvent( 'cr-tree-item-expand', {bubbles: true, composed: true, detail: true})); this.scrollIntoViewIfNeeded(); } return; } if (this.tree && !this.hasAttribute(SELECTED_ATTR)) { const oldSelected = this.tree.selectedItem; if (oldSelected && hasDescendant(this, oldSelected)) { this.toggleAttribute(SELECTED_ATTR, true); } } if (this.hasAttribute(MAY_HAVE_CHILDREN_ATTR)) { rowElement.setAttribute('aria-expanded', 'false'); } else { rowElement.removeAttribute('aria-expanded'); } this.dispatchEvent(new CustomEvent( 'cr-tree-item-collapse', {bubbles: true, composed: true, detail: true})); } // CrTreeBaseElement implementation: override get depth(): number { return this.depth_; } override set depth(depth: number) { if (depth !== this.depth_) { const rowDepth = Math.max(0, depth - 1); const row = this.shadowRoot!.querySelector<HTMLElement>('.tree-row'); assert(row); row.style.paddingInlineStart = rowDepth * INDENT_PX + 'px'; this.rowElement.setAttribute('aria-level', depth.toString()); this.depth_ = depth; this.items.forEach(item => item.depth = depth + 1); } } override get itemsRoot(): DocumentFragment|HTMLElement { const root = this.shadowRoot!.querySelector<HTMLElement>('.tree-children'); assert(root); return root; } override removeTreeItem(child: CrTreeItemElement) { // If we removed the selected item we should become selected. const tree = this.tree; assert(tree); const selectedItem = tree.selectedItem; if (selectedItem && hasDescendant(child, selectedItem)) { this.toggleAttribute(SELECTED_ATTR, true); } super.removeTreeItem(child); } /** * Whether the tree item has children. */ override setHasChildren(hasChildren: boolean) { super.setHasChildren(hasChildren); if (hasChildren) { this.toggleAttribute(MAY_HAVE_CHILDREN_ATTR, true); this.rowElement.toggleAttribute('aria-expanded', this.expanded); } } // These methods shouldn't be called on a tree item. override set selectedItem(_item: CrTreeBaseElement|null) { assertNotReached(); } override get selectedItem() { return null; } // Mouse event handlers private handleMouseDown_(e: MouseEvent) { if (e.button === 2) { // right this.handleClick_(e); } } private handleExpandMouseDown_(e: MouseEvent) { if (e.button === 2) { // right this.handleExpandClick_(e); } } /** * Handles double click events on the tree item. */ private handleDblClick_(e: Event) { const expanded = this.expanded; this.expanded = !expanded; e.stopPropagation(); } /** * Called when the user clicks on a tree item's expand icon. */ private handleExpandClick_(e: Event) { this.expanded = !this.expanded; e.stopPropagation(); } /** * Called when the user clicks on a tree item. */ private handleClick_(e: Event) { this.toggleAttribute(SELECTED_ATTR, true); e.stopPropagation(); } // Additional methods unique to CrTreeItem: /** * Expands all parent items. */ reveal() { let pi = this.parentItem; while (pi) { pi.expanded = true; pi = pi.parentItem; } } /** * The element containing the label text. */ get labelElement(): HTMLElement { const labelEl = this.shadowRoot!.querySelector<HTMLElement>('.tree-label'); assert(labelEl); return labelEl; } get rowElement(): HTMLElement { if (!this.rowElement_) { this.rowElement_ = this.shadowRoot!.querySelector<HTMLElement>('.tree-row'); } assert(this.rowElement_); return this.rowElement_; } /** * The label text. */ get label(): string { return this.label_; } set label(s: string) { this.label_ = s; if (this.shadowRoot && this.shadowRoot.querySelector('.tree-label')) { this.labelElement.textContent = s; } } setExtraAriaLabel(s: string) { this.extraAriaLabel_ = s; if (this.shadowRoot && this.shadowRoot.querySelector('#extra-aria-label')) { this.shadowRoot!.querySelector<HTMLElement>( '#extra-aria-label')!.textContent = s; } } } declare global { interface HTMLElementTagNameMap { 'cr-tree-item': CrTreeItemElement; } } customElements.define('cr-tree-item', CrTreeItemElement);
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_tree/cr_tree_item.ts
TypeScript
unknown
8,623
<style include="cr-hidden-style cr-icons"> :host { --cr-url-list-item-image-container-border_: 2px solid white; /* Intentionally 1px higher than the inherited border radius to avoid * anti-aliasing issues. */ --cr-url-list-item-image-container-border-radius_: 5px; align-items: center; box-sizing: border-box; cursor: default; display: flex; height: 52px; padding: 6px 16px; width: 100%; } @media (prefers-color-scheme: dark) { :host { --cr-url-list-item-image-container-border_: 2px solid black; } } :host-context([chrome-refresh-2023]):host { height: 48px; padding: 4px 16px; } :host-context([chrome-refresh-2023]):host([size=medium]), :host-context([chrome-refresh-2023]):host([size=large]) { --cr-url-list-item-image-container-border-radius_: 9px; } :host([size=compact]) { height: 32px; padding: 8px 20px; } :host([size=large]) { height: 68px; padding: 6px 16px; } :host-context([chrome-refresh-2023]):host([size=compact]), :host-context([chrome-refresh-2023]):host([size=large]) { padding: 6px 16px; } :host-context([chrome-refresh-2023]):host([size=compact]) { height: 36px; } :host-context([chrome-refresh-2023]):host([size=large]) { height: 68px; } :host(.hovered), :host([force-hover]) { background: var(--cr-hover-background-color); } :host(.active), :host-context(.focus-outline-visible):host(:focus-within) { background: var(--cr-active-background-color); } ::slotted([slot=prefix]) { margin-inline-end: 16px; } #iconContainer { align-items: center; background: var(--google-grey-50); border-radius: 4px; display: flex; flex-shrink: 0; height: 40px; justify-content: center; margin-inline-end: 16px; overflow: hidden; width: 40px; } @media (prefers-color-scheme: dark) { #iconContainer { --cr-icon-color: var(--google-grey-100); background: rgba(var(--google-grey-200-rgb), .11); } } :host([size=compact]) #iconContainer { background: transparent; height: 16px; margin-inline-end: 12px; width: 16px; } :host-context([chrome-refresh-2023]) #iconContainer { background: var(--color-list-item-url-favicon-background, var(--cr-fallback-color-neutral-container)); } :host-context([chrome-refresh-2023]):host([is-folder_]) #iconContainer { background: var(--color-list-item-folder-icon-background, var(--cr-fallback-color-primary-container)); color: var(--color-list-item-folder-icon-foreground, var(--cr-fallback-color-on-primary-container)); } :host-context([chrome-refresh-2023]):host([size=compact]) #iconContainer { height: 24px; margin-inline-end: 8px; width: 24px; } :host([size=large]) #iconContainer { height: 56px; margin-inline-end: 16px; width: 56px; } :host-context([chrome-refresh-2023]):host([size=medium]) #iconContainer, :host-context([chrome-refresh-2023]):host([size=large]) #iconContainer { border-radius: 8px; } .favicon { background-position: center center; background-repeat: no-repeat; height: 16px; width: 16px; } :host([size=large]) .folder-and-count { align-items: center; display: grid; grid-template-columns: repeat(2, 50%); grid-template-rows: repeat(2, 50%); height: 100%; justify-items: center; width: 100%; } .folder-and-count .image-container { border-bottom: var(--cr-url-list-item-image-container-border_); border-radius: 0 var(--cr-url-list-item-image-container-border-radius_) 0 0; box-sizing: border-box; height: 100%; overflow: hidden; width: 100%; } :host-context([dir=rtl]) .folder-and-count .image-container { border-radius: var(--cr-url-list-item-image-container-border-radius_) 0 0 0; } .folder-and-count .image-container img { height: 100%; object-fit: cover; opacity: 95%; width: 100%; } /* If there is only 2 imgs, span the 1st image across both rows. */ .folder-and-count:not(:has(div:nth-child(3))) .image-container:first-of-type { border-bottom: none; border-inline-end: var(--cr-url-list-item-image-container-border_); border-radius: var(--cr-url-list-item-image-container-border-radius_) 0 0 var(--cr-url-list-item-image-container-border-radius_); grid-row: 1 / span 2; } :host-context([dir=rtl]) .folder-and-count:not(:has(div:nth-child(3))) .image-container:first-of-type { border-radius: 0 var(--cr-url-list-item-image-container-border-radius_) var(--cr-url-list-item-image-container-border-radius_) 0; } /* If there is only 1 img, span the entire grid. */ .folder-and-count:not(:has(div:nth-child(2))) .image-container:first-of-type { border: none; grid-column: 1 / span 2; grid-row: 1 / span 2; } .folder { --cr-icon-color: currentColor; height: 16px; margin: 0; width: 16px; } .count { --cr-url-list-item-count-border-radius: 4px; display: none; } :host([size=large]) .count { align-items: center; background: var(--google-grey-50); border-radius: var(--cr-url-list-item-count-border-radius) 0 0 0; display: flex; grid-column: 2; grid-row: 2; height: 100%; justify-content: center; width: 100%; z-index: 1; } :host-context([dir=rtl]):host([size=large]) .count { border-radius: 0 var(--cr-url-list-item-count-border-radius) 0 0; } .folder-and-count:has(div:nth-child(2)) .count { border-radius: 0; } @media (prefers-color-scheme: dark) { :host([size=large]) .count { background: rgba(var(--google-grey-200-rgb), .11); } } :host-context([chrome-refresh-2023]):host([size=large]) .count { background: var(--color-list-item-folder-icon-background, var(--cr-fallback-color-primary-container)); } .image-container { /* * Acts as an overlay to images with some transparency, to ensure contrast * against the row background. */ background: black; border-radius: var(--cr-url-list-item-image-container-border-radius_); height: 100%; width: 100%; } @media (prefers-color-scheme: dark) { .image-container { background: transparent; } } .metadata { display: flex; flex-direction: column; gap: 8px; min-width: 0; width: 100%; } :host([size=compact]) .metadata { align-items: center; flex-direction: row; } :host-context([chrome-refresh-2023]):host([size=compact]) .metadata, :host-context([chrome-refresh-2023]):host([size=medium]) .metadata { gap: 4px; } :host([size=large]) .metadata { gap: 4px; } :host-context([chrome-refresh-2023]):host([size=large]) .metadata { gap: 2px; } .title { appearance: none; background: transparent; border: 0; color: var(--cr-primary-text-color); display: inline; font-size: 13px; font-weight: 400; padding: 0; text-align: start; } :host-context([chrome-refresh-2023]) .title { font-size: 12px; font-weight: 500; } .title:focus { outline: none; } .descriptions { align-items: center; display: flex; gap: 3px; height: 14px; } :host([size=compact]) .descriptions { display: contents; } :host([size=large]) .descriptions { align-items: flex-start; flex-direction: column; gap: 4px; height: auto; } :host(:not([has-descriptions_])) .descriptions { display: none; } .description { color: var(--cr-secondary-text-color); flex-shrink: 0; font-size: 13px; font-weight: 400; } :host-context([chrome-refresh-2023]) .description { font-size: 11px; font-weight: 400; } .title, .description { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .badges { align-items: flex-start; display: flex; gap: 4px; min-width: fit-content; } :host(:not([has-badges_])) .badges { display: none; } .suffix-icons { align-items: center; display: flex; flex-shrink: 0; margin-inline-start: auto; } ::slotted(cr-icon-button[slot=suffix-icon]) { --cr-icon-button-icon-size: 16px; --cr-icon-button-size: 24px; --cr-icon-button-margin-end: 0; --cr-icon-button-margin-start: 0; display: none; } :host(.hovered) ::slotted(cr-icon-button[slot=suffix-icon]), :host-context(.focus-outline-visible):host(:focus-within) ::slotted(cr-icon-button[slot=suffix-icon]), :host([always-show-suffix-icons]) ::slotted(cr-icon-button[slot=suffix-icon]) { display: block; } .url-image { height: 100%; object-fit: cover; object-position: center center; opacity: 95%; width: 100%; } </style> <slot name="prefix"></slot> <div id="iconContainer"> <div class="favicon" hidden$="[[!shouldShowFavicon_(url, size, imageUrls)]]" style$="background-image: [[getFavicon_(url)]];"> </div> <div class="image-container" hidden$="[[!shouldShowUrlImage_( url, size, imageUrls, firstImageLoaded_)]]"> <img class="url-image" is="cr-auto-img" auto-src="[[imageUrls.0]]"> </div> <div class="folder-and-count" hidden$="[[!shouldShowFolderCount_(url, count)]]"> <template is="dom-if" if="[[shouldShowFolderImages_(size)]]" restamp> <template is="dom-repeat" items="[[imageUrls]]" filter="shouldShowImageUrl_"> <div class="image-container" hidden$="[[!firstImageLoaded_]]"> <img class="folder-image" is="cr-auto-img" auto-src="[[item]]"> </div> </template> </template> <slot id="folder-icon" name="folder-icon"> <div class="folder cr-icon icon-folder-open" hidden$="[[!shouldShowFolderIcon_(size, imageUrls)]]"></div> </slot> <div class="count">[[getDisplayedCount_(count)]]</div> </div> </div> <slot name="content"> <div id="metadata" class="metadata"> <button class="title" aria-label="[[getButtonAriaLabel_(title, buttonAriaLabel)]]" aria-description="[[ getButtonAriaDescription_(description, buttonAriaDescription)]]"> [[title]] </button> <div class="descriptions"> <div class="description" hidden$="[[!description]]">[[description]]</div> <div class="badges"> <slot id="badges" name="badges" on-slotchange="onBadgesSlotChange_"> </slot> </div> </div> </div> </slot> <div class="suffix-icons"> <slot name="suffix-icon"></slot> </div>
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_url_list_item/cr_url_list_item.html
HTML
unknown
10,632
// 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. import '../cr_hidden_style.css.js'; import '../cr_icons.css.js'; import '../cr_shared_vars.css.js'; import '//resources/cr_elements/cr_auto_img/cr_auto_img.js'; import {assert} from '//resources/js/assert_ts.js'; import {FocusOutlineManager} from '//resources/js/focus_outline_manager.js'; import {getFaviconForPageURL} from '//resources/js/icon.js'; import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {MouseHoverableMixin} from '../mouse_hoverable_mixin.js'; import {getTemplate} from './cr_url_list_item.html.js'; export enum CrUrlListItemSize { COMPACT = 'compact', MEDIUM = 'medium', LARGE = 'large', } export interface CrUrlListItemElement { $: { badges: HTMLSlotElement, description: HTMLSlotElement, }; } const CrUrlListItemElementBase = MouseHoverableMixin(PolymerElement); export class CrUrlListItemElement extends CrUrlListItemElementBase { static get is() { return 'cr-url-list-item'; } static get template() { return getTemplate(); } static get properties() { return { buttonAriaLabel: String, buttonAriaDescription: String, count: Number, description: String, url: String, title: { reflectToAttribute: true, type: String, }, hasBadges_: { type: Boolean, reflectToAttribute: true, }, hasDescriptions_: { type: Boolean, computed: 'computeHasDescriptions_(hasBadges_, description)', reflectToAttribute: true, }, isFolder_: { computed: 'computeIsFolder_(count)', type: Boolean, value: false, reflectToAttribute: true, }, size: { observer: 'onSizeChanged_', reflectToAttribute: true, type: String, value: CrUrlListItemSize.MEDIUM, }, imageUrls: { observer: 'resetFirstImageLoaded_', type: Array, value: () => [], }, firstImageLoaded_: { type: Boolean, value: false, }, forceHover: { reflectToAttribute: true, type: Boolean, value: false, }, }; } buttonAriaLabel?: string; buttonAriaDescription?: string; count?: number; description?: string; private hasBadges_: boolean; private hasDescription_: boolean; private isFolder_: boolean; size: CrUrlListItemSize; url?: string; imageUrls: string[]; private firstImageLoaded_: boolean; forceHover: boolean; override ready() { super.ready(); FocusOutlineManager.forDocument(document); this.addEventListener('pointerdown', () => this.setActiveState_(true)); this.addEventListener('pointerup', () => this.setActiveState_(false)); this.addEventListener('pointerleave', () => this.setActiveState_(false)); } override connectedCallback() { super.connectedCallback(); this.resetFirstImageLoaded_(); } private resetFirstImageLoaded_() { this.firstImageLoaded_ = false; const image = this.shadowRoot!.querySelector('img'); if (!image) { return; } if (image.complete) { this.firstImageLoaded_ = true; return; } image.addEventListener('load', () => { this.firstImageLoaded_ = true; }, {once: true}); } private computeHasDescriptions_(): boolean { return !!this.description || this.hasBadges_; } private computeIsFolder_(): boolean { return this.count !== undefined; } private getButtonAriaDescription_(): string|undefined { return this.buttonAriaDescription || this.description; } private getButtonAriaLabel_(): string { return this.buttonAriaLabel || this.title; } private getDisplayedCount_() { if (this.count && this.count > 999) { // The square to display the count only fits 3 characters. return '99+'; } return this.count; } private getFavicon_(): string { return getFaviconForPageURL(this.url || '', false); } private shouldShowImageUrl_(_url: string, index: number) { return index <= 1; } private onBadgesSlotChange_() { this.hasBadges_ = this.$.badges.assignedElements({flatten: true}).length > 0; } private onSizeChanged_() { assert(Object.values(CrUrlListItemSize).includes(this.size)); } private setActiveState_(active: boolean) { this.classList.toggle('active', active); } private shouldShowFavicon_(): boolean { return this.url !== undefined && (this.size === CrUrlListItemSize.COMPACT || this.imageUrls.length === 0); } private shouldShowUrlImage_(): boolean { return this.url !== undefined && !(this.size === CrUrlListItemSize.COMPACT || this.imageUrls.length === 0) && this.firstImageLoaded_; } private shouldShowFolderImages_(): boolean { return this.size !== CrUrlListItemSize.COMPACT; } private shouldShowFolderIcon_(): boolean { return this.size === CrUrlListItemSize.COMPACT || this.imageUrls.length === 0; } private shouldShowFolderCount_(): boolean { return this.url === undefined; } } declare global { interface HTMLElementTagNameMap { 'cr-url-list-item': CrUrlListItemElement; } } customElements.define(CrUrlListItemElement.is, CrUrlListItemElement);
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_url_list_item/cr_url_list_item.ts
TypeScript
unknown
5,429
<style> :host ::slotted([slot=view]) { bottom: 0; display: none; left: 0; position: absolute; right: 0; top: 0; } :host ::slotted(.active), :host ::slotted(.closing) { display: block; } </style> <slot name="view"></slot>
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_view_manager/cr_view_manager.html
HTML
unknown
320
// 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 {assert} from '//resources/js/assert_ts.js'; import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {CrLazyRenderElement} from '../cr_lazy_render/cr_lazy_render.js'; import {getTemplate} from './cr_view_manager.html.js'; function getEffectiveView<T extends HTMLElement>( element: CrLazyRenderElement<T>|T): HTMLElement { return element.matches('cr-lazy-render') ? (element as CrLazyRenderElement<T>).get() : element; } function dispatchCustomEvent(element: Element, eventType: string) { element.dispatchEvent( new CustomEvent(eventType, {bubbles: true, composed: true})); } const viewAnimations: Map<string, (element: Element) => Promise<Animation>> = new Map(); viewAnimations.set('fade-in', element => { const animation = element.animate([{opacity: 0}, {opacity: 1}], { duration: 180, easing: 'ease-in-out', iterations: 1, }); return animation.finished; }); viewAnimations.set('fade-out', element => { const animation = element.animate([{opacity: 1}, {opacity: 0}], { duration: 180, easing: 'ease-in-out', iterations: 1, }); return animation.finished; }); viewAnimations.set('slide-in-fade-in-ltr', element => { const animation = element.animate( [ {transform: 'translateX(-8px)', opacity: 0}, {transform: 'translateX(0)', opacity: 1}, ], { duration: 300, easing: 'cubic-bezier(0.0, 0.0, 0.2, 1)', fill: 'forwards', iterations: 1, }); return animation.finished; }); viewAnimations.set('slide-in-fade-in-rtl', element => { const animation = element.animate( [ {transform: 'translateX(8px)', opacity: 0}, {transform: 'translateX(0)', opacity: 1}, ], { duration: 300, easing: 'cubic-bezier(0.0, 0.0, 0.2, 1)', fill: 'forwards', iterations: 1, }); return animation.finished; }); export class CrViewManagerElement extends PolymerElement { static get is() { return 'cr-view-manager'; } static get template() { return getTemplate(); } private exit_(element: HTMLElement, animation: string): Promise<void> { const animationFunction = viewAnimations.get(animation); element.classList.remove('active'); element.classList.add('closing'); dispatchCustomEvent(element, 'view-exit-start'); if (!animationFunction) { // Nothing to animate. Immediately resolve. element.classList.remove('closing'); dispatchCustomEvent(element, 'view-exit-finish'); return Promise.resolve(); } return animationFunction(element).then(() => { element.classList.remove('closing'); dispatchCustomEvent(element, 'view-exit-finish'); }); } private enter_(view: HTMLElement, animation: string): Promise<void> { const animationFunction = viewAnimations.get(animation); const effectiveView = getEffectiveView(view); effectiveView.classList.add('active'); dispatchCustomEvent(effectiveView, 'view-enter-start'); if (!animationFunction) { // Nothing to animate. Immediately resolve. dispatchCustomEvent(effectiveView, 'view-enter-finish'); return Promise.resolve(); } return animationFunction(effectiveView).then(() => { dispatchCustomEvent(effectiveView, 'view-enter-finish'); }); } switchView( newViewId: string, enterAnimation?: string, exitAnimation?: string): Promise<void> { const previousView = this.querySelector<HTMLElement>('.active'); const newView = this.querySelector<HTMLElement>('#' + newViewId); assert(!!newView); const promises = []; if (previousView) { promises.push(this.exit_(previousView, exitAnimation || 'fade-out')); promises.push(this.enter_(newView, enterAnimation || 'fade-in')); } else { promises.push(this.enter_(newView, 'no-animation')); } return Promise.all(promises).then(() => {}); } } declare global { interface HTMLElementTagNameMap { 'cr-view-manager': CrViewManagerElement; } } customElements.define(CrViewManagerElement.is, CrViewManagerElement);
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_view_manager/cr_view_manager.ts
TypeScript
unknown
4,294
// 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 CrViewManagerElement() {} /** * @param {string} newViewId * @param {string=} enterAnimation * @param {string=} exitAnimation * @return {!Promise} */ CrViewManagerElement.prototype.switchView = function( newViewId, enterAnimation, exitAnimation) {};
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/cr_view_manager/cr_view_manager_externs.js
JavaScript
unknown
587
// 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, assertNotReached} from '//resources/js/assert_ts.js'; import {KeyboardShortcutList} from '//resources/js/keyboard_shortcut_list.js'; import {isMac} from '//resources/js/platform.js'; import {dedupingMixin, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; /** * @fileoverview Listens for a find keyboard shortcut (i.e. Ctrl/Cmd+f or /) * and keeps track of an stack of potential listeners. Only the listener at the * top of the stack will be notified that a find shortcut has been invoked. */ export const FindShortcutManager = (() => { /** * Stack of listeners. Only the top listener will handle the shortcut. */ const listeners: FindShortcutMixinInterface[] = []; /** * Tracks if any modal context is open in settings. This assumes only one * modal can be open at a time. The modals that are being tracked include * cr-dialog and cr-drawer. * @type {boolean} */ let modalContextOpen = false; const shortcutCtrlF = new KeyboardShortcutList(isMac ? 'meta|f' : 'ctrl|f'); const shortcutSlash = new KeyboardShortcutList('/'); window.addEventListener('keydown', e => { if (e.defaultPrevented || listeners.length === 0) { return; } const element = e.composedPath()[0] as Element; if (!shortcutCtrlF.matchesEvent(e) && (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA' || !shortcutSlash.matchesEvent(e))) { return; } const focusIndex = listeners.findIndex(listener => listener.searchInputHasFocus()); // If no listener has focus or the first (outer-most) listener has focus, // try the last (inner-most) listener. // If a listener has a search input with focus, the next listener that // should be called is the right before it in |listeners| such that the // goes from inner-most to outer-most. const index = focusIndex <= 0 ? listeners.length - 1 : focusIndex - 1; if (listeners[index]!.handleFindShortcut(modalContextOpen)) { e.preventDefault(); } }); window.addEventListener('cr-dialog-open', () => { modalContextOpen = true; }); window.addEventListener('cr-drawer-opened', () => { modalContextOpen = true; }); window.addEventListener('close', e => { if (['CR-DIALOG', 'CR-DRAWER'].includes( (e.composedPath()[0] as Element).nodeName)) { modalContextOpen = false; } }); return Object.freeze({listeners: listeners}); })(); type Constructor<T> = new (...args: any[]) => T; /** * Used to determine how to handle find shortcut invocations. */ export const FindShortcutMixin = dedupingMixin( <T extends Constructor<PolymerElement>>(superClass: T): T& Constructor<FindShortcutMixinInterface> => { class FindShortcutMixin extends superClass implements FindShortcutMixinInterface { findShortcutListenOnAttach: boolean = true; override connectedCallback() { super.connectedCallback(); if (this.findShortcutListenOnAttach) { this.becomeActiveFindShortcutListener(); } } override disconnectedCallback() { super.disconnectedCallback(); if (this.findShortcutListenOnAttach) { this.removeSelfAsFindShortcutListener(); } } becomeActiveFindShortcutListener() { const listeners = FindShortcutManager.listeners; assert( !listeners.includes(this), 'Already listening for find shortcuts.'); listeners.push(this); } private handleFindShortcutInternal_() { assertNotReached('Must override handleFindShortcut()'); } handleFindShortcut(_modalContextOpen: boolean) { this.handleFindShortcutInternal_(); return false; } removeSelfAsFindShortcutListener() { const listeners = FindShortcutManager.listeners; const index = listeners.indexOf(this); assert(listeners.includes(this), 'Find shortcut listener not found.'); listeners.splice(index, 1); } private searchInputHasFocusInternal_() { assertNotReached('Must override searchInputHasFocus()'); } searchInputHasFocus() { this.searchInputHasFocusInternal_(); return false; } } return FindShortcutMixin; }); export interface FindShortcutMixinInterface { findShortcutListenOnAttach: boolean; becomeActiveFindShortcutListener(): void; /** If handled, return true. */ handleFindShortcut(modalContextOpen: boolean): boolean; removeSelfAsFindShortcutListener(): void; searchInputHasFocus(): boolean; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/find_shortcut_mixin.ts
TypeScript
unknown
4,865
// 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. // clang-format off import {afterNextRender, dedupingMixin, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {assert} from 'chrome://resources/js/assert_ts.js'; import {focusWithoutInk} from 'chrome://resources/js/focus_without_ink.js'; import {FocusRow, FocusRowDelegate} from 'chrome://resources/js/focus_row.js'; // clang-format on interface ListItem { lastFocused: object; overrideCustomEquivalent?: boolean; getCustomEquivalent?: (el: HTMLElement) => HTMLElement | null; } class FocusRowMixinDelegate implements FocusRowDelegate { private listItem_: ListItem; constructor(listItem: ListItem) { this.listItem_ = listItem; } /** * This function gets called when the [focus-row-control] element receives * the focus event. */ onFocus(_row: FocusRow, e: Event) { const element = e.composedPath()[0]! as HTMLElement; const focusableElement = FocusRow.getFocusableElement(element); if (element !== focusableElement) { focusableElement.focus(); } this.listItem_.lastFocused = focusableElement; } /** * @param row The row that detected a keydown. * @return Whether the event was handled. */ onKeydown(_row: FocusRow, e: KeyboardEvent): boolean { // Prevent iron-list from changing the focus on enter. if (e.key === 'Enter') { e.stopPropagation(); } return false; } getCustomEquivalent(sampleElement: HTMLElement): HTMLElement|null { return this.listItem_.overrideCustomEquivalent ? this.listItem_.getCustomEquivalent!(sampleElement) : null; } } class VirtualFocusRow extends FocusRow { constructor(root: HTMLElement, delegate: FocusRowDelegate) { super(root, /* boundary */ null, delegate); } override getCustomEquivalent(sampleElement: HTMLElement) { const equivalent = this.delegate ? this.delegate.getCustomEquivalent(sampleElement) : null; return equivalent || super.getCustomEquivalent(sampleElement); } } /** * Any element that is being used as an iron-list row item can extend this * behavior, which encapsulates focus controls of mouse and keyboards. * To use this behavior: * - The parent element should pass a "last-focused" attribute double-bound * to the row items, to track the last-focused element across rows, and * a "list-blurred" attribute double-bound to the row items, to track * whether the list of row items has been blurred. * - There must be a container in the extending element with the * [focus-row-container] attribute that contains all focusable controls. * - On each of the focusable controls, there must be a [focus-row-control] * attribute, and a [focus-type=] attribute unique for each control. * */ type Constructor<T> = new (...args: any[]) => T; export const FocusRowMixin = dedupingMixin( <T extends Constructor<PolymerElement>>(superClass: T): T& Constructor<FocusRowMixinInterface> => { class FocusRowMixin extends superClass implements FocusRowMixinInterface { static get properties() { return { row_: Object, mouseFocused_: Boolean, id: { type: String, reflectToAttribute: true, }, isFocused: { type: Boolean, notify: true, }, focusRowIndex: { type: Number, observer: 'focusRowIndexChanged', }, lastFocused: { type: Object, notify: true, }, ironListTabIndex: { type: Number, observer: 'ironListTabIndexChanged_', }, listBlurred: { type: Boolean, notify: true, }, }; } private row_: VirtualFocusRow; private mouseFocused_: boolean; // Will be updated when |index| is set, unless specified elsewhere. override id: string; // For notifying when the row is in focus. isFocused: boolean; // Should be bound to the index of the item from the iron-list. focusRowIndex: number; lastFocused: HTMLElement; /** * This is different from tabIndex, since the template only does a * one-way binding on both attributes, and the behavior actually make * use of this fact. For example, when a control within a row is * focused, it will have tabIndex = -1 and ironListTabIndex = 0. */ ironListTabIndex: number; listBlurred: boolean; private firstControl_: HTMLElement|null = null; private controlObservers_: MutationObserver[] = []; private boundOnFirstControlKeydown_: ((e: Event) => void)|null = null; override connectedCallback() { super.connectedCallback(); this.classList.add('no-outline'); this.boundOnFirstControlKeydown_ = this.onFirstControlKeydown_.bind(this); afterNextRender(this, () => { const rowContainer = this.root!.querySelector<HTMLElement>('[focus-row-container]'); assert(rowContainer); this.row_ = new VirtualFocusRow( rowContainer, new FocusRowMixinDelegate(this)); this.addItems_(); // Adding listeners asynchronously to reduce blocking time, since // this behavior will be used by items in potentially long lists. this.addEventListener('focus', this.onFocus_); this.addEventListener('dom-change', this.addItems_); this.addEventListener('mousedown', this.onMouseDown_); this.addEventListener('blur', this.onBlur_); }); } override disconnectedCallback() { super.disconnectedCallback(); this.removeEventListener('focus', this.onFocus_); this.removeEventListener('dom-change', this.addItems_); this.removeEventListener('mousedown', this.onMouseDown_); this.removeEventListener('blur', this.onBlur_); this.removeObservers_(); if (this.firstControl_ && this.boundOnFirstControlKeydown_) { this.firstControl_.removeEventListener( 'keydown', this.boundOnFirstControlKeydown_); this.boundOnFirstControlKeydown_ = null; } if (this.row_) { this.row_.destroy(); } } /** * Returns an ID based on the index that was passed in. */ private computeId_(index: number): string|undefined { return index !== undefined ? `frb${index}` : undefined; } /** * Sets |id| if it hasn't been set elsewhere. Also sets |aria-rowindex|. */ focusRowIndexChanged(newIndex: number, oldIndex: number) { // focusRowIndex is 0-based where aria-rowindex is 1-based. this.setAttribute('aria-rowindex', (newIndex + 1).toString()); // Only set ID if it matches what was previously set. This prevents // overriding the ID value if it's set elsewhere. if (this.id === this.computeId_(oldIndex)) { this.id = this.computeId_(newIndex) || ''; } } getFocusRow(): FocusRow { assert(this.row_); return this.row_; } private updateFirstControl_() { const newFirstControl = this.row_.getFirstFocusable(); if (newFirstControl === this.firstControl_) { return; } if (this.firstControl_) { this.firstControl_.removeEventListener( 'keydown', this.boundOnFirstControlKeydown_!); } this.firstControl_ = newFirstControl; if (this.firstControl_) { this.firstControl_.addEventListener( 'keydown', this.boundOnFirstControlKeydown_!); } } private removeObservers_() { if (this.controlObservers_.length > 0) { this.controlObservers_.forEach(observer => { observer.disconnect(); }); } this.controlObservers_ = []; } private addItems_() { this.ironListTabIndexChanged_(); if (this.row_) { this.removeObservers_(); this.row_.destroy(); const controls = this.root!.querySelectorAll<HTMLElement>('[focus-row-control]'); controls.forEach(control => { assert(control); this.row_.addItem( control.getAttribute('focus-type')!, FocusRow.getFocusableElement(control)); this.addMutationObservers_(control); }); this.updateFirstControl_(); } } private createObserver_(): MutationObserver { return new MutationObserver(mutations => { const mutation = mutations[0]!; if (mutation.attributeName === 'style' && mutation.oldValue) { const newStyle = window.getComputedStyle(mutation.target as Element); const oldDisplayValue = mutation.oldValue.match(/^display:(.*)(?=;)/); const oldVisibilityValue = mutation.oldValue.match(/^visibility:(.*)(?=;)/); // Return early if display and visibility have not changed. if (oldDisplayValue && newStyle.display === oldDisplayValue[1]!.trim() && oldVisibilityValue && newStyle.visibility === oldVisibilityValue[1]!.trim()) { return; } } this.updateFirstControl_(); }); } /** * The first focusable control changes if hidden, disabled, or * style.display changes for the control or any of its ancestors. Add * mutation observers to watch for these changes in order to ensure the * first control keydown listener is always on the correct element. */ private addMutationObservers_(control: Element) { let current = control; while (current && current !== this.root) { const currentObserver = this.createObserver_(); currentObserver.observe(current, { attributes: true, attributeFilter: ['hidden', 'disabled', 'style'], attributeOldValue: true, }); this.controlObservers_.push(currentObserver); current = current.parentNode as Element; } } /** * This function gets called when the row itself receives the focus * event. */ private onFocus_(e: Event) { if (this.mouseFocused_) { this.mouseFocused_ = false; // Consume and reset flag. return; } // If focus is being restored from outside the item and the event is // fired by the list item itself, focus the first control so that the // user can tab through all the controls. When the user shift-tabs // back to the row, or focus is restored to the row from a dropdown on // the last item, the last child item will be focused before the row // itself. Since this is the desired behavior, do not shift focus to // the first item in these cases. const restoreFocusToFirst = this.listBlurred && e.composedPath()[0] === this; if (this.lastFocused && !restoreFocusToFirst) { focusWithoutInk(this.row_.getEquivalentElement(this.lastFocused)); } else { assert(this.firstControl_); const firstFocusable = this.firstControl_; focusWithoutInk(firstFocusable); } this.listBlurred = false; this.isFocused = true; } private onFirstControlKeydown_(e: Event) { const keyEvent = e as KeyboardEvent; if (keyEvent.shiftKey && keyEvent.key === 'Tab') { this.focus(); } } private ironListTabIndexChanged_() { if (this.row_) { this.row_.makeActive(this.ironListTabIndex === 0); } // If a new row is being focused, reset listBlurred. This means an // item has been removed and iron-list is about to focus the next // item. if (this.ironListTabIndex === 0) { this.listBlurred = false; } } private onMouseDown_() { this.mouseFocused_ = true; // Set flag to not do any control-focusing. } private onBlur_(e: FocusEvent) { // Reset focused flags since it's not active anymore. this.mouseFocused_ = false; this.isFocused = false; const node = e.relatedTarget ? e.relatedTarget as Node : null; if (!this.parentNode!.contains(node)) { this.listBlurred = true; } } } return FocusRowMixin; }); export interface FocusRowMixinInterface { id: string; isFocused: boolean; focusRowIndex: number; lastFocused: HTMLElement|null; ironListTabIndex: number; listBlurred: boolean; overrideCustomEquivalent?: boolean; focusRowIndexChanged(newIndex: number, oldIndex: number): void; getCustomEquivalent?(el: HTMLElement): HTMLElement|null; getFocusRow(): FocusRow; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/focus_row_mixin.ts
TypeScript
unknown
13,712
// 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 * 'I18nMixin' is a Mixin offering loading of internationalization * strings. Typically it is used as [[i18n('someString')]] computed bindings or * for this.i18n('foo'). It is not needed for HTML $i18n{otherString}, which is * handled by a C++ templatizer. */ import {loadTimeData} from '//resources/js/load_time_data.js'; import {parseHtmlSubset, sanitizeInnerHtml, SanitizeInnerHtmlOpts} from '//resources/js/parse_html_subset.js'; import {dedupingMixin, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; type Constructor<T> = new (...args: any[]) => T; export const I18nMixin = dedupingMixin( <T extends Constructor<PolymerElement>>(superClass: T): T& Constructor<I18nMixinInterface> => { class I18nMixin extends superClass implements I18nMixinInterface { /** * Returns a translated string where $1 to $9 are replaced by the given * values. * @param id The ID of the string to translate. * @param varArgs Values to replace the placeholders $1 to $9 in the * string. * @return A translated, substituted string. */ private i18nRaw_(id: string, ...varArgs: Array<string|number>) { return varArgs.length === 0 ? loadTimeData.getString(id) : loadTimeData.getStringF(id, ...varArgs); } /** * Returns a translated string where $1 to $9 are replaced by the given * values. Also sanitizes the output to filter out dangerous HTML/JS. * Use with Polymer bindings that are *not* inner-h-t-m-l. * NOTE: This is not related to $i18n{foo} in HTML, see file overview. * @param id The ID of the string to translate. * @param varArgs Values to replace the placeholders $1 to $9 in the * string. * @return A translated, sanitized, substituted string. */ i18n(id: string, ...varArgs: Array<string|number>) { const rawString = this.i18nRaw_(id, ...varArgs); return parseHtmlSubset(`<b>${rawString}</b>`).firstChild!.textContent! ; } /** * Similar to 'i18n', returns a translated, sanitized, substituted * string. It receives the string ID and a dictionary containing the * substitutions as well as optional additional allowed tags and * attributes. Use with Polymer bindings that are inner-h-t-m-l, for * example. * @param id The ID of the string to translate. */ i18nAdvanced(id: string, opts?: SanitizeInnerHtmlOpts) { opts = opts || {}; const rawString = this.i18nRaw_(id, ...(opts.substitutions || [])); return sanitizeInnerHtml(rawString, opts); } /** * Similar to 'i18n', with an unused |locale| parameter used to trigger * updates when the locale changes. * @param locale The UI language used. * @param id The ID of the string to translate. * @param varArgs Values to replace the placeholders $1 to $9 in the * string. * @return A translated, sanitized, substituted string. */ i18nDynamic(_locale: string, id: string, ...varArgs: string[]) { return this.i18n(id, ...varArgs); } /** * Similar to 'i18nDynamic', but varArgs valus are interpreted as keys * in loadTimeData. This allows generation of strings that take other * localized strings as parameters. * @param locale The UI language used. * @param id The ID of the string to translate. * @param varArgs Values to replace the placeholders $1 to $9 * in the string. Values are interpreted as strings IDs if found in * the list of localized strings. * @return A translated, sanitized, substituted string. */ i18nRecursive(locale: string, id: string, ...varArgs: string[]) { let args = varArgs; if (args.length > 0) { // Try to replace IDs with localized values. args = args.map(str => { return this.i18nExists(str) ? loadTimeData.getString(str) : str; }); } return this.i18nDynamic(locale, id, ...args); } /** * Returns true if a translation exists for |id|. */ i18nExists(id: string) { return loadTimeData.valueExists(id); } } return I18nMixin; }); export interface I18nMixinInterface { i18n(id: string, ...varArgs: Array<string|number>): string; i18nAdvanced(id: string, opts?: SanitizeInnerHtmlOpts): TrustedHTML; i18nDynamic(locale: string, id: string, ...varArgs: string[]): string; i18nRecursive(locale: string, id: string, ...varArgs: string[]): string; i18nExists(id: string): boolean; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/i18n_mixin.ts
TypeScript
unknown
5,057
<!-- List commonly used icons here to prevent duplication. Do not add rarely used icons here; place those in your application. Note that 20px and 24px icons are specified separately (size="", below). Icons are rendered at 20x20 px, but we don't have 20 px SVGs for everything. The 24 px icons are used where 20 px icons are unavailable (which may appear blurry at 20 px). Please use 20 px icons when available. --> <iron-iconset-svg name="cr20" size="20"> <svg> <defs> <!-- Keep these in sorted order by id="". See also http://goo.gl/Y1OdAq --> <g id="block"> <path fill-rule="evenodd" clip-rule="evenodd" d="M10 0C4.48 0 0 4.48 0 10C0 15.52 4.48 20 10 20C15.52 20 20 15.52 20 10C20 4.48 15.52 0 10 0ZM2 10C2 5.58 5.58 2 10 2C11.85 2 13.55 2.63 14.9 3.69L3.69 14.9C2.63 13.55 2 11.85 2 10ZM5.1 16.31C6.45 17.37 8.15 18 10 18C14.42 18 18 14.42 18 10C18 8.15 17.37 6.45 16.31 5.1L5.1 16.31Z"> </path> </g> <g id="cloud-off"> <path d="M16 18.125L13.875 16H5C3.88889 16 2.94444 15.6111 2.16667 14.8333C1.38889 14.0556 1 13.1111 1 12C1 10.9444 1.36111 10.0347 2.08333 9.27083C2.80556 8.50694 3.6875 8.09028 4.72917 8.02083C4.77083 7.86805 4.8125 7.72222 4.85417 7.58333C4.90972 7.44444 4.97222 7.30555 5.04167 7.16667L1.875 4L2.9375 2.9375L17.0625 17.0625L16 18.125ZM5 14.5H12.375L6.20833 8.33333C6.15278 8.51389 6.09722 8.70139 6.04167 8.89583C6 9.07639 5.95139 9.25694 5.89583 9.4375L4.83333 9.52083C4.16667 9.57639 3.61111 9.84028 3.16667 10.3125C2.72222 10.7708 2.5 11.3333 2.5 12C2.5 12.6944 2.74306 13.2847 3.22917 13.7708C3.71528 14.2569 4.30556 14.5 5 14.5ZM17.5 15.375L16.3958 14.2917C16.7153 14.125 16.9792 13.8819 17.1875 13.5625C17.3958 13.2431 17.5 12.8889 17.5 12.5C17.5 11.9444 17.3056 11.4722 16.9167 11.0833C16.5278 10.6944 16.0556 10.5 15.5 10.5H14.125L14 9.14583C13.9028 8.11806 13.4722 7.25694 12.7083 6.5625C11.9444 5.85417 11.0417 5.5 10 5.5C9.65278 5.5 9.31944 5.54167 9 5.625C8.69444 5.70833 8.39583 5.82639 8.10417 5.97917L7.02083 4.89583C7.46528 4.61806 7.93056 4.40278 8.41667 4.25C8.91667 4.08333 9.44444 4 10 4C11.4306 4 12.6736 4.48611 13.7292 5.45833C14.7847 6.41667 15.375 7.59722 15.5 9C16.4722 9 17.2986 9.34028 17.9792 10.0208C18.6597 10.7014 19 11.5278 19 12.5C19 13.0972 18.8611 13.6458 18.5833 14.1458C18.3194 14.6458 17.9583 15.0556 17.5 15.375Z"> </path> </g> <g id="domain"> <path d="M2,3 L2,17 L11.8267655,17 L13.7904799,17 L18,17 L18,7 L12,7 L12,3 L2,3 Z M8,13 L10,13 L10,15 L8,15 L8,13 Z M4,13 L6,13 L6,15 L4,15 L4,13 Z M8,9 L10,9 L10,11 L8,11 L8,9 Z M4,9 L6,9 L6,11 L4,11 L4,9 Z M12,9 L16,9 L16,15 L12,15 L12,9 Z M12,11 L14,11 L14,13 L12,13 L12,11 Z M8,5 L10,5 L10,7 L8,7 L8,5 Z M4,5 L6,5 L6,7 L4,7 L4,5 Z"> </path> </g> <g id="kite"> <path fill-rule="evenodd" clip-rule="evenodd" d="M4.6327 8.00094L10.3199 2L16 8.00094L10.1848 16.8673C10.0995 16.9873 10.0071 17.1074 9.90047 17.2199C9.42417 17.7225 8.79147 18 8.11611 18C7.44076 18 6.80806 17.7225 6.33175 17.2199C5.85545 16.7173 5.59242 16.0497 5.59242 15.3371C5.59242 14.977 5.46445 14.647 5.22275 14.3919C4.98104 14.1369 4.66825 14.0019 4.32701 14.0019H4V12.6667H4.32701C5.00237 12.6667 5.63507 12.9442 6.11137 13.4468C6.58768 13.9494 6.85071 14.617 6.85071 15.3296C6.85071 15.6896 6.97867 16.0197 7.22038 16.2747C7.46209 16.5298 7.77488 16.6648 8.11611 16.6648C8.45735 16.6648 8.77014 16.5223 9.01185 16.2747C9.02396 16.2601 9.03607 16.246 9.04808 16.2319C9.08541 16.1883 9.12176 16.1458 9.15403 16.0947L9.55213 15.4946L4.6327 8.00094ZM10.3199 13.9371L6.53802 8.17116L10.3199 4.1814L14.0963 8.17103L10.3199 13.9371Z"> </path> </g> <g id="menu"> <path d="M21.25,17.9482759 C21.6642136,17.9482759 22,18.2840623 22,18.6982759 L22,18.75 C22,19.1642136 21.6642136,19.5 21.25,19.5 L2.75,19.5 C2.33578644,19.5 2,19.1642136 2,18.75 L2,18.6982759 C2,18.2840623 2.33578644,17.9482759 2.75,17.9482759 L21.25,17.9482759 Z M18.928479,9.29664948 C19.1937277,9.29664948 19.4481097,9.40203181 19.6356515,9.58960835 L21.8098771,11.7642377 L19.6356515,13.9388671 C19.2451634,14.3294277 18.6119984,14.3294865 18.2214379,13.9389984 C18.0338614,13.7514567 17.928479,13.4970747 17.928479,13.231826 L17.928479,10.2966495 C17.928479,9.74436473 18.3761943,9.29664948 18.928479,9.29664948 Z M14.25,11.2241379 C14.6642136,11.2241379 15,11.5599244 15,11.9741379 L15,12.0258621 C15,12.4400756 14.6642136,12.7758621 14.25,12.7758621 L2.75,12.7758621 C2.33578644,12.7758621 2,12.4400756 2,12.0258621 L2,11.9741379 C2,11.5599244 2.33578644,11.2241379 2.75,11.2241379 L14.25,11.2241379 Z M21.25,4.5 C21.6642136,4.5 22,4.83578644 22,5.25 L22,5.30172414 C22,5.7159377 21.6642136,6.05172414 21.25,6.05172414 L2.75,6.05172414 C2.33578644,6.05172414 2,5.7159377 2,5.30172414 L2,5.25 C2,4.83578644 2.33578644,4.5 2.75,4.5 L21.25,4.5 Z"></path> </g> <if expr="chromeos_ash"> <g id="banner-warning"> <path fill-rule="evenodd" clip-rule="evenodd" d="M9.13177 1.50386C9.51566 0.832046 10.4844 0.832046 10.8683 1.50386L18.8683 15.5039C19.2492 16.1705 18.7678 17 18 17H2.00001C1.23219 17 0.750823 16.1705 1.13177 15.5039L9.13177 1.50386ZM10 4.01556L3.72321 15H16.2768L10 4.01556ZM9 11H11V7H9V11ZM11 14H9V12H11V14Z"> </path> </g> <g id="warning"> <path fill-rule="evenodd" clip-rule="evenodd" d="M9.13177 1.50386C9.51566 0.832046 10.4844 0.832046 10.8683 1.50386L18.8683 15.5039C19.2492 16.1705 18.7678 17 18 17H2.00001C1.23219 17 0.750823 16.1705 1.13177 15.5039L9.13177 1.50386ZM10 4.01556L3.72321 15H16.2768L10 4.01556ZM9 11H11V7H9V11ZM11 14H9V12H11V14Z"> </path> </g> </if> </svg> </iron-iconset-svg> <!-- NOTE: In the common case that the final icon will be 20x20, export the SVG at 20px and place it in the section above. --> <iron-iconset-svg name="cr" size="24"> <svg> <defs> <!-- These icons are copied from Polymer's iron-icons and kept in sorted order. See http://goo.gl/Y1OdAq for instructions on adding additional icons. --> <g id="account-child-invert" viewBox="0 0 48 48"> <path d="M24 4c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6 2.69-6 6-6z"></path> <path fill="none" d="M0 0h48v48H0V0z"></path> <circle fill="none" cx="24" cy="26" r="4"></circle> <path d="M24 18c-6.16 0-13 3.12-13 7.23v11.54c0 2.32 2.19 4.33 5.2 5.63 2.32 1 5.12 1.59 7.8 1.59.66 0 1.33-.06 2-.14v-5.2c-.67.08-1.34.14-2 .14-2.63 0-5.39-.57-7.68-1.55.67-2.12 4.34-3.65 7.68-3.65.86 0 1.75.11 2.6.29 2.79.62 5.2 2.15 5.2 4.04v4.47c3.01-1.31 5.2-3.31 5.2-5.63V25.23C37 21.12 30.16 18 24 18zm0 12c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4z"> </path> </g> <g id="add"> <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z" /> </g> <g id="arrow-back"> <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"></path> </g> <g id="arrow-drop-up"> <path d="M7 14l5-5 5 5z"> </g> <g id="arrow-drop-down"> <path d="M7 10l5 5 5-5z"></path> </g> <g id="arrow-forward"> <path d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8z"></path> </g> <g id="arrow-right"> <path d="M10 7l5 5-5 5z"></path> </g> <if expr="chromeos_ash"> <g id="bluetooth"> <path d="M17.71 7.71L12 2h-1v7.59L6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 11 14.41V22h1l5.71-5.71-4.3-4.29 4.3-4.29zM13 5.83l1.88 1.88L13 9.59V5.83zm1.88 10.46L13 18.17v-3.76l1.88 1.88z"> </path> </g> <g id="camera-alt"> <circle cx="12" cy="12" r="3.2"></circle> <path d="M9 2L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2h-3.17L15 2H9zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z"> </path> </g> <g id="work"> <path d="M20 6h-4V4c0-1.11-.89-2-2-2h-4c-1.11 0-2 .89-2 2v2H4c-1.11 0-1.99.89-1.99 2L2 19c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-6 0h-4V4h4v2z"> </path> </g> </if> <g id="cancel"> <path d="M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z"> </path> </g> <g id="check"> <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"></path> </g> <g id="check-circle"> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"> </path> </g> <g id="chevron-left"> <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"></path> </g> <g id="chevron-right"> <path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path> </g> <g id="clear"> <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"> </path> </g> <g id="close"> <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"> </path> </g> <g id="computer"> <path d="M20 18c1.1 0 1.99-.9 1.99-2L22 6c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2H0v2h24v-2h-4zM4 6h16v10H4V6z"> </path> </g> <g id="create"> <path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"> </path> </g> <g id="delete"> <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"></path> </g> <g id="domain"> <path d="M12 7V3H2v18h20V7H12zM6 19H4v-2h2v2zm0-4H4v-2h2v2zm0-4H4V9h2v2zm0-4H4V5h2v2zm4 12H8v-2h2v2zm0-4H8v-2h2v2zm0-4H8V9h2v2zm0-4H8V5h2v2zm10 12h-8v-2h2v-2h-2v-2h2v-2h-2V9h8v10zm-2-8h-2v2h2v-2zm0 4h-2v2h2v-2z"> </path> </g> <g id="error"> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"> </path> </g> <g id="error-outline"> <path d="M11 15h2v2h-2zm0-8h2v6h-2zm.99-5C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"> </path> </g> <g id="expand-less"> <path d="M12 8l-6 6 1.41 1.41L12 10.83l4.59 4.58L18 14z"></path> </g> <g id="expand-more"> <path d="M16.59 8.59L12 13.17 7.41 8.59 6 10l6 6 6-6z"></path> </g> <g id="extension"> <path d="M20.5 11H19V7c0-1.1-.9-2-2-2h-4V3.5C13 2.12 11.88 1 10.5 1S8 2.12 8 3.5V5H4c-1.1 0-1.99.9-1.99 2v3.8H3.5c1.49 0 2.7 1.21 2.7 2.7s-1.21 2.7-2.7 2.7H2V20c0 1.1.9 2 2 2h3.8v-1.5c0-1.49 1.21-2.7 2.7-2.7 1.49 0 2.7 1.21 2.7 2.7V22H17c1.1 0 2-.9 2-2v-4h1.5c1.38 0 2.5-1.12 2.5-2.5S21.88 11 20.5 11z"> </path> </g> <g id="file-download"> <path d="M21.25,15.5 C21.6494202,15.5 21.9759152,15.81223 21.9987268,16.2059318 L22,16.25 L22,18 C22,20.1828397 20.2515247,21.9573012 18.0787177,21.9992409 L6,22 C3.81716027,22 2.04269883,20.2515247 2.0007591,18.0787177 L2,16.25 C2,15.8357864 2.33578644,15.5 2.75,15.5 C3.14942022,15.5 3.47591522,15.81223 3.49872683,16.2059318 L3.5,16.25 L3.5,18 C3.5,19.35731 4.5816677,20.4619829 5.93002379,20.4990396 L18,20.5 C19.35731,20.5 20.4619829,19.4183323 20.4990396,18.0699762 L20.5,16.25 C20.5,15.8357864 20.8357864,15.5 21.25,15.5 Z M11.9984143,2 C12.4126279,2 12.7484143,2.33578644 12.7484143,2.75 L12.748,15.434 L16.7167084,11.4694602 C17.0097174,11.1766828 17.4845911,11.1768707 17.7773685,11.4698797 C18.0701458,11.7628888 18.069958,12.2377625 17.776949,12.5305398 L12.5278693,17.7754689 C12.2350241,18.0680825 11.7604739,18.0680825 11.4676287,17.7754689 L6.21987976,12.5318705 C5.92687069,12.2390932 5.92668283,11.7642195 6.21946015,11.4712104 C6.51223747,11.1782014 6.98711117,11.1780135 7.28012024,11.4707908 L11.248,15.435 L11.2484143,2.75 C11.2484143,2.33578644 11.5842008,2 11.9984143,2 Z"></path> </g> <if expr="chromeos_ash"> <g id="folder-filled"> <path d="M10 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"></path> </g> </if> <g id="fullscreen"> <path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"></path> </g> <g id="group"> <path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z"> </path> </g> <g id="help-outline"> <path d="M11 18h2v-2h-2v2zm1-16C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm0-14c-2.21 0-4 1.79-4 4h2c0-1.1.9-2 2-2s2 .9 2 2c0 2-3 1.75-3 5h2c0-2.25 3-2.5 3-5 0-2.21-1.79-4-4-4z"> </path> </g> <g id="info"> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"> </path> </g> <g id="info-outline"> <path d="M11 17h2v-6h-2v6zm1-15C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zM11 9h2V7h-2v2z"> </path> </g> <g id="insert-drive-file"> <path d="M6 2c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6H6zm7 7V3.5L18.5 9H13z"> </path> </g> <g id="location-on"> <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"> </path> </g> <g id="mic"> <path d="M12 14c1.66 0 2.99-1.34 2.99-3L15 5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm5.3-3c0 3-2.54 5.1-5.3 5.1S6.7 14 6.7 11H5c0 3.41 2.72 6.23 6 6.72V21h2v-3.28c3.28-.48 6-3.3 6-6.72h-1.7z"> </path> </g> <g id="more-vert"> <path d="M6.25,8.25 C7.21649831,8.25 8,7.46649831 8,6.5 C8,5.53350169 7.21649831,4.75 6.25,4.75 C5.28350169,4.75 4.5,5.53350169 4.5,6.5 C4.5,7.46649831 5.28350169,8.25 6.25,8.25 Z M6.25,19.25 C7.21649831,19.25 8,18.4664983 8,17.5 C8,16.5335017 7.21649831,15.75 6.25,15.75 C5.28350169,15.75 4.5,16.5335017 4.5,17.5 C4.5,18.4664983 5.28350169,19.25 6.25,19.25 Z M17.75,19.25 C18.7164983,19.25 19.5,18.4664983 19.5,17.5 C19.5,16.5335017 18.7164983,15.75 17.75,15.75 C16.7835017,15.75 16,16.5335017 16,17.5 C16,18.4664983 16.7835017,19.25 17.75,19.25 Z M17.75,8.25 C18.7164983,8.25 19.5,7.46649831 19.5,6.5 C19.5,5.53350169 18.7164983,4.75 17.75,4.75 C16.7835017,4.75 16,5.53350169 16,6.5 C16,7.46649831 16.7835017,8.25 17.75,8.25 Z" ></path> </g> <g id="open-in-new"> <path d="M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z"> </path> </g> <g id="person"> <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"> </path> </g> <g id="phonelink"><path d="M4 6h18V4H4c-1.1 0-2 .9-2 2v11H0v3h14v-3H4V6zm19 2h-6c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h6c.55 0 1-.45 1-1V9c0-.55-.45-1-1-1zm-1 9h-4v-7h4v7z"></path></g> <g id="print"> <path d="M15,14.5 C16.6568542,14.5 18,15.8431458 18,17.5 L18,19.5 C18,21.1568542 16.6568542,22.5 15,22.5 L9,22.5 C7.34314575,22.5 6,21.1568542 6,19.5 L6,17.5 C6,15.8431458 7.34314575,14.5 9,14.5 L15,14.5 Z M15,16 L9,16 C8.17157288,16 7.5,16.6715729 7.5,17.5 L7.5,19.5 C7.5,20.3284271 8.17157288,21 9,21 L15,21 C15.8284271,21 16.5,20.3284271 16.5,19.5 L16.5,17.5 C16.5,16.6715729 15.8284271,16 15,16 Z M15.75,1.75 C17.3813642,1.75 18.7085982,3.05213609 18.74905,4.6737563 L18.75,6.5 C20.959139,6.5 22.75,8.290861 22.75,10.5 L22.75,16 C22.75,18.1248648 21.0931683,19.8627558 19.0009202,19.9923197 L19.0008994,18.4875667 C20.2409952,18.3639916 21.2142949,17.3342085 21.2490396,16.0699762 L21.25,10.5 C21.25,9.14269002 20.1683323,8.03801707 18.8199762,8.00096045 L5.25,8 C3.89269002,8 2.78801707,9.0816677 2.75096045,10.4300238 L2.75,16 C2.75,17.2964887 3.7369003,18.3624746 5.00044359,18.4877002 L5.0000836,19.9923197 C2.90736171,19.8633117 1.25,18.1252046 1.25,16 L1.25,10.5 C1.25,8.290861 3.040861,6.5 5.25,6.5 L5.25,4.75 C5.25,3.11863582 6.55213609,1.79140181 8.1737563,1.75094996 L15.75,1.75 Z M18.5,9.5 C19.1903559,9.5 19.75,10.0596441 19.75,10.75 C19.75,11.4403559 19.1903559,12 18.5,12 C17.8096441,12 17.25,11.4403559 17.25,10.75 C17.25,10.0596441 17.8096441,9.5 18.5,9.5 Z M15.8062346,3.25103462 L8.25,3.25 C7.44040076,3.25 6.78060706,3.89139372 6.75103462,4.69376543 L6.75,6.5 L17.25,6.5 L17.25,4.75 C17.25,3.94040076 16.6086063,3.28060706 15.8062346,3.25103462 Z"></path> </g> <g id="schedule"><path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z"></path></g> <g id="search"> <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"> </path> </g> <g id="security"> <path d="M12 1L3 5v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V5l-9-4zm0 10.99h7c-.53 4.12-3.28 7.79-7 8.94V12H5V6.3l7-3.11v8.8z"> </path> </g> <if expr="chromeos_ash"> <g id="sim-card-alert"> <path d="M18 2h-8L4.02 8 4 20c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-5 15h-2v-2h2v2zm0-4h-2V8h2v5z"> </path> </g> <g id="sim-lock"> <path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2z"> </path> </g> <g id="sms-connect"> <path d="M20,2C21.1,2 22,2.9 22,4L22,16C22,17.1 21.1,18 20,18L6,18L2,22L2.01,4C2.01,2.9 2.9,2 4,2L20,2ZM8,8L4,12L8,16L8,13L14,13L14,11L8,11L8,8ZM19.666,7.872L16.038,4.372L16.038,6.997L10,6.997L10,9L16.038,9L16.038,11.372L19.666,7.872Z"> </path> </g> </if> <!-- The <g> IDs are exposed as global variables in Vulcanized mode, which conflicts with the "settings" namespace of MD Settings. Using an "_icon" suffix prevents the naming conflict. --> <g id="settings_icon"> <path d="M19.43 12.98c.04-.32.07-.64.07-.98s-.03-.66-.07-.98l2.11-1.65c.19-.15.24-.42.12-.64l-2-3.46c-.12-.22-.39-.3-.61-.22l-2.49 1c-.52-.4-1.08-.73-1.69-.98l-.38-2.65C14.46 2.18 14.25 2 14 2h-4c-.25 0-.46.18-.49.42l-.38 2.65c-.61.25-1.17.59-1.69.98l-2.49-1c-.23-.09-.49 0-.61.22l-2 3.46c-.13.22-.07.49.12.64l2.11 1.65c-.04.32-.07.65-.07.98s.03.66.07.98l-2.11 1.65c-.19.15-.24.42-.12.64l2 3.46c.12.22.39.3.61.22l2.49-1c.52.4 1.08.73 1.69.98l.38 2.65c.03.24.24.42.49.42h4c.25 0 .46-.18.49-.42l.38-2.65c.61-.25 1.17-.59 1.69-.98l2.49 1c.23.09.49 0 .61-.22l2-3.46c.12-.22.07-.49-.12-.64l-2.11-1.65zM12 15.5c-1.93 0-3.5-1.57-3.5-3.5s1.57-3.5 3.5-3.5 3.5 1.57 3.5 3.5-1.57 3.5-3.5 3.5z"> </path> </g> <g id="star"> <path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"></path> </g> <g id="sync"> <path d="M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46C19.54 15.03 20 13.57 20 12c0-4.42-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74C4.46 8.97 4 10.43 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3z"> </path> </g> <g id="videocam"> <path d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4z"> </path> </g> <g id="warning"> <path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"></path> </g> </defs> </svg> </iron-iconset-svg>
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/icons.html
HTML
unknown
20,702
// 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 |ListPropertyUpdateMixin| is used to update an existing * polymer list property given the list after all the edits were made while * maintaining the reference to the original list. This allows * dom-repeat/iron-list elements bound to this list property to not fully * re-rendered from scratch. * * The minimal splices needed to transform the original list to the edited list * are calculated using |Polymer.ArraySplice.calculateSplices|. All the edits * are then applied to the original list. Once completed, a single notification * containing information about all the edits is sent to the polyer object. */ import {calculateSplices, dedupingMixin, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; type Constructor<T> = new (...args: any[]) => T; export const ListPropertyUpdateMixin = dedupingMixin( <T extends Constructor<PolymerElement>>(superClass: T): T& Constructor<ListPropertyUpdateMixinInterface> => { class ListPropertyUpdateMixin extends superClass implements ListPropertyUpdateMixinInterface { updateList<T>( propertyPath: string, identityGetter: (item: T) => (T | string), updatedList: T[], identityBasedUpdate: boolean = false): boolean { const list = this.get(propertyPath); const splices = calculateSplices( updatedList.map(item => identityGetter(item)), list.map(identityGetter)); splices.forEach(splice => { const index = splice.index; const deleteCount = splice.removed.length; // Transform splices to the expected format of notifySplices(). // Convert !Array<string> to !Array<!Object>. splice.removed = list.slice(index, index + deleteCount); splice.object = list; splice.type = 'splice'; const added = updatedList.slice(index, index + splice.addedCount); const spliceParams = [index, deleteCount].concat(added); list.splice.apply(list, spliceParams); }); let updated = splices.length > 0; if (!identityBasedUpdate) { list.forEach((item: object, index: number) => { const updatedItem = updatedList[index]; if (JSON.stringify(item) !== JSON.stringify(updatedItem)) { this.set([propertyPath, index], updatedItem); updated = true; } }); } if (splices.length > 0) { this.notifySplices(propertyPath, splices); } return updated; } } return ListPropertyUpdateMixin; }); export interface ListPropertyUpdateMixinInterface { /** @return Whether notifySplices was called. */ updateList<T>( propertyPath: string, identityGetter: (item: T) => (T | string), updatedList: T[], identityBasedUpdate?: boolean): boolean; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/list_property_update_mixin.ts
TypeScript
unknown
3,095
/* 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 */ .md-select { --md-arrow-width: 10px; --md-select-bg-color: var(--google-grey-100); --md-select-focus-shadow-color: rgba(var(--google-blue-600-rgb), .4); --md-select-option-bg-color: white; --md-select-side-padding: 8px; --md-select-text-color: var(--cr-primary-text-color); -webkit-appearance: none; background: url(chrome://resources/images/arrow_down.svg) calc(100% - var(--md-select-side-padding)) center no-repeat; background-color: var(--md-select-bg-color); background-size: var(--md-arrow-width); border: none; border-radius: 4px; color: var(--md-select-text-color); cursor: pointer; font-family: inherit; font-size: inherit; line-height: inherit; max-width: 100%; outline: none; padding-bottom: 6px; /* Ensures 3px space between text and arrow */ padding-inline-end: calc(var(--md-select-side-padding) + var(--md-arrow-width) + 3px); padding-inline-start: var(--md-select-side-padding); padding-top: 6px; width: var(--md-select-width, 200px); } @media (prefers-color-scheme: dark) { .md-select { --md-select-bg-color: rgba(0, 0, 0, .3); --md-select-focus-shadow-color: rgba(var(--google-blue-300-rgb), .5); --md-select-option-bg-color: var(--google-grey-900-white-4-percent); background-image: url(chrome://resources/images/dark/arrow_down.svg); } } /* Makes sure anything within the dropdown menu has a background. */ .md-select :-webkit-any(option, optgroup) { background-color: var(--md-select-option-bg-color); } .md-select[disabled] { opacity: var(--cr-disabled-opacity); pointer-events: none; } .md-select:focus { box-shadow: 0 0 0 2px var(--md-select-focus-shadow-color); } @media (forced-colors: active) { .md-select:focus { /* Use outline instead of box-shadow (which does not work) in Windows HCM. */ outline: var(--cr-focus-outline-hcm); } } /* Should not have an outline if opened by mouse click. */ .md-select:active { box-shadow: none; } :host-context([dir=rtl]) .md-select { background-position-x: var(--md-select-side-padding); }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/md_select.css
CSS
unknown
2,408
// 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 This file provides a mixin to manage a `hovered` style on mouse * events. Relies on listening for pointer events as touch devices may fire * mouse events too. */ import {dedupingMixin, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; const HOVERED_STYLE: string = 'hovered'; type Constructor<T> = new (...args: any[]) => T; export const MouseHoverableMixin = dedupingMixin(<T extends Constructor<PolymerElement>>(superClass: T): T => { class MouseHoverableMixin extends superClass { override ready() { super.ready(); this.addEventListener('pointerenter', (e) => { const hostElement = e.currentTarget as HTMLElement; hostElement.classList.toggle( HOVERED_STYLE, e.pointerType === 'mouse'); }); this.addEventListener('pointerleave', (e) => { if (e.pointerType !== 'mouse') { return; } const hostElement = e.currentTarget as HTMLElement; hostElement.classList.remove(HOVERED_STYLE); }); } } return MouseHoverableMixin; });
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/mouse_hoverable_mixin.ts
TypeScript
unknown
1,321
/* 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=./mwb_shared_vars.css.js * #css_wrapper_metadata_end */ a, cr-button, cr-icon-button, div { cursor: default; } cr-icon-button { --cr-icon-button-icon-size: var(--mwb-icon-size); --cr-icon-button-size: calc(var(--mwb-icon-size) * 1.5); } cr-icon-button:hover { background-color: var(--mwb-icon-button-hover-background-color); } cr-icon-button:focus { box-shadow: 0 0 0 2px var(--mwb-icon-button-focus-ring-color); }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/mwb_element_shared_style.css
CSS
unknown
634
<iron-iconset-svg name="mwb16" size="16"> <svg> <defs> <g id="close"> <path d="M13 4.00714L11.9929 3L8 6.99286L4.00714 3L3 4.00714L6.99286 8L3 11.9929L4.00714 13L8 9.00714L11.9929 13L13 11.9929L9.00714 8L13 4.00714Z"> </path> </g> <g id="search"> <path fill-rule="evenodd" clip-rule="evenodd" d="M10.8619 10.2981L10.6177 10.0578C11.484 9.05905 12.0874 7.68174 12.0874 5.97468C12.0874 2.82136 9.23365 0 6.04368 0C2.85486 0 0 2.82136 0 5.97468C0 9.12687 3.45353 11.9462 6.17606 11.9482C7.77044 11.9494 9.0094 11.5085 9.98871 10.6796L10.2341 10.921V11.6156L14.6752 16L16 14.6904L11.5681 10.2981H10.8619ZM6.04422 10.2423C3.65985 10.2423 1.72676 8.33212 1.72676 5.97468C1.72676 3.61724 3.65985 1.70705 6.04422 1.70705C8.42749 1.70705 10.3606 3.61724 10.3606 5.97468C10.3606 8.33212 8.42749 10.2423 6.04422 10.2423V10.2423Z"> </path> </g> </defs> </svg> </iron-iconset-svg>
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/mwb_shared_icons.html
HTML
unknown
948
/* 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=./mwb_shared_vars.css.js * #css_wrapper_metadata_end */ ::-webkit-scrollbar-thumb { background-color: var(--mwb-scrollbar-thumb-color); } ::-webkit-scrollbar-thumb:hover { background-color: var(--mwb-scrollbar-thumb-hover-color); } ::-webkit-scrollbar-track { background-color: var(--mwb-scrollbar-track-color); } ::-webkit-scrollbar { width: var(--mwb-scrollbar-width); } .mwb-list-item { align-items: center; background-color: var(--mwb-background-color); contain-intrinsic-size: var(--mwb-item-height); content-visibility: auto; display: flex; height: var(--mwb-item-height); padding: 0 var(--mwb-list-item-horizontal-margin); } .mwb-list-item.hovered { background-color: var(--mwb-list-item-hover-background-color); } .mwb-list-item.selected { background-color: var(--mwb-list-item-selected-background-color); }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/mwb_shared_style.css
CSS
unknown
1,089
/* 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=./cr_shared_vars.css.js * #css_wrapper_metadata_end */ html { --mwb-background-color: white; --mwb-icon-button-fill-color: var(--google-grey-700); --mwb-icon-button-focus-ring-color: var(--google-blue-600); --mwb-icon-button-hover-background-color: rgba(var(--google-grey-900-rgb), 0.1); --mwb-icon-size: 16px; --mwb-item-height: 56px; --mwb-list-item-horizontal-margin: 16px; --mwb-list-item-hover-background-color: rgba(var(--google-grey-900-rgb), 0.1); --mwb-list-item-selected-background-color: rgba(var(--google-grey-900-rgb), 0.14); --mwb-list-section-title-font-size: 11px; --mwb-list-section-title-height: 40px; --mwb-primary-text-font-size: 13px; --mwb-scrollbar-thumb-color: var(--google-grey-300); --mwb-scrollbar-thumb-hover-color: var(--google-grey-500); --mwb-scrollbar-track-color: var(--mwb-background-color); --mwb-scrollbar-width: 4px; --mwb-secondary-text-font-size: 12px; } @media (prefers-color-scheme: dark) { html { --mwb-background-color: var(--google-grey-900); --mwb-icon-button-fill-color: var(--google-grey-300); --mwb-icon-button-focus-ring-color: var(--google-blue-300); --mwb-icon-button-hover-background-color: rgba(255, 255, 255, 0.1); --mwb-list-item-hover-background-color: rgb(55, 56, 58); /* #37383a */ --mwb-list-item-selected-background-color: rgb(68, 69, 71); /* #444547 */ --mwb-scrollbar-thumb-color: var(--google-grey-500); --mwb-scrollbar-thumb-hover-color: var(--google-grey-300); } }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/mwb_shared_vars.css
CSS
unknown
1,706
<style include="cr-hidden-style"></style> <cr-tooltip-icon hidden$="[[!indicatorVisible]]" tooltip-text="[[indicatorTooltip_]]" icon-class="[[indicatorIcon]]" icon-aria-label="[[iconAriaLabel]]"> </cr-tooltip-icon>
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/policy/cr_policy_indicator.html
HTML
unknown
243
// 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 Polymer element for indicating policies by type. */ import '../cr_hidden_style.css.js'; import './cr_tooltip_icon.js'; import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {getTemplate} from './cr_policy_indicator.html.js'; import {CrPolicyIndicatorMixin, CrPolicyIndicatorType} from './cr_policy_indicator_mixin.js'; const CrPolicyIndicatorElementBase = CrPolicyIndicatorMixin(PolymerElement); export class CrPolicyIndicatorElement extends CrPolicyIndicatorElementBase { static get is() { return 'cr-policy-indicator'; } static get template() { return getTemplate(); } static get properties() { return { iconAriaLabel: String, indicatorTooltip_: { type: String, computed: 'getIndicatorTooltip_(indicatorType, indicatorSourceName)', }, }; } iconAriaLabel: string; private indicatorTooltip_: string; /** * @param indicatorSourceName The name associated with the indicator. * See chrome.settingsPrivate.PrefObject.controlledByName * @return The tooltip text for |type|. */ private getIndicatorTooltip_( indicatorType: CrPolicyIndicatorType, indicatorSourceName: string): string { return this.getIndicatorTooltip(indicatorType, indicatorSourceName); } } declare global { interface HTMLElementTagNameMap { 'cr-policy-indicator': CrPolicyIndicatorElement; } } customElements.define(CrPolicyIndicatorElement.is, CrPolicyIndicatorElement);
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/policy/cr_policy_indicator.ts
TypeScript
unknown
1,661
// 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 CrPolicyIndicatorElement() {}
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/policy/cr_policy_indicator_externs.js
JavaScript
unknown
358
// 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. /** * @fileoverview Mixin for policy controlled indicators. * TODO(michaelpg): Since extensions can also control settings and be indicated, * rework the "policy" naming scheme throughout this directory. */ import {assertNotReached} from '//resources/js/assert_ts.js'; import {dedupingMixin, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; /** * Strings required for policy indicators. These must be set at runtime. * Chrome OS only strings may be undefined. */ export interface CrPolicyStringsType { controlledSettingExtension: string; controlledSettingExtensionWithoutName: string; controlledSettingPolicy: string; controlledSettingRecommendedMatches: string; controlledSettingRecommendedDiffers: string; // <if expr="chromeos_ash"> controlledSettingShared: string; controlledSettingWithOwner: string; controlledSettingNoOwner: string; controlledSettingParent: string; controlledSettingChildRestriction: string; // </if> } declare global { interface Window { CrPolicyStrings: Partial<CrPolicyStringsType>; } } /** * Possible policy indicators that can be shown in settings. */ export enum CrPolicyIndicatorType { DEVICE_POLICY = 'devicePolicy', EXTENSION = 'extension', NONE = 'none', OWNER = 'owner', PRIMARY_USER = 'primary_user', RECOMMENDED = 'recommended', USER_POLICY = 'userPolicy', PARENT = 'parent', CHILD_RESTRICTION = 'childRestriction', } type Constructor<T> = new (...args: any[]) => T; export const CrPolicyIndicatorMixin = dedupingMixin( <T extends Constructor<PolymerElement>>(superClass: T): T& Constructor<CrPolicyIndicatorMixinInterface> => { class CrPolicyIndicatorMixin extends superClass implements CrPolicyIndicatorMixinInterface { // Properties exposed to all policy indicators. static get properties() { return { /** * Which indicator type to show (or NONE). */ indicatorType: { type: String, value: CrPolicyIndicatorType.NONE, }, /** * The name associated with the policy source. See * chrome.settingsPrivate.PrefObject.controlledByName. */ indicatorSourceName: { type: String, value: '', }, // Computed properties based on indicatorType and // indicatorSourceName. Override to provide different values. indicatorVisible: { type: Boolean, computed: 'getIndicatorVisible_(indicatorType)', }, indicatorIcon: { type: String, computed: 'getIndicatorIcon_(indicatorType)', }, }; } indicatorType: CrPolicyIndicatorType; indicatorSourceName: string; indicatorVisible: boolean; indicatorIcon: string; /** * @return True if the indicator should be shown. */ private getIndicatorVisible_(type: CrPolicyIndicatorType): boolean { return type !== CrPolicyIndicatorType.NONE; } /** * @return {string} The iron-icon icon name. */ private getIndicatorIcon_(type: CrPolicyIndicatorType): string { switch (type) { case CrPolicyIndicatorType.EXTENSION: return 'cr:extension'; case CrPolicyIndicatorType.NONE: return ''; case CrPolicyIndicatorType.PRIMARY_USER: return 'cr:group'; case CrPolicyIndicatorType.OWNER: return 'cr:person'; case CrPolicyIndicatorType.USER_POLICY: case CrPolicyIndicatorType.DEVICE_POLICY: case CrPolicyIndicatorType.RECOMMENDED: return 'cr20:domain'; case CrPolicyIndicatorType.PARENT: case CrPolicyIndicatorType.CHILD_RESTRICTION: return 'cr20:kite'; default: assertNotReached(); } } /** * @param name The name associated with the indicator. See * chrome.settingsPrivate.PrefObject.controlledByName * @param matches For RECOMMENDED only, whether the indicator * value matches the recommended value. * @return The tooltip text for |type|. */ getIndicatorTooltip( type: CrPolicyIndicatorType, name: string, matches?: boolean): string { if (!window.CrPolicyStrings) { return ''; } // Tooltips may not be defined, e.g. in OOBE. const CrPolicyStrings = window.CrPolicyStrings; switch (type) { case CrPolicyIndicatorType.EXTENSION: return name.length > 0 ? CrPolicyStrings.controlledSettingExtension!.replace( '$1', name) : CrPolicyStrings.controlledSettingExtensionWithoutName!; // <if expr="chromeos_ash"> case CrPolicyIndicatorType.PRIMARY_USER: return CrPolicyStrings.controlledSettingShared!.replace( '$1', name); case CrPolicyIndicatorType.OWNER: return name.length > 0 ? CrPolicyStrings.controlledSettingWithOwner!.replace( '$1', name) : CrPolicyStrings.controlledSettingNoOwner!; // </if> case CrPolicyIndicatorType.USER_POLICY: case CrPolicyIndicatorType.DEVICE_POLICY: return CrPolicyStrings.controlledSettingPolicy!; case CrPolicyIndicatorType.RECOMMENDED: return matches ? CrPolicyStrings.controlledSettingRecommendedMatches! : CrPolicyStrings.controlledSettingRecommendedDiffers!; // <if expr="chromeos_ash"> case CrPolicyIndicatorType.PARENT: return CrPolicyStrings.controlledSettingParent!; case CrPolicyIndicatorType.CHILD_RESTRICTION: return CrPolicyStrings.controlledSettingChildRestriction!; // </if> } return ''; } } return CrPolicyIndicatorMixin; }); export interface CrPolicyIndicatorMixinInterface { indicatorType: CrPolicyIndicatorType; indicatorSourceName: string; indicatorVisible: boolean; indicatorIcon: string; getIndicatorTooltip( type: CrPolicyIndicatorType, name: string, matches?: boolean): string; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/policy/cr_policy_indicator_mixin.ts
TypeScript
unknown
6,700
<style include="cr-hidden-style"></style> <cr-tooltip-icon id="tooltipIcon" hidden$="[[!indicatorVisible]]" tooltip-text="[[indicatorTooltip]]" icon-class="[[indicatorIcon]]" icon-aria-label="[[iconAriaLabel]]" exportparts="tooltip"> </cr-tooltip-icon>
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/policy/cr_policy_pref_indicator.html
HTML
unknown
281
// 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 Polymer element for indicating policies that apply to an * element controlling a settings preference. */ import '../cr_hidden_style.css.js'; import './cr_tooltip_icon.js'; import {assert} from '//resources/js/assert_ts.js'; import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {CrPolicyIndicatorMixin, CrPolicyIndicatorType} from './cr_policy_indicator_mixin.js'; import {getTemplate} from './cr_policy_pref_indicator.html.js'; import {CrTooltipIconElement} from './cr_tooltip_icon.js'; const CrPolicyPrefIndicatorElementBase = CrPolicyIndicatorMixin(PolymerElement); export interface CrPolicyPrefIndicatorElement { $: { tooltipIcon: CrTooltipIconElement, }; } export class CrPolicyPrefIndicatorElement extends CrPolicyPrefIndicatorElementBase { static get is() { return 'cr-policy-pref-indicator'; } static get template() { return getTemplate(); } static get properties() { return { iconAriaLabel: String, indicatorType: { type: String, value: CrPolicyIndicatorType.NONE, computed: 'getIndicatorTypeForPref_(pref.*, associatedValue)', }, indicatorTooltip: { type: String, computed: 'getIndicatorTooltipForPref_(indicatorType, pref.*)', }, /** * Optional preference object associated with the indicator. Initialized * to null so that computed functions will get called if this is never * set. */ pref: Object, /** * Optional value for the preference value this indicator is associated * with. If this is set, no indicator will be shown if it is a member * of |pref.userSelectableValues| and is not |pref.recommendedValue|. */ associatedValue: Object, }; } iconAriaLabel: string; override indicatorType: CrPolicyIndicatorType; indicatorTooltip: string; pref?: chrome.settingsPrivate.PrefObject; associatedValue?: any; /** * @return The indicator type based on |pref| and |associatedValue|. */ private getIndicatorTypeForPref_(): CrPolicyIndicatorType { assert(this.pref); const {enforcement, userSelectableValues, controlledBy, recommendedValue} = this.pref; if (enforcement === chrome.settingsPrivate.Enforcement.RECOMMENDED) { if (this.associatedValue !== undefined && this.associatedValue !== recommendedValue) { return CrPolicyIndicatorType.NONE; } return CrPolicyIndicatorType.RECOMMENDED; } if (enforcement === chrome.settingsPrivate.Enforcement.ENFORCED) { // An enforced preference may also have some values still available for // the user to select from. if (userSelectableValues !== undefined) { if (recommendedValue && this.associatedValue === recommendedValue) { return CrPolicyIndicatorType.RECOMMENDED; } else if (userSelectableValues.includes(this.associatedValue)) { return CrPolicyIndicatorType.NONE; } } switch (controlledBy) { case chrome.settingsPrivate.ControlledBy.EXTENSION: return CrPolicyIndicatorType.EXTENSION; case chrome.settingsPrivate.ControlledBy.PRIMARY_USER: return CrPolicyIndicatorType.PRIMARY_USER; case chrome.settingsPrivate.ControlledBy.OWNER: return CrPolicyIndicatorType.OWNER; case chrome.settingsPrivate.ControlledBy.USER_POLICY: return CrPolicyIndicatorType.USER_POLICY; case chrome.settingsPrivate.ControlledBy.DEVICE_POLICY: return CrPolicyIndicatorType.DEVICE_POLICY; case chrome.settingsPrivate.ControlledBy.PARENT: return CrPolicyIndicatorType.PARENT; case chrome.settingsPrivate.ControlledBy.CHILD_RESTRICTION: return CrPolicyIndicatorType.CHILD_RESTRICTION; } } if (enforcement === chrome.settingsPrivate.Enforcement.PARENT_SUPERVISED) { return CrPolicyIndicatorType.PARENT; } return CrPolicyIndicatorType.NONE; } /** * @return The tooltip text for |indicatorType|. */ private getIndicatorTooltipForPref_(): string { if (!this.pref) { return ''; } const matches = this.pref && this.pref.value === this.pref.recommendedValue; return this.getIndicatorTooltip( this.indicatorType, this.pref.controlledByName || '', matches); } getFocusableElement(): HTMLElement { return this.$.tooltipIcon.getFocusableElement(); } } declare global { interface HTMLElementTagNameMap { 'cr-policy-pref-indicator': CrPolicyPrefIndicatorElement; } } customElements.define( CrPolicyPrefIndicatorElement.is, CrPolicyPrefIndicatorElement);
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/policy/cr_policy_pref_indicator.ts
TypeScript
unknown
4,858
// 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 CrPolicyPrefIndicatorElement() {}
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/policy/cr_policy_pref_indicator_externs.js
JavaScript
unknown
362
<style include="cr-shared-style"> :host { display: flex; /* Position independently from the line-height. */ } iron-icon { --iron-icon-width: var(--cr-icon-size); --iron-icon-height: var(--cr-icon-size); --iron-icon-fill-color: var(--cr-tooltip-icon-fill-color, var(--google-grey-700)); } @media (prefers-color-scheme: dark) { iron-icon { --iron-icon-fill-color: var(--cr-tooltip-icon-fill-color, var(--google-grey-500)); } } </style> <iron-icon id="indicator" tabindex="0" aria-label$="[[iconAriaLabel]]" aria-describedby="tooltip" icon="[[iconClass]]" role="img"></iron-icon> <paper-tooltip id="tooltip" for="indicator" position="[[tooltipPosition]]" fit-to-visible-bounds part="tooltip"> <slot name="tooltip-text">[[tooltipText]]</slot> </paper-tooltip>
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/policy/cr_tooltip_icon.html
HTML
unknown
929
// 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 '../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 '//resources/polymer/v3_0/paper-tooltip/paper-tooltip.js'; import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {getTemplate} from './cr_tooltip_icon.html.js'; export interface CrTooltipIconElement { $: { indicator: HTMLElement, }; } export class CrTooltipIconElement extends PolymerElement { static get is() { return 'cr-tooltip-icon'; } static get template() { return getTemplate(); } static get properties() { return { iconAriaLabel: String, iconClass: String, tooltipText: String, /** Position of tooltip popup related to the icon. */ tooltipPosition: { type: String, value: 'top', }, }; } iconAriaLabel: string; iconClass: string; tooltipText: string; tooltipPosition: string; getFocusableElement(): HTMLElement { return this.$.indicator; } } declare global { interface HTMLElementTagNameMap { 'cr-tooltip-icon': CrTooltipIconElement; } } customElements.define(CrTooltipIconElement.is, CrTooltipIconElement);
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/policy/cr_tooltip_icon.ts
TypeScript
unknown
1,386
// 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 CrTooltipIconElement() {}
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/policy/cr_tooltip_icon_externs.js
JavaScript
unknown
354
/* 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 */ .search-bubble { --search-bubble-color: var(--paper-yellow-500); position: absolute; z-index: 1; } .search-bubble-innards { align-items: center; background-color: var(--search-bubble-color); border-radius: 2px; color: var(--google-grey-900); max-width: 100px; min-width: 64px; overflow: hidden; padding: 4px 10px; text-align: center; text-overflow: ellipsis; white-space: nowrap; } /* Provides the arrow which points at the anchor element. */ .search-bubble-innards::after { background-color: var(--search-bubble-color); content: ''; height: 10px; left: calc(50% - 5px); position: absolute; top: -5px; transform: rotate(-45deg); width: 10px; z-index: -1; } /* Turns the arrow direction downwards, when the bubble is placed above * the anchor element */ .search-bubble-innards.above::after { bottom: -5px; top: auto; transform: rotate(-135deg); }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/search_highlight_style.css
CSS
unknown
1,163
// 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 Mixin to be used by Polymer elements that want to * automatically remove WebUI listeners when detached. */ import {addWebUiListener, removeWebUiListener, WebUiListener} from '//resources/js/cr.js'; import {dedupingMixin, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; type Constructor<T> = new (...args: any[]) => T; export const WebUiListenerMixin = dedupingMixin( <T extends Constructor<PolymerElement>>(superClass: T): T& Constructor<WebUiListenerMixinInterface> => { class WebUiListenerMixin extends superClass implements WebUiListenerMixinInterface { /** * Holds WebUI listeners that need to be removed when this element is * destroyed. */ private webUiListeners_: WebUiListener[] = []; /** * Adds a WebUI listener and registers it for automatic removal when * this element is detached. Note: Do not use this method if you intend * to remove this listener manually (use addWebUiListener directly * instead). * * @param eventName The event to listen to. * @param callback The callback run when the event is fired. */ addWebUiListener(eventName: string, callback: Function) { this.webUiListeners_.push(addWebUiListener(eventName, callback)); } override disconnectedCallback() { super.disconnectedCallback(); while (this.webUiListeners_.length > 0) { removeWebUiListener(this.webUiListeners_.pop()!); } } } return WebUiListenerMixin; }); export interface WebUiListenerMixinInterface { addWebUiListener(eventName: string, callback: Function): void; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/cr_elements/web_ui_listener_mixin.ts
TypeScript
unknown
1,907
/* 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. */ [is='action-link'] { cursor: pointer; display: inline-block; text-decoration: none; } [is='action-link']:hover { text-decoration: underline; } [is='action-link']:active { color: rgb(5, 37, 119); text-decoration: underline; } [is='action-link'][disabled] { color: #999; cursor: default; pointer-events: none; text-decoration: none; } [is='action-link'].no-outline { outline: none; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/css/action_link.css
CSS
unknown
555
/* Copyright 2012 The Chromium Authors * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* This file holds CSS that should be shared, in theory, by all user-visible * chrome:// pages. */ @import url(chrome://resources/css/text_defaults.css); @import url(widgets.css); /* Prevent CSS from overriding the hidden property. */ [hidden] { display: none !important; } html { height: 100%; /* For printing. */ } html.loading * { transition-delay: 0ms !important; transition-duration: 0ms !important; } body { cursor: default; margin: 0; } p { line-height: 1.8em; } h1, h2, h3 { font-weight: normal; /* Makes the vertical size of the text the same for all fonts. */ line-height: 1; user-select: none; } h1 { font-size: 1.5em; } h2 { font-size: 1.3em; margin-bottom: 0.4em; } h3 { color: black; font-size: 1.2em; margin-bottom: 0.8em; } a { color: rgb(17, 85, 204); text-decoration: underline; } a:active { color: rgb(5, 37, 119); } /* Elements that need to be LTR even in an RTL context, but should align * right. (Namely, URLs, search engine names, etc.) */ html[dir='rtl'] .weakrtl { direction: ltr; text-align: right; } /* Input fields in search engine table need to be weak-rtl. Since those input * fields are generated for all cr.ListItem elements (and we only want weakrtl * on some), the class needs to be on the enclosing div. */ html[dir='rtl'] div.weakrtl input { direction: ltr; text-align: right; } html[dir='rtl'] .favicon-cell.weakrtl { padding-inline-end: 22px; padding-inline-start: 0; } /* weakrtl for selection drop downs needs to account for the fact that * Webkit does not honor the text-align attribute for the select element. * (See Webkit bug #40216) */ html[dir='rtl'] select.weakrtl { direction: rtl; } html[dir='rtl'] select.weakrtl option { direction: ltr; } /* WebKit does not honor alignment for text specified via placeholder attribute. * This CSS is a workaround. Please remove once WebKit bug is fixed. * https://bugs.webkit.org/show_bug.cgi?id=63367 */ html[dir='rtl'] input.weakrtl::-webkit-input-placeholder, html[dir='rtl'] .weakrtl input::-webkit-input-placeholder { direction: rtl; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/css/chrome_shared.css
CSS
unknown
2,258
/* Copyright 2012 The Chromium Authors * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ list, grid { display: block; outline: none; overflow: auto; position: relative; /* Make sure that item offsets are relative to the list. */ } list > *, grid > * { background-color: rgba(255, 255, 255, 0); border: 1px solid rgba(255, 255, 255, 0); /* transparent white */ border-radius: 2px; cursor: default; line-height: 20px; margin: -1px 0; overflow: hidden; padding: 0 3px; position: relative; /* to allow overlap */ text-overflow: ellipsis; user-select: none; white-space: pre; } list > * { display: block; } grid > * { display: inline-block; } list > [lead], grid > [lead] { border-color: transparent; } list:focus > [lead], grid:focus > [lead] { border-color: hsl(214, 91%, 65%); z-index: 2; } list > [anchor], grid > [anchor] { } list:not([disabled]) > :hover, grid:not([disabled]) > :hover { background-color: hsl(214, 91%, 97%); border-color: hsl(214, 91%, 85%); z-index: 1; } list > [selected], grid > [selected] { background-color: hsl(0, 0%, 90%); background-image: -webkit-linear-gradient(rgba(255, 255, 255, 0.8), rgba(255, 255, 255, 0)); border-color: hsl(0, 0%, 85%); z-index: 2; } list:focus > [selected], grid:focus > [selected] { background-color: hsl(214, 91%, 89%); border-color: hsl(214, 91%, 65%); } list:focus > [lead][selected], list > [selected]:hover, grid:focus > [lead][selected], grid > [selected]:hover { background-color: hsl(214, 91%, 87%); border-color: hsl(214, 91%, 65%); } list > .spacer, grid > .spacer { border: 0; box-sizing: border-box; display: block; margin: 0; overflow: hidden; visibility: hidden; } list :-webkit-any( input[type='input'], input[type='password'], input[type='search'], input[type='text'], input[type='url']), list :-webkit-any( button, input[type='button'], input[type='submit'], select):not(.custom-appearance) { line-height: normal; margin: 0; vertical-align: middle; } list > [hidden], grid > [hidden] { display: none; } list > .drag-selection-border { background-color: rgba(255, 255, 255, 0.3); border: 2px solid rgba(255, 255, 255, 0.6); border-radius: 0; outline: 1px solid rgba(0, 0, 0, 0.1); position: absolute; z-index: 2; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/css/list.css
CSS
unknown
2,460
/* 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. */ html { /* This is a custom, Chrome-specific color that does not have a --paper or * --google equivalent. */ --md-background-color: rgb(248, 249, 250); --md-loading-message-color: #6e6e6e; --md-toolbar-color: white; --md-toolbar-height: 56px; } @media (prefers-color-scheme: dark) { html { --md-background-color: rgb(32, 33, 36); /* --google-grey-900 */ --md-loading-message-color: #9AA0A6; /* --google-grey-500 */ /* --cr-separator-line */ --md-toolbar-border: 1px solid rgba(255, 255, 255, .1); --md-toolbar-color: rgba(255, 255, 255, .04); } }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/css/md_colors.css
CSS
unknown
733
/* Copyright 2012 The Chromium Authors * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ cr-menu { -webkit-box-shadow: 0 2px 4px rgba(0, 0, 0, .50); background: white; border-radius: 2px; color: black; cursor: default; left: 0; margin: 0; outline: 1px solid rgba(0, 0, 0, 0.2); padding: 8px 0; position: fixed; white-space: nowrap; z-index: 3; } cr-menu:not(.decorated) { display: none; } cr-menu > * { box-sizing: border-box; display: block; margin: 0; text-align: start; width: 100%; } cr-menu > :not(hr) { -webkit-appearance: none; background: transparent; border: 0; color: black; font: inherit; line-height: 18px; outline: none; overflow: hidden; padding: 0 19px; text-overflow: ellipsis; } cr-menu > hr { background: -webkit-linear-gradient(left, rgba(0, 0, 0, .10), rgba(0, 0, 0, .02) 96%); border: 0; height: 1px; margin: 8px 0; } cr-menu > [disabled] { color: rgba(0, 0, 0, .3); } cr-menu > [hidden] { display: none; } cr-menu > :not(hr):-webkit-any([selected], :active) { background-color: rgba(0, 0, 0, .06); } cr-menu > [checked]::before { content: url(../images/checkbox_black.png); display: inline-block; height: 9px; margin: 0 5px; width: 9px; } cr-menu > [checked] { padding-inline-start: 0; } cr-menu > [selected][checked]:active::before { content: url(../images/checkbox_white.png); } /* TODO(zvorygin) menu > [shortcutText]::after - this selector is much better, * but it's buggy in current webkit revision, so I have to use [showShortcuts]. */ cr-menu[showShortcuts] > ::after { color: #999; content: attr(shortcutText); float: right; padding-inline-start: 30px; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/css/menu.css
CSS
unknown
1,824
/* Copyright 2012 The Chromium Authors * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* NOTE: If you are using the drop-down style, you must first call * MenuButton.createDropDownArrows() to initialize the CSS canvases that * contain the arrow images. */ button.menu-button.drop-down { background: white url(../images/drop_down_arrow_gray.svg) no-repeat center 4px; border: 1px solid rgb(192, 195, 198); border-radius: 2px; height: 12px; margin: 0 5px; padding: 0; position: relative; top: 1px; width: 12px; } button.menu-button.drop-down:hover { background-image: url(../images/drop_down_arrow_black.svg); border-color: rgb(48, 57, 66); } button.menu-button.drop-down[menu-shown], button.menu-button.drop-down:focus { background-color: rgb(48, 57, 66); background-image: url(../images/drop_down_arrow_white.svg); border-color: rgb(48, 57, 66); } button.menu-button.using-mouse { outline: none; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/css/menu_button.css
CSS
unknown
995
/* 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. */ .os-link-container-container { margin: 20px; } .os-link-container { align-items: center; /* color_primary GRAY 200 */ border: 1px solid rgb(232, 234, 237); font-family: 'Roboto', Roboto, sans-serif; border-radius: 4px; display: flex; font-size: 14px; line-height: 20px; margin-bottom: 28px; padding: 12px; } @media (prefers-color-scheme: dark) { .os-link-container { /* color_primary GRAY 900 */ border: 1px solid rgb(32, 33, 36); } } .os-link-icon { background-image: url(chrome://resources/images/os_system_app_icon.svg); background-size: 16px 16px; height: 16px; margin-inline-end: 16px; width: 16px; } #os-link-href { font-size: 14px; line-height: 20px; padding-inline-start: 4px; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/css/os_header.css
CSS
unknown
888
/* Copyright 2012 The Chromium Authors * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* The shield that overlays the background. */ .overlay { -webkit-box-align: center; -webkit-box-orient: vertical; -webkit-box-pack: center; background-color: rgba(255, 255, 255, 0.75); bottom: 0; display: -webkit-box; left: 0; overflow: auto; padding: 20px; /* TODO(dbeam): remove perspective when http://crbug.com/374970 is fixed. */ perspective: 1px; position: fixed; right: 0; top: 0; transition: 200ms opacity; } /* Used to slide in the overlay. */ .overlay.transparent .page { /* TODO(flackr): Add perspective(500px) rotateX(5deg) when accelerated * compositing is enabled on chrome:// pages. See http://crbug.com/116800. */ transform: scale(0.99) translateY(-20px); } /* The foreground dialog. */ .overlay .page { -webkit-border-radius: 3px; -webkit-box-orient: vertical; background: white; box-shadow: 0 4px 23px 5px rgba(0, 0, 0, 0.2), 0 2px 6px rgba(0,0,0,0.15); color: #333; display: -webkit-box; min-width: 400px; padding: 0; position: relative; transition: 200ms transform; z-index: 0; } /* If the options page is loading don't do the transition. */ .loading .overlay, .loading .overlay .page { transition-duration: 0ms !important; } /* keyframes used to pulse the overlay */ @keyframes pulse { 0% { transform: scale(1); } 40% { transform: scale(1.02); } 60% { transform: scale(1.02); } 100% { transform: scale(1); } } .overlay .page.pulse { animation-duration: 180ms; animation-iteration-count: 1; animation-name: pulse; animation-timing-function: ease-in-out; } .overlay .page > .close-button { background-image: url(chrome://theme/IDR_CLOSE_DIALOG); background-position: center; background-repeat: no-repeat; height: 14px; position: absolute; right: 7px; top: 7px; width: 14px; z-index: 1; } html[dir='rtl'] .overlay .page > .close-button { left: 10px; right: auto; } .overlay .page > .close-button:hover { background-image: url(chrome://theme/IDR_CLOSE_DIALOG_H); } .overlay .page > .close-button:active { background-image: url(chrome://theme/IDR_CLOSE_DIALOG_P); } .overlay .page h1 { color: #333; /* 120% of the body's font-size of 84% is 16px. This will keep the relative * size between the body and these titles consistent. */ font-size: 120%; /* TODO(flackr): Pages like sync-setup and delete user collapse the margin * above the top of the page. Use padding instead to make sure that the * headers of these pages have the correct spacing, but this should not be * necessary. See http://crbug.com/119029. */ margin: 0; padding: 14px 17px 14px; text-shadow: white 0 1px 2px; user-select: none; } .overlay .page .content-area { -webkit-box-flex: 1; overflow: auto; padding: 6px 17px 6px; position: relative; } .overlay .page .action-area { -webkit-box-align: center; -webkit-box-orient: horizontal; -webkit-box-pack: end; display: -webkit-box; padding: 14px 17px; } html[dir='rtl'] .overlay .page .action-area { left: 0; } .overlay .page .action-area-right { display: -webkit-box; } .overlay .page .button-strip { -webkit-box-orient: horizontal; display: -webkit-box; } .overlay .page .button-strip > :-webkit-any(button, input[type='button'], input[type='submit']) { display: block; margin-inline-start: 10px; } .overlay .page .button-strip > .default-button:not(:focus) { border-color: rgba(0, 0, 0, 0.5); } .overlay .page .spacer-div { -webkit-box-flex: 1; } /* On OSX 10.7, hidden scrollbars may prevent the user from realizing that the * overlay contains scrollable content. To resolve this, style the scrollbars on * OSX so they are always visible. See http://crbug.com/123010. */ <if expr="is_macosx or is_ios"> .overlay .page .content-area::-webkit-scrollbar { -webkit-appearance: none; width: 11px; } .overlay .page .content-area::-webkit-scrollbar-thumb { background-color: rgba(0, 0, 0, 0.2); border: 2px solid white; border-radius: 8px; } .overlay .page .content-area::-webkit-scrollbar-thumb:hover { background-color: rgba(0, 0, 0, 0.5); } </if> .gray-bottom-bar { background-color: #f5f5f5; border-bottom-left-radius: inherit; border-bottom-right-radius: inherit; border-color: #e7e7e7; border-top-style: solid; border-width: 1px; color: #888; display: -webkit-box; padding: 14px 17px; } /* Prevent the page underneath the overlay from scrolling. */ .frozen { position: fixed; } #overlay-container-1 { z-index: 11; } #overlay-container-2 { z-index: 12; } .transparent { opacity: 0; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/css/overlay.css
CSS
unknown
4,797
/* 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. */ @font-face { font-family: 'Roboto'; font-style: normal; font-weight: 400; src: local('Roboto'), local('Roboto-Regular'), url(//resources/roboto/roboto-regular.woff2) format('woff2'); } @font-face { font-family: 'Roboto'; font-style: normal; font-weight: 500; src: local('Roboto Medium'), local('Roboto-Medium'), url(//resources/roboto/roboto-medium.woff2) format('woff2'); } @font-face { font-family: 'Roboto'; font-style: normal; font-weight: 700; src: local('Roboto Bold'), local('Roboto-Bold'), url(//resources/roboto/roboto-bold.woff2) format('woff2'); }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/css/roboto.css
CSS
unknown
750
/* Copyright 2012 The Chromium Authors * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ .inline-spinner, .spinner { background-image: url(../images/throbber_small.svg); background-size: 100%; } .inline-spinner { display: inline-block; height: 16px; width: 16px; } .spinner { height: 22px; width: 22px; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/css/spinner.css
CSS
unknown
379
/* Copyright 2014 The Chromium Authors * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* This file is dynamically processed by a C++ data source handler to fill in * some per-platform/locale styles that dramatically alter the page. This is * done to reduce flicker, as JS may not run before the page is rendered. * * There are two ways to include this stylesheet: * 1. via its chrome://resources/ URL in HTML, i.e.: * * <link rel="stylesheet" href="chrome://resources/css/text_defaults.css"> * * 2. via the webui::AppendWebUICSSTextDefaults() method to directly append it * to an HTML string. * Otherwise its placeholders won't be expanded. */ body { font-family: $i18nRaw{fontfamily}; font-size: $i18n{fontsize}; } button { font-family: $i18nRaw{fontfamily}; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/css/text_defaults.css
CSS
unknown
844
/* 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. */ /* This file is dynamically processed by a C++ data source handler to fill in * some per-platform/locale styles that dramatically alter the page. This is * done to reduce flicker, as JS may not run before the page is rendered. * * There are two ways to include this stylesheet: * 1. via its chrome://resources/ URL in HTML, i.e.: * * <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css"> * * 2. via the webui::AppendWebUICSSTextDefaultsMd() method to directly append it * to an HTML string. * Otherwise its placeholders won't be expanded. */ <if expr="not chromeos_ash and not is_android"> @import url(//resources/css/roboto.css); </if> body { font-family: $i18nRaw{fontfamilyMd}; font-size: 81.25%; } button { font-family: $i18nRaw{fontfamilyMd}; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/css/text_defaults_md.css
CSS
unknown
940
/* Copyright 2012 The Chromium Authors * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ .throbber { background: url(../images/throbber_small.svg) no-repeat; display: inline-block; height: 16px; width: 16px; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/css/throbber.css
CSS
unknown
276
/* Copyright 2012 The Chromium Authors * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* This file defines styles for form controls. The order of rule blocks is * important as there are some rules with equal specificity that rely on order * as a tiebreaker. These are marked with OVERRIDE. */ @import url(action_link.css); /* Default state **************************************************************/ :-webkit-any(button, input[type='button'], input[type='submit']):not(.custom-appearance), select, input[type='checkbox'], input[type='radio'] { -webkit-appearance: none; background-image: -webkit-linear-gradient(#ededed, #ededed 38%, #dedede); border: 1px solid rgba(0, 0, 0, 0.25); border-radius: 2px; box-shadow: 0 1px 0 rgba(0, 0, 0, 0.08), inset 0 1px 2px rgba(255, 255, 255, 0.75); color: #444; font: inherit; margin: 0 1px 0 0; outline: none; text-shadow: 0 1px 0 rgb(240, 240, 240); user-select: none; } :-webkit-any(button, input[type='button'], input[type='submit']):not(.custom-appearance), select { min-height: 2em; min-width: 4em; padding-bottom: 1px; <if expr="is_win or is_macosx"> /* The following platform-specific rule is necessary to get adjacent * buttons, text inputs, and so forth to align on their borders while also * aligning on the text's baselines. */ padding-bottom: 2px; </if> padding-top: 1px; } :-webkit-any(button, input[type='button'], input[type='submit']):not(.custom-appearance) { padding-inline-end: 10px; padding-inline-start: 10px; } select { -webkit-appearance: none; /* OVERRIDE */ background-image: -webkit-image-set( url(../images/select.png) 1x, url(../images/2x/select.png) 2x), -webkit-linear-gradient(#ededed, #ededed 38%, #dedede); background-position: right center; background-repeat: no-repeat; padding-inline-end: 24px; padding-inline-start: 10px; } html[dir='rtl'] select { background-position: center left; } input[type='checkbox'] { height: 13px; position: relative; vertical-align: middle; width: 13px; } input[type='radio'] { /* OVERRIDE */ border-radius: 100%; height: 15px; position: relative; vertical-align: middle; width: 15px; } /* TODO(estade): add more types here? */ input[type='number'], input[type='password'], input[type='search'], input[type='text'], input[type='url'], input:not([type]), textarea { border: 1px solid #bfbfbf; border-radius: 2px; box-sizing: border-box; color: #444; font: inherit; margin: 0; /* Use min-height to accommodate addditional padding for touch as needed. */ min-height: 2em; outline: none; padding: 3px; <if expr="is_win or is_macosx or is_ios"> /* For better alignment between adjacent buttons and inputs. */ padding-bottom: 4px; </if> } input[type='search'] { -webkit-appearance: textfield; /* NOTE: Keep a relatively high min-width for this so we don't obscure the end * of the default text in relatively spacious languages (i.e. German). */ min-width: 160px; } /* Checked ********************************************************************/ input[type='checkbox']:checked::before { background-image: -webkit-image-set( url(../images/check.png) 1x, url(../images/2x/check.png) 2x); background-size: 100% 100%; content: ''; display: block; height: 100%; user-select: none; width: 100%; } input[type='radio']:checked::before { background-color: #666; border-radius: 100%; bottom: 3px; content: ''; display: block; left: 3px; position: absolute; right: 3px; top: 3px; } <if expr="not is_ios"> /* Hover **********************************************************************/ :enabled:hover:-webkit-any( select, input[type='checkbox'], input[type='radio'], :-webkit-any( button, input[type='button'], input[type='submit']):not(.custom-appearance)) { background-image: -webkit-linear-gradient(#f0f0f0, #f0f0f0 38%, #e0e0e0); border-color: rgba(0, 0, 0, 0.3); box-shadow: 0 1px 0 rgba(0, 0, 0, 0.12), inset 0 1px 2px rgba(255, 255, 255, 0.95); color: black; } :enabled:hover:-webkit-any(select) { /* OVERRIDE */ background-image: -webkit-image-set( url(../images/select.png) 1x, url(../images/2x/select.png) 2x), -webkit-linear-gradient(#f0f0f0, #f0f0f0 38%, #e0e0e0); } </if> /* Active *********************************************************************/ :enabled:active:-webkit-any( select, input[type='checkbox'], input[type='radio'], :-webkit-any( button, input[type='button'], input[type='submit']):not(.custom-appearance)) { background-image: -webkit-linear-gradient(#e7e7e7, #e7e7e7 38%, #d7d7d7); box-shadow: none; text-shadow: none; } :enabled:active:-webkit-any(select) { /* OVERRIDE */ background-image: url(../images/select.png), -webkit-linear-gradient(#e7e7e7, #e7e7e7 38%, #d7d7d7); } /* Disabled *******************************************************************/ :disabled:-webkit-any( button, input[type='button'], input[type='submit']):not(.custom-appearance), select:disabled { background-image: -webkit-linear-gradient(#f1f1f1, #f1f1f1 38%, #e6e6e6); border-color: rgba(80, 80, 80, 0.2); box-shadow: 0 1px 0 rgba(80, 80, 80, 0.08), inset 0 1px 2px rgba(255, 255, 255, 0.75); color: #aaa; } select:disabled { /* OVERRIDE */ background-image: -webkit-image-set( url(../images/disabled_select.png) 1x, url(../images/2x/disabled_select.png) 2x), -webkit-linear-gradient(#f1f1f1, #f1f1f1 38%, #e6e6e6); } input:disabled:-webkit-any([type='checkbox'], [type='radio']) { opacity: .75; } input:disabled:-webkit-any([type='password'], [type='search'], [type='text'], [type='url'], :not([type])) { color: #999; } /* Focus **********************************************************************/ :enabled:focus:-webkit-any( select, input[type='checkbox'], input[type='number'], input[type='password'], input[type='radio'], input[type='search'], input[type='text'], input[type='url'], input:not([type]), :-webkit-any( button, input[type='button'], input[type='submit']):not(.custom-appearance)) { /* We use border color because it follows the border radius (unlike outline). * This is particularly noticeable on mac. */ border-color: rgb(77, 144, 254); outline: none; /* OVERRIDE */ transition: border-color 200ms; } /* Checkbox/radio helpers ****************************************************** * * .checkbox and .radio classes wrap labels. Checkboxes and radios should use * these classes with the markup structure: * * <div class="checkbox"> * <label> * <input type="checkbox"> * <span> * </label> * </div> */ :-webkit-any(.checkbox, .radio) label { /* Don't expand horizontally: <http://crbug.com/112091>. */ align-items: center; display: inline-flex; padding-bottom: 7px; padding-top: 7px; user-select: none; } :-webkit-any(.checkbox, .radio) label input { flex-shrink: 0; } :-webkit-any(.checkbox, .radio) label input ~ span { /* Make sure long spans wrap at the same horizontal position they start. */ display: block; margin-inline-start: 0.6em; } :-webkit-any(.checkbox, .radio) label:hover { color: black; } label > input:disabled:-webkit-any([type='checkbox'], [type='radio']) ~ span { color: #999; } extensionview { display: inline-block; height: 300px; width: 300px; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/css/widgets.css
CSS
unknown
7,854
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Action links are elements that are used to perform an in-page navigation or // action (e.g. showing a dialog). // // They look like normal anchor (<a>) tags as their text color is blue. However, // they're subtly different as they're not initially underlined (giving users a // clue that underlined links navigate while action links don't). // // Action links look very similar to normal links when hovered (hand cursor, // underlined). This gives the user an idea that clicking this link will do // something similar to navigation but in the same page. // // They can be created in JavaScript like this (note second arg): // // var link = document.createElement('a', {is: 'action-link'}); // // or with a constructor like this: // // var link = new ActionLink(); // // They can be used easily from HTML as well, like so: // // <a is="action-link">Click me!</a> // // NOTE: <action-link> and document.createElement('action-link') don't work. class ActionLink extends HTMLAnchorElement { private boundOnKeyDown_: ((e: KeyboardEvent) => void)|null = null; private boundOnMouseDown_: (() => void)|null = null; private boundOnBlur_: (() => void)|null = null; connectedCallback() { // Action links can start disabled (e.g. <a is="action-link" disabled>). this.tabIndex = this.disabled ? -1 : 0; if (!this.hasAttribute('role')) { this.setAttribute('role', 'link'); } this.boundOnKeyDown_ = (e: KeyboardEvent) => { if (!this.disabled && e.key === 'Enter' && !this.href) { // Schedule a click asynchronously because other 'keydown' handlers // may still run later (e.g. document.addEventListener('keydown')). // Specifically options dialogs break when this timeout isn't here. // NOTE: this affects the "trusted" state of the ensuing click. I // haven't found anything that breaks because of this (yet). window.setTimeout(() => this.click(), 0); } }; this.addEventListener('keydown', this.boundOnKeyDown_!); function preventDefault(e: Event) { e.preventDefault(); } function removePreventDefault() { document.removeEventListener('selectstart', preventDefault); document.removeEventListener('mouseup', removePreventDefault); } this.boundOnMouseDown_ = () => { // This handlers strives to match the behavior of <a href="...">. // While the mouse is down, prevent text selection from dragging. document.addEventListener('selectstart', preventDefault); document.addEventListener('mouseup', removePreventDefault); // If focus started via mouse press, don't show an outline. if (document.activeElement !== this) { this.classList.add('no-outline'); } }; this.addEventListener('mousedown', this.boundOnMouseDown_!); this.boundOnBlur_ = () => this.classList.remove('no-outline'); this.addEventListener('blur', this.boundOnBlur_!); } disconnectedCallback() { this.removeEventListener('keydown', this.boundOnKeyDown_!); this.boundOnKeyDown_ = null; this.removeEventListener('mousedown', this.boundOnMouseDown_!); this.boundOnMouseDown_ = null; this.removeEventListener('blur', this.boundOnBlur_!); this.boundOnBlur_ = null; } set disabled(disabled: boolean) { if (disabled) { HTMLAnchorElement.prototype.setAttribute.call(this, 'disabled', ''); } else { HTMLAnchorElement.prototype.removeAttribute.call(this, 'disabled'); } this.tabIndex = disabled ? -1 : 0; } get disabled(): boolean { return this.hasAttribute('disabled'); } override setAttribute(attr: string, val: string) { if (attr.toLowerCase() === 'disabled') { this.disabled = true; } else { super.setAttribute(attr, val); } } override removeAttribute(attr: string) { if (attr.toLowerCase() === 'disabled') { this.disabled = false; } else { super.removeAttribute(attr); } } } customElements.define('action-link', ActionLink, {extends: 'a'});
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/action_link.ts
TypeScript
unknown
4,182
// 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. /** @fileoverview A better version of assert.js for TypeScript. */ /** * Verify |value| is truthy. * @param value A value to check for truthiness. Note that this * may be used to test whether |value| is defined or not, and we don't want * to force a cast to boolean. */ export function assert<T>(value: T, message?: string): asserts value { if (value) { return; } throw new Error('Assertion failed' + (message ? `: ${message}` : '')); } export function assertInstanceof<T>( value: unknown, type: {new (...args: any): T}, message?: string): asserts value is T { if (value instanceof type) { return; } throw new Error( message || `Value ${value} is not of type ${type.name || typeof type}`); } /** * Call this from places in the code that should never be reached. * * For example, handling all the values of enum with a switch() like this: * * function getValueFromEnum(enum) { * switch (enum) { * case ENUM_FIRST_OF_TWO: * return first * case ENUM_LAST_OF_TWO: * return last; * } * assertNotReached(); * } * * This code should only be hit in the case of serious programmer error or * unexpected input. */ export function assertNotReached(message: string = 'Unreachable code hit'): never { assert(false, message); }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/assert_ts.ts
TypeScript
unknown
1,477
// 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 {CommandHandlerFactory, CommandHandlerRemote} from '../browser_command.mojom-webui.js'; /** * @fileoverview This file provides a class that exposes the Mojo handler * interface used for sending the browser commands to the browser and * receiving the browser response. */ let instance: BrowserCommandProxy|null = null; export class BrowserCommandProxy { static getInstance(): BrowserCommandProxy { return instance || (instance = new BrowserCommandProxy()); } static setInstance(newInstance: BrowserCommandProxy) { instance = newInstance; } handler: CommandHandlerRemote; constructor() { this.handler = new CommandHandlerRemote(); const factory = CommandHandlerFactory.getRemote(); factory.createBrowserCommandHandler( this.handler.$.bindNewPipeAndPassReceiver()); } }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/browser_command/browser_command_proxy.ts
TypeScript
unknown
970
// 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 Helper functions for color manipulations. */ import {SkColor} from '//resources/mojo/skia/public/mojom/skcolor.mojom-webui.js'; /** * Converts an SkColor object to a string in the form * "rgba(<red>, <green>, <blue>, <alpha>)". * @param skColor The input color. * @return The rgba string. */ export function skColorToRgba(skColor: SkColor): string { const a = (skColor.value >> 24) & 0xff; const r = (skColor.value >> 16) & 0xff; const g = (skColor.value >> 8) & 0xff; const b = skColor.value & 0xff; return `rgba(${r}, ${g}, ${b}, ${(a / 255).toFixed(2)})`; } /** * Converts a string of the form "#rrggbb" to an SkColor object. * @param hexColor The color string. * @return The SkColor object, */ export function hexColorToSkColor(hexColor: string): SkColor { if (!/^#[0-9a-f]{6}$/.test(hexColor)) { return {value: 0}; } const r = parseInt(hexColor.substring(1, 3), 16); const g = parseInt(hexColor.substring(3, 5), 16); const b = parseInt(hexColor.substring(5, 7), 16); return {value: 0xff000000 + (r << 16) + (g << 8) + b}; } /** * Converts a string of the form "<red>, <green>, <blue>" to an SkColor * object. * @param rgb The rgb color string. * @return The SkColor object, */ export function rgbToSkColor(rgb: string): SkColor { const rgbValues = rgb.split(','); const hex = rgbValues.map((bit) => { bit = parseInt(bit).toString(16); return (bit.length === 1) ? '0' + bit : bit; }); return hexColorToSkColor('#' + hex.join('')); }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/color_utils.ts
TypeScript
unknown
1,663
// 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 {assert} from './assert_ts.js'; import {PromiseResolver} from './promise_resolver.js'; export interface WebUiListener { eventName: string; uid: number; } /** Counter for use with createUid */ let uidCounter: number = 1; /** @return A new unique ID. */ function createUid(): number { return uidCounter++; } /** * The mapping used by the sendWithPromise mechanism to tie the Promise * returned to callers with the corresponding WebUI response. The mapping is * from ID to the PromiseResolver helper; the ID is generated by * sendWithPromise and is unique across all invocations of said method. */ const chromeSendResolverMap: {[id: string]: PromiseResolver<any>} = {}; /** * The named method the WebUI handler calls directly in response to a * chrome.send call that expects a response. The handler requires no knowledge * of the specific name of this method, as the name is passed to the handler * as the first argument in the arguments list of chrome.send. The handler * must pass the ID, also sent via the chrome.send arguments list, as the * first argument of the JS invocation; additionally, the handler may * supply any number of other arguments that will be included in the response. * @param id The unique ID identifying the Promise this response is * tied to. * @param isSuccess Whether the request was successful. * @param response The response as sent from C++. */ export function webUIResponse(id: string, isSuccess: boolean, response: any) { const resolver = chromeSendResolverMap[id]; assert(resolver); delete chromeSendResolverMap[id]; if (isSuccess) { resolver.resolve(response); } else { resolver.reject(response); } } /** * A variation of chrome.send, suitable for messages that expect a single * response from C++. * @param methodName The name of the WebUI handler API. * @param args Variable number of arguments to be forwarded to the * C++ call. */ export function sendWithPromise( methodName: string, ...args: any[]): Promise<any> { const promiseResolver = new PromiseResolver(); const id = methodName + '_' + createUid(); chromeSendResolverMap[id] = promiseResolver; chrome.send(methodName, [id].concat(args)); return promiseResolver.promise; } /** * A map of maps associating event names with listeners. The 2nd level map * associates a listener ID with the callback function, such that individual * listeners can be removed from an event without affecting other listeners of * the same event. */ const webUiListenerMap: {[event: string]: {[listenerId: number]: Function}} = {}; /** * The named method the WebUI handler calls directly when an event occurs. * The WebUI handler must supply the name of the event as the first argument * of the JS invocation; additionally, the handler may supply any number of * other arguments that will be forwarded to the listener callbacks. * @param event The name of the event that has occurred. * @param args Additional arguments passed from C++. */ export function webUIListenerCallback(event: string, ...args: any[]) { const eventListenersMap = webUiListenerMap[event]; if (!eventListenersMap) { // C++ event sent for an event that has no listeners. // TODO(dpapad): Should a warning be displayed here? return; } for (const listenerId in eventListenersMap) { eventListenersMap[listenerId]!.apply(null, args); } } /** * Registers a listener for an event fired from WebUI handlers. Any number of * listeners may register for a single event. * @param eventName The event to listen to. * @param callback The callback run when the event is fired. * @return An object to be used for removing a listener via * removeWebUiListener. Should be treated as read-only. */ export function addWebUiListener( eventName: string, callback: Function): WebUiListener { webUiListenerMap[eventName] = webUiListenerMap[eventName] || {}; const uid = createUid(); webUiListenerMap[eventName]![uid] = callback; return {eventName: eventName, uid: uid}; } /** * Removes a listener. Does nothing if the specified listener is not found. * @param listener The listener to be removed (as returned by addWebUiListener). * @return Whether the given listener was found and actually removed. */ export function removeWebUiListener(listener: WebUiListener): boolean { const listenerExists = webUiListenerMap[listener.eventName] && webUiListenerMap[listener.eventName]![listener.uid]; if (listenerExists) { const map = webUiListenerMap[listener.eventName]!; delete map[listener.uid]; return true; } return false; } // Globally expose functions that must be called from C++. type WindowAndCr = Window&{cr?: object}; assert(!(window as WindowAndCr).cr); Object.assign(window, {cr: {webUIResponse, webUIListenerCallback}});
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/cr.ts
TypeScript
unknown
4,973
// 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 Base class for Web Components that don't use Polymer. * See the following file for usage: * chrome/test/data/webui/js/custom_element_test.js */ function emptyHTML(): string|TrustedHTML { return window.trustedTypes ? window.trustedTypes.emptyHTML : ''; } export class CustomElement extends HTMLElement { static get template() { return emptyHTML(); } constructor() { super(); this.attachShadow({mode: 'open'}); const template = document.createElement('template'); template.innerHTML = (this.constructor as typeof CustomElement).template || emptyHTML(); this.shadowRoot!.appendChild(template.content.cloneNode(true)); } $<E extends Element = Element>(query: string): E|null { return this.shadowRoot!.querySelector<E>(query); } $all<E extends Element = Element>(query: string): NodeListOf<E> { return this.shadowRoot!.querySelectorAll<E>(query); } }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/custom_element.ts
TypeScript
unknown
1,079
// 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 Extern for window.domAutomationController which is used in * browsertests. */ /** @constructor */ function DomAutomationController() {} /** @param {*} jsonObj */ DomAutomationController.prototype.send = function(jsonObj) {}; /** @type {DomAutomationController} */ window.domAutomationController;
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/dom_automation_controller.js
JavaScript
unknown
466
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview DragWrapper * A class for simplifying HTML5 drag and drop. Classes should use this to * handle the details of nested drag enters and leaves. */ export interface DragWrapperDelegate { // TODO(devlin): The only method this "delegate" actually needs is // shouldAcceptDrag(); the rest can be events emitted by the DragWrapper. /** * @return Whether the drag should be accepted. If false, * subsequent methods (doDrag*) will not be called. */ shouldAcceptDrag(e: MouseEvent): boolean; doDragEnter(e: MouseEvent): void; doDragLeave(e: MouseEvent): void; doDragOver(e: MouseEvent): void; doDrop(e: MouseEvent): void; } /** * Creates a DragWrapper which listens for drag target events on |target| and * delegates event handling to |delegate|. */ export class DragWrapper { /** * The number of un-paired dragenter events that have fired on |this|. * This is incremented by |onDragEnter_| and decremented by * |onDragLeave_|. This is necessary because dragging over child widgets * will fire additional enter and leave events on |this|. A non-zero value * does not necessarily indicate that |isCurrentDragTarget()| is true. */ private dragEnters_: number = 0; private target_: HTMLElement; private delegate_: DragWrapperDelegate; constructor(target: HTMLElement, delegate: DragWrapperDelegate) { this.target_ = target; this.delegate_ = delegate; target.addEventListener('dragenter', e => this.onDragEnter_(e)); target.addEventListener('dragover', e => this.onDragOver_(e)); target.addEventListener('drop', e => this.onDrop_(e)); target.addEventListener('dragleave', e => this.onDragLeave_(e)); } /** * Whether the tile page is currently being dragged over with data it can * accept. */ get isCurrentDragTarget(): boolean { return this.target_.classList.contains('drag-target'); } /** * Delegate for dragenter events fired on |target_|. */ private onDragEnter_(e: MouseEvent) { if (++this.dragEnters_ === 1) { if (this.delegate_.shouldAcceptDrag(e)) { this.target_.classList.add('drag-target'); this.delegate_.doDragEnter(e); } } else { // Sometimes we'll get an enter event over a child element without an // over event following it. In this case we have to still call the // drag over delegate so that we make the necessary updates (one visible // symptom of not doing this is that the cursor's drag state will // flicker during drags). this.onDragOver_(e); } } /** * Thunk for dragover events fired on |target_|. */ private onDragOver_(e: MouseEvent) { if (!this.target_.classList.contains('drag-target')) { return; } this.delegate_.doDragOver(e); } /** * Thunk for drop events fired on |target_|. */ private onDrop_(e: MouseEvent) { this.dragEnters_ = 0; if (!this.target_.classList.contains('drag-target')) { return; } this.target_.classList.remove('drag-target'); this.delegate_.doDrop(e); } /** * Thunk for dragleave events fired on |target_|. */ private onDragLeave_(e: MouseEvent) { if (--this.dragEnters_ > 0) { return; } this.target_.classList.remove('drag-target'); this.delegate_.doDragLeave(e); } }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/drag_wrapper.ts
TypeScript
unknown
3,479
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview EventTracker is a simple class that manages the addition and * removal of DOM event listeners. In particular, it keeps track of all * listeners that have been added and makes it easy to remove some or all of * them without requiring all the information again. This is particularly handy * when the listener is a generated function such as a lambda or the result of * calling Function.bind. */ export class EventTracker { private listeners_: EventTrackerEntry[] = []; /** * Add an event listener - replacement for EventTarget.addEventListener. * @param target The DOM target to add a listener to. * @param eventType The type of event to subscribe to. * @param listener The listener to add. * @param capture Whether to invoke during the capture phase. Defaults to * false. */ add(target: EventTarget, eventType: string, listener: EventListener|((p: any) => void), capture: boolean = false) { const h = { target: target, eventType: eventType, listener: listener, capture: capture, }; this.listeners_.push(h); target.addEventListener(eventType, listener, capture); } /** * Remove any specified event listeners added with this EventTracker. * @param target The DOM target to remove a listener from. * @param eventType The type of event to remove. */ remove(target: EventTarget, eventType?: string) { this.listeners_ = this.listeners_.filter(listener => { if (listener.target === target && (!eventType || (listener.eventType === eventType))) { EventTracker.removeEventListener(listener); return false; } return true; }); } /** Remove all event listeners added with this EventTracker. */ removeAll() { this.listeners_.forEach( listener => EventTracker.removeEventListener(listener)); this.listeners_ = []; } /** * Remove a single event listener given it's tracking entry. It's up to the * caller to ensure the entry is removed from listeners_. * @param entry The entry describing the listener to * remove. */ static removeEventListener(entry: EventTrackerEntry) { entry.target.removeEventListener( entry.eventType, entry.listener, entry.capture); } } // The type of the internal tracking entry. interface EventTrackerEntry { target: EventTarget; eventType: string; listener: EventListener|(() => void); capture: boolean; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/event_tracker.ts
TypeScript
unknown
2,605
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // clang-format off import {assert} from './assert_ts.js'; import {FocusRow, FocusRowDelegate} from './focus_row.js'; // clang-format on /** * A class to manage grid of focusable elements in a 2D grid. For example, * given this grid: * * focusable [focused] focusable (row: 0, col: 1) * focusable focusable focusable * focusable focusable focusable * * Pressing the down arrow would result in the focus moving down 1 row and * keeping the same column: * * focusable focusable focusable * focusable [focused] focusable (row: 1, col: 1) * focusable focusable focusable * * And pressing right or tab at this point would move the focus to: * * focusable focusable focusable * focusable focusable [focused] (row: 1, col: 2) * focusable focusable focusable */ export class FocusGrid implements FocusRowDelegate { rows: FocusRow[] = []; private ignoreFocusChange_: boolean = false; private lastFocused_: EventTarget|null = null; onFocus(row: FocusRow, e: Event) { if (this.ignoreFocusChange_) { this.ignoreFocusChange_ = false; } else { this.lastFocused_ = e.currentTarget; } this.rows.forEach(function(r) { r.makeActive(r === row); }); } onKeydown(row: FocusRow, e: KeyboardEvent) { const rowIndex = this.rows.indexOf(row); assert(rowIndex >= 0); let newRow = -1; if (e.key === 'ArrowUp') { newRow = rowIndex - 1; } else if (e.key === 'ArrowDown') { newRow = rowIndex + 1; } else if (e.key === 'PageUp') { newRow = 0; } else if (e.key === 'PageDown') { newRow = this.rows.length - 1; } const rowToFocus = this.rows[newRow]; if (rowToFocus) { this.ignoreFocusChange_ = true; rowToFocus.getEquivalentElement(this.lastFocused_ as HTMLElement).focus(); e.preventDefault(); return true; } return false; } getCustomEquivalent(_sampleElement: HTMLElement) { return null; } /** * Unregisters event handlers and removes all |this.rows|. */ destroy() { this.rows.forEach(function(row) { row.destroy(); }); this.rows.length = 0; } /** * @param target A target item to find in this grid. * @return The row index. -1 if not found. */ getRowIndexForTarget(target: HTMLElement): number { for (let i = 0; i < this.rows.length; ++i) { if (this.rows[i]!.getElements().indexOf(target) >= 0) { return i; } } return -1; } /** * @param root An element to search for. * @return The row with root of |root| or null. */ getRowForRoot(root: HTMLElement): FocusRow|null { for (let i = 0; i < this.rows.length; ++i) { if (this.rows[i]!.root === root) { return this.rows[i]!; } } return null; } /** * Adds |row| to the end of this list. * @param row The row that needs to be added to this grid. */ addRow(row: FocusRow) { this.addRowBefore(row, null); } /** * Adds |row| before |nextRow|. If |nextRow| is not in the list or it's * null, |row| is added to the end. * @param row The row that needs to be added to this grid. * @param nextRow The row that should follow |row|. */ addRowBefore(row: FocusRow, nextRow: FocusRow|null) { row.delegate = row.delegate || this; const nextRowIndex = nextRow ? this.rows.indexOf(nextRow) : -1; if (nextRowIndex === -1) { this.rows.push(row); } else { this.rows.splice(nextRowIndex, 0, row); } } /** * Removes a row from the focus row. No-op if row is not in the grid. * @param row The row that needs to be removed. */ removeRow(row: FocusRow|null) { const nextRowIndex = row ? this.rows.indexOf(row) : -1; if (nextRowIndex > -1) { this.rows.splice(nextRowIndex, 1); } } /** * Makes sure that at least one row is active. Should be called once, after * adding all rows to FocusGrid. * @param preferredRow The row to select if no other row is * active. Selects the first item if this is beyond the range of the * grid. */ ensureRowActive(preferredRow?: number) { if (this.rows.length === 0) { return; } for (let i = 0; i < this.rows.length; ++i) { if (this.rows[i]!.isActive()) { return; } } (this.rows[preferredRow || 0] || this.rows[0]!).makeActive(true); } }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/focus_grid.ts
TypeScript
unknown
4,546
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * The class name to set on the document element. */ const CLASS_NAME = 'focus-outline-visible'; const docsToManager: Map<Document, FocusOutlineManager> = new Map(); /** * This class sets a CSS class name on the HTML element of |doc| when the user * presses a key. It removes the class name when the user clicks anywhere. * * This allows you to write CSS like this: * * html.focus-outline-visible my-element:focus { * outline: 5px auto -webkit-focus-ring-color; * } * * And the outline will only be shown if the user uses the keyboard to get to * it. * */ export class FocusOutlineManager { // Whether focus change is triggered by a keyboard event. private focusByKeyboard_: boolean = true; private classList_: DOMTokenList; /** * @param doc The document to attach the focus outline manager to. */ constructor(doc: Document) { this.classList_ = doc.documentElement.classList; doc.addEventListener('keydown', () => this.onEvent_(true), true); doc.addEventListener('mousedown', () => this.onEvent_(false), true); this.updateVisibility(); } private onEvent_(focusByKeyboard: boolean) { if (this.focusByKeyboard_ === focusByKeyboard) { return; } this.focusByKeyboard_ = focusByKeyboard; this.updateVisibility(); } updateVisibility() { this.visible = this.focusByKeyboard_; } /** * Whether the focus outline should be visible. */ set visible(visible: boolean) { this.classList_.toggle(CLASS_NAME, visible); } get visible(): boolean { return this.classList_.contains(CLASS_NAME); } /** * Gets a per document singleton focus outline manager. * @param doc The document to get the |FocusOutlineManager| for. * @return The per document singleton focus outline manager. */ static forDocument(doc: Document): FocusOutlineManager { let manager = docsToManager.get(doc); if (!manager) { manager = new FocusOutlineManager(doc); docsToManager.set(doc, manager); } return manager; } }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/focus_outline_manager.ts
TypeScript
unknown
2,180
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // clang-format off import {assert, assertInstanceof} from './assert_ts.js'; import {EventTracker} from './event_tracker.js'; import {hasKeyModifiers, isRTL} from './util_ts.js'; // clang-format on const ACTIVE_CLASS: string = 'focus-row-active'; /** * A class to manage focus between given horizontally arranged elements. * * Pressing left cycles backward and pressing right cycles forward in item * order. Pressing Home goes to the beginning of the list and End goes to the * end of the list. * * If an item in this row is focused, it'll stay active (accessible via tab). * If no items in this row are focused, the row can stay active until focus * changes to a node inside |this.boundary_|. If |boundary| isn't specified, * any focus change deactivates the row. */ export class FocusRow { root: HTMLElement; delegate: FocusRowDelegate|undefined; protected eventTracker: EventTracker = new EventTracker(); private boundary_: Element; /** * @param root The root of this focus row. Focus classes are * applied to |root| and all added elements must live within |root|. * @param boundary Focus events are ignored outside of this element. * @param delegate An optional event delegate. */ constructor(root: HTMLElement, boundary: Element|null, delegate?: FocusRowDelegate) { this.root = root; this.boundary_ = boundary || document.documentElement; this.delegate = delegate; } /** * Whether it's possible that |element| can be focused. */ static isFocusable(element: Element): boolean { if (!element || (element as Element & {disabled?: boolean}).disabled) { return false; } // We don't check that element.tabIndex >= 0 here because inactive rows // set a tabIndex of -1. let current = element; while (true) { assertInstanceof(current, Element); const style = window.getComputedStyle(current); if (style.visibility === 'hidden' || style.display === 'none') { return false; } const parent = current.parentNode; if (!parent) { return false; } if (parent === current.ownerDocument || parent instanceof DocumentFragment) { return true; } current = parent as Element; } } /** * A focus override is a function that returns an element that should gain * focus. The element may not be directly selectable for example the element * that can gain focus is in a shadow DOM. Allowing an override via a * function leaves the details of how the element is retrieved to the * component. */ static getFocusableElement(element: HTMLElement): HTMLElement { const withFocusable = element as HTMLElement & { getFocusableElement?: () => HTMLElement}; if (withFocusable.getFocusableElement) { return withFocusable.getFocusableElement(); } return element; } /** * Register a new type of focusable element (or add to an existing one). * * Example: an (X) button might be 'delete' or 'close'. * * When FocusRow is used within a FocusGrid, these types are used to * determine equivalent controls when Up/Down are pressed to change rows. * * Another example: mutually exclusive controls that hide each other on * activation (i.e. Play/Pause) could use the same type (i.e. 'play-pause') * to indicate they're equivalent. * * @param type The type of element to track focus of. * @param selectorOrElement The selector of the element * from this row's root, or the element itself. * @return Whether a new item was added. */ addItem(type: string, selectorOrElement: string|HTMLElement): boolean { assert(type); let element; if (typeof selectorOrElement === 'string') { element = this.root.querySelector<HTMLElement>(selectorOrElement); } else { element = selectorOrElement; } if (!element) { return false; } element.setAttribute('focus-type', type); element.tabIndex = this.isActive() ? 0 : -1; this.eventTracker.add(element, 'blur', this.onBlur_.bind(this)); this.eventTracker.add(element, 'focus', this.onFocus_.bind(this)); this.eventTracker.add(element, 'keydown', this.onKeydown_.bind(this)); this.eventTracker.add(element, 'mousedown', this.onMousedown_.bind(this)); return true; } /** Dereferences nodes and removes event handlers. */ destroy() { this.eventTracker.removeAll(); } /** * @param sampleElement An element for to find an equivalent * for. * @return An equivalent element to focus for * |sampleElement|. */ protected getCustomEquivalent(_sampleElement: HTMLElement): HTMLElement { const focusable = this.getFirstFocusable(); assert(focusable); return focusable; } /** * @return All registered elements (regardless of focusability). */ getElements(): HTMLElement[] { return Array.from(this.root.querySelectorAll<HTMLElement>('[focus-type]')) .map(FocusRow.getFocusableElement); } /** * Find the element that best matches |sampleElement|. * @param sampleElement An element from a row of the same * type which previously held focus. * @return The element that best matches sampleElement. */ getEquivalentElement(sampleElement: HTMLElement): HTMLElement { if (this.getFocusableElements().indexOf(sampleElement) >= 0) { return sampleElement; } const sampleFocusType = this.getTypeForElement(sampleElement); if (sampleFocusType) { const sameType = this.getFirstFocusable(sampleFocusType); if (sameType) { return sameType; } } return this.getCustomEquivalent(sampleElement); } /** * @param type An optional type to search for. * @return The first focusable element with |type|. */ getFirstFocusable(type?: string): HTMLElement|null { const element = this.getFocusableElements().find( el => !type || el.getAttribute('focus-type') === type); return element || null; } /** @return Registered, focusable elements. */ getFocusableElements(): HTMLElement[] { return this.getElements().filter(FocusRow.isFocusable); } /** * @param element An element to determine a focus type for. * @return The focus type for |element| or '' if none. */ getTypeForElement(element: Element): string { return element.getAttribute('focus-type') || ''; } /** @return Whether this row is currently active. */ isActive(): boolean { return this.root.classList.contains(ACTIVE_CLASS); } /** * Enables/disables the tabIndex of the focusable elements in the FocusRow. * tabIndex can be set properly. * @param active True if tab is allowed for this row. */ makeActive(active: boolean) { if (active === this.isActive()) { return; } this.getElements().forEach(function(element) { element.tabIndex = active ? 0 : -1; }); this.root.classList.toggle(ACTIVE_CLASS, active); } private onBlur_(e: FocusEvent) { if (!this.boundary_.contains(e.relatedTarget as Element)) { return; } const currentTarget = e.currentTarget as HTMLElement; if (this.getFocusableElements().indexOf(currentTarget) >= 0) { this.makeActive(false); } } private onFocus_(e: Event) { if (this.delegate) { this.delegate.onFocus(this, e); } } private onMousedown_(e: MouseEvent) { // Only accept left mouse clicks. if (e.button) { return; } // Allow the element under the mouse cursor to be focusable. const target = e.currentTarget as HTMLElement & {disabled?: boolean}; if (!target.disabled) { target.tabIndex = 0; } } private onKeydown_(e: KeyboardEvent) { const elements = this.getFocusableElements(); const currentElement = FocusRow.getFocusableElement( e.currentTarget as HTMLElement); const elementIndex = elements.indexOf(currentElement); assert(elementIndex >= 0); if (this.delegate && this.delegate.onKeydown(this, e)) { return; } const isShiftTab = !e.altKey && !e.ctrlKey && !e.metaKey && e.shiftKey && e.key === 'Tab'; if (hasKeyModifiers(e) && !isShiftTab) { return; } let index = -1; let shouldStopPropagation = true; if (isShiftTab) { // This always moves back one element, even in RTL. index = elementIndex - 1; if (index < 0) { // Bubble up to focus on the previous element outside the row. return; } } else if (e.key === 'ArrowLeft') { index = elementIndex + (isRTL() ? 1 : -1); } else if (e.key === 'ArrowRight') { index = elementIndex + (isRTL() ? -1 : 1); } else if (e.key === 'Home') { index = 0; } else if (e.key === 'End') { index = elements.length - 1; } else { shouldStopPropagation = false; } const elementToFocus = elements[index]; if (elementToFocus) { this.getEquivalentElement(elementToFocus).focus(); e.preventDefault(); } if (shouldStopPropagation) { e.stopPropagation(); } } } export interface FocusRowDelegate { /** * Called when a key is pressed while on a FocusRow's item. If true is * returned, further processing is skipped. * @param row The row that detected a keydown. * @return Whether the event was handled. */ onKeydown(row: FocusRow, e: KeyboardEvent): boolean; onFocus(row: FocusRow, e: Event): void; /** * @param sampleElement An element to find an equivalent for. * @return An equivalent element to focus, or null to use the * default FocusRow element. */ getCustomEquivalent(sampleElement: HTMLElement): HTMLElement|null; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/focus_row.ts
TypeScript
unknown
9,884
// 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. // clang-format off import {assert} from './assert_ts.js'; import {isIOS} from './platform.js'; // clang-format on let hideInk = false; assert(!isIOS, 'pointerdown doesn\'t work on iOS'); document.addEventListener('pointerdown', function() { hideInk = true; }, true); document.addEventListener('keydown', function() { hideInk = false; }, true); /** * Attempts to track whether focus outlines should be shown, and if they * shouldn't, removes the "ink" (ripple) from a control while focusing it. * This is helpful when a user is clicking/touching, because it's not super * helpful to show focus ripples in that case. This is Polymer-specific. */ export function focusWithoutInk(toFocus: HTMLElement) { // |toFocus| does not have a 'noink' property, so it's unclear whether the // element has "ink" and/or whether it can be suppressed. Just focus(). if (!('noink' in toFocus) || !hideInk) { toFocus.focus(); return; } const toFocusWithNoInk = toFocus as HTMLElement & {noink: boolean}; // Make sure the element is in the document we're listening to events on. assert(document === toFocusWithNoInk.ownerDocument); const {noink} = toFocusWithNoInk; toFocusWithNoInk.noink = true; toFocusWithNoInk.focus(); toFocusWithNoInk.noink = noink; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/focus_without_ink.ts
TypeScript
unknown
1,428
// 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 {isAndroid, isIOS} from './platform.js'; /** * @return The scale factors supported by this platform for webui resources. */ function getSupportedScaleFactors(): number[] { const supportedScaleFactors = []; if (!isIOS) { // This matches the code in ResourceBundle::InitSharedInstance() that // supports SCALE_FACTOR_100P on all non-iOS platforms. supportedScaleFactors.push(1); } if (!isIOS && !isAndroid) { // All desktop platforms support zooming which also updates the renderer's // device scale factors (a.k.a devicePixelRatio), and these platforms have // high DPI assets for 2x. Let the renderer pick the closest image for // the current device scale factor. supportedScaleFactors.push(2); } else { // For other platforms that use fixed device scale factor, use // the window's device pixel ratio. // TODO(oshima): Investigate corresponding to // ResourceBundle::InitSharedInstance() more closely. supportedScaleFactors.push(window.devicePixelRatio); } return supportedScaleFactors; } /** * Generates a CSS url string. * @param s The URL to generate the CSS url for. * @return The CSS url string. */ export function getUrlForCss(s: string): string { // http://www.w3.org/TR/css3-values/#uris // Parentheses, commas, whitespace characters, single quotes (') and double // quotes (") appearing in a URI must be escaped with a backslash const s2 = s.replace(/(\(|\)|\,|\s|\'|\"|\\)/g, '\\$1'); return `url("${s2}")`; } /** * A URL for the filetype icon for |filePath|. OS and theme dependent. */ export function getFileIconUrl(filePath: string): string { const url = new URL('chrome://fileicon/'); url.searchParams.set('path', filePath); url.searchParams.set('scale', window.devicePixelRatio + 'x'); return url.toString(); } /** * Generates a CSS image-set for a chrome:// url. * An entry in the image set is added for each of getSupportedScaleFactors(). * The scale-factor-specific url is generated by replacing the first instance * of 'scalefactor' in |path| with the numeric scale factor. * * @param path The URL to generate an image set for. * 'scalefactor' should be a substring of |path|. * @return The CSS image-set. */ function getImageSet(path: string): string { const supportedScaleFactors = getSupportedScaleFactors(); const replaceStartIndex = path.indexOf('SCALEFACTOR'); if (replaceStartIndex < 0) { return getUrlForCss(path); } let s = ''; for (let i = 0; i < supportedScaleFactors.length; ++i) { const scaleFactor = supportedScaleFactors[i]; const pathWithScaleFactor = path.substr(0, replaceStartIndex) + scaleFactor + path.substr(replaceStartIndex + 'scalefactor'.length); s += getUrlForCss(pathWithScaleFactor) + ' ' + scaleFactor + 'x'; if (i !== supportedScaleFactors.length - 1) { s += ', '; } } return 'image-set(' + s + ')'; } /** * Returns the URL of the image, or an image set of URLs for the provided * path. Resources in chrome://theme have multiple supported scale factors. * * @param path The path of the image. * @return The url, or an image set of URLs. */ export function getImage(path: string): string { const chromeThemePath = 'chrome://theme'; const isChromeThemeUrl = (path.slice(0, chromeThemePath.length) === chromeThemePath); return isChromeThemeUrl ? getImageSet(path + '@SCALEFACTORx') : getUrlForCss(path); } function getBaseFaviconUrl(): URL { const faviconUrl = new URL('chrome://favicon2/'); faviconUrl.searchParams.set('size', '16'); faviconUrl.searchParams.set('scaleFactor', 'SCALEFACTORx'); return faviconUrl; } /** * Creates a CSS image-set for a favicon. * * @param url URL of the favicon * @return image-set for the favicon */ export function getFavicon(url: string): string { const faviconUrl = getBaseFaviconUrl(); faviconUrl.searchParams.set('iconUrl', url); return getImageSet(faviconUrl.toString()); } /** * Creates a CSS image-set for a favicon request based on a page URL. * * @param url URL of the original page * @param isSyncedUrlForHistoryUi Should be set to true only if the * caller is an UI aimed at displaying user history, and the requested url * is known to be present in Chrome sync data. * @param remoteIconUrlForUma In case the entry is contained in sync * data, we can pass the associated icon url. * @param size The favicon size. * @param forceLightMode Flag to force the service to show the light * mode version of the default favicon. * * @return image-set for the favicon. */ export function getFaviconForPageURL( url: string, isSyncedUrlForHistoryUi: boolean, remoteIconUrlForUma: string = '', size: number = 16, forceLightMode: boolean = false): string { // Note: URL param keys used below must match those in the description of // chrome://favicon2 format in components/favicon_base/favicon_url_parser.h. const faviconUrl = getBaseFaviconUrl(); faviconUrl.searchParams.set('size', size.toString()); faviconUrl.searchParams.set('pageUrl', url); // TODO(dbeam): use the presence of 'allowGoogleServerFallback' to // indicate true, otherwise false. const fallback = isSyncedUrlForHistoryUi ? '1' : '0'; faviconUrl.searchParams.set('allowGoogleServerFallback', fallback); if (isSyncedUrlForHistoryUi) { faviconUrl.searchParams.set('iconUrl', remoteIconUrlForUma); } if (forceLightMode) { faviconUrl.searchParams.set('forceLightMode', 'true'); } return getImageSet(faviconUrl.toString()); }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/icon.ts
TypeScript
unknown
5,737
// 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. // Note: The API should stay in sync with the IDL definitions in // third_party/WebKit/Source/core/mojo // eslint-disable-next-line no-var var Mojo = Mojo || {}; /** * MojoResult {number}: Result codes for Mojo operations. */ Mojo.RESULT_OK = 0; Mojo.RESULT_CANCELLED = 1; Mojo.RESULT_UNKNOWN = 2; Mojo.RESULT_INVALID_ARGUMENT = 3; Mojo.RESULT_DEADLINE_EXCEEDED = 4; Mojo.RESULT_NOT_FOUND = 5; Mojo.RESULT_ALREADY_EXISTS = 6; Mojo.RESULT_PERMISSION_DENIED = 7; Mojo.RESULT_RESOURCE_EXHAUSTED = 8; Mojo.RESULT_FAILED_PRECONDITION = 9; Mojo.RESULT_ABORTED = 10; Mojo.RESULT_OUT_OF_RANGE = 11; Mojo.RESULT_UNIMPLEMENTED = 12; Mojo.RESULT_INTERNAL = 13; Mojo.RESULT_UNAVAILABLE = 14; Mojo.RESULT_DATA_LOSS = 15; Mojo.RESULT_BUSY = 16; Mojo.RESULT_SHOULD_WAIT = 17; /** * Creates a message pipe. * * @return {result: !MojoResult, handle0: !MojoHandle=, handle1: !MojoHandle=} * Result code and (on success) the two message pipe handles. */ Mojo.createMessagePipe = function() { const result = Mojo.internal.sendMessage({name: 'Mojo.createMessagePipe', args: {}}); if (result.result === Mojo.RESULT_OK) { result.handle0 = new MojoHandle(result.handle0); result.handle1 = new MojoHandle(result.handle1); } return result; }; /** * Binds to the specified Mojo interface. * @param {string} interfaceName The interface name to connect. * @param {!MojoHandle} requestHandle The interface request handle. */ Mojo.bindInterface = function(interfaceName, requestHandle) { Mojo.internal.sendMessage({ name: 'Mojo.bindInterface', args: { interfaceName: interfaceName, requestHandle: requestHandle.takeNativeHandle_(), }, }); }; class MojoHandle { /* * @param {?number=} nativeHandle An opaque number representing the underlying * Mojo system resource. */ constructor(nativeHandle) { if (nativeHandle === undefined) { nativeHandle = null; } /** * @type {number|null} */ this.nativeHandle_ = nativeHandle; } /** * Takes the native handle value. This is not part of the public API. * @return {?number} */ takeNativeHandle_() { const nativeHandle = this.nativeHandle_; this.nativeHandle_ = null; return nativeHandle; } /** * Closes the handle. */ close() { if (this.nativeHandle_ === null) { return; } const nativeHandle = this.nativeHandle_; this.nativeHandle_ = null; Mojo.internal.sendMessage( {name: 'MojoHandle.close', args: {handle: nativeHandle}}); } /** * Begins watching the handle for |signals| to be satisfied or unsatisfiable. * * @param {readable: boolean=, writable: boolean=, peerClosed: boolean=} * signals The signals to watch. * @param {!function(!MojoResult)} callback Called with a result any time * the watched signals become satisfied or unsatisfiable. * * @return {!MojoWatcher} A MojoWatcher instance that could be used to cancel * the watch. */ watch(signals, callback) { const HANDLE_SIGNAL_NONE = 0; const HANDLE_SIGNAL_READABLE = 1; const HANDLE_SIGNAL_WRITABLE = 2; const HANDLE_SIGNAL_PEER_CLOSED = 4; let signalsValue = HANDLE_SIGNAL_NONE; if (signals.readable) { signalsValue |= HANDLE_SIGNAL_READABLE; } if (signals.writable) { signalsValue |= HANDLE_SIGNAL_WRITABLE; } if (signalsValue.peerClosed) { signalsValue |= HANDLE_SIGNAL_PEER_CLOSED; } const watchId = Mojo.internal.sendMessage({ name: 'MojoHandle.watch', args: { handle: this.nativeHandle_, signals: signalsValue, callbackId: Mojo.internal.watchCallbacksHolder.getNextCallbackId(), }, }); Mojo.internal.watchCallbacksHolder.addWatchCallback(watchId, callback); return new MojoWatcher(watchId); } /** * Writes a message to the message pipe. * * @param {!ArrayBufferView} buffer The message data. May be empty. * @param {!Array<!MojoHandle>} handles Any handles to attach. Handles are * transferred and will no longer be valid. May be empty. * @return {!MojoResult} Result code. */ writeMessage(buffer, handles) { let base64EncodedBuffer; if (buffer instanceof Uint8Array) { // calls from mojo_bindings.js base64EncodedBuffer = _Uint8ArrayToBase64(buffer); } else if (buffer instanceof ArrayBuffer) { // calls from mojo/public/js/bindings.js base64EncodedBuffer = _arrayBufferToBase64(buffer); } const nativeHandles = handles.map(function(handle) { return handle.takeNativeHandle_(); }); return Mojo.internal.sendMessage({ name: 'MojoHandle.writeMessage', args: { handle: this.nativeHandle_, buffer: base64EncodedBuffer, handles: nativeHandles, }, }); } /** * Reads a message from the message pipe. * * @return {result: !MojoResult, * buffer: !ArrayBufferView=, * handles: !Array<!MojoHandle>=} * Result code and (on success) the data and handles received. */ readMessage() { const result = Mojo.internal.sendMessage( {name: 'MojoHandle.readMessage', args: {handle: this.nativeHandle_}}); if (result.result === Mojo.RESULT_OK) { result.buffer = new Uint8Array(result.buffer).buffer; result.handles = result.handles.map(function(handle) { return new MojoHandle(handle); }); } return result; } } /** * MojoWatcher identifies a watch on a MojoHandle and can be used to cancel the * watch. */ class MojoWatcher { /** @param {number} An opaque id representing the watch. */ constructor(watchId) { this.watchId_ = watchId; } /* * Cancels a handle watch. */ cancel() { Mojo.internal.sendMessage( {name: 'MojoWatcher.cancel', args: {watchId: this.watchId_}}); Mojo.internal.watchCallbacksHolder.removeWatchCallback(this.watchId_); } } // ----------------------------------------------------------------------------- // Mojo API implementation details. It is not part of the public API. Mojo.internal = Mojo.internal || {}; /** * Synchronously sends a message to Mojo backend. * @param {!Object} message The message to send. * @return {Object=} Response from Mojo backend. */ Mojo.internal.sendMessage = function(message) { const response = window.prompt(__gCrWeb.common.JSONStringify(message)); return response ? JSON.parse(response) : undefined; }; /** * Holds callbacks for all currently active watches. */ Mojo.internal.watchCallbacksHolder = (function() { /** * Next callback id to be used for watch. * @type{number} */ let nextCallbackId = 0; /** * Map where keys are callbacks ids and values are callbacks. * @type {!Map<number, !function(!MojoResult)>} */ const callbacks = new Map(); /** * Map where keys are watch ids and values are callback ids. * @type {!Map<number, number>} */ const callbackIds = new Map(); /** * Calls watch callback. * * @param {number} callbackId Callback id previously returned from {@code getNextCallbackId}. * @param {!MojoResult} mojoResult The result code to call the callback with. */ const callCallback = function(callbackId, mojoResult) { const callback = callbacks.get(callbackId); // Signalling the watch is asynchronous operation and this function may be // called for already removed watch. if (callback) { callback(mojoResult); } }; /** * Returns next callback id to be used for watch (idempotent). * * @return {number} callback id. */ const getNextCallbackId = function() { return nextCallbackId; }; /** * Adds callback which must be executed when the watch fires. * * @param {number} watchId The value returned from "MojoHandle.watch" Mojo * backend. * @param {!function(!MojoResult)} callback The callback which should be * executed when the watch fires. */ const addWatchCallback = function(watchId, callback) { callbackIds.set(watchId, nextCallbackId); callbacks.set(nextCallbackId, callback); ++nextCallbackId; }; /** * Removes callback which should no longer be executed. * * @param {!number} watchId The id to remove callback for. */ const removeWatchCallback = function(watchId) { callbacks.delete(callbackIds.get(watchId)); callbackIds.delete(watchId); }; return { callCallback: callCallback, getNextCallbackId: getNextCallbackId, addWatchCallback: addWatchCallback, removeWatchCallback: removeWatchCallback, }; })(); /** * Base64-encode an ArrayBuffer * @param {ArrayBuffer} buffer * @return {String} */ function _arrayBufferToBase64(buffer) { return _Uint8ArrayToBase64(new Uint8Array(buffer)); } /** * Base64-encode an Uint8Array * @param {Uint8Array} buffer * @return {String} */ function _Uint8ArrayToBase64(bytes) { let binary = ''; const numBytes = bytes.byteLength; for (let i = 0; i < numBytes; i++) { binary += String.fromCharCode(bytes[i]); } return window.btoa(binary); }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/ios/mojo_api.js
JavaScript
unknown
9,256
// 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. window['chrome'] = window['chrome'] || {}; /** * Sends messages to the browser. See * https://chromium.googlesource.com/chromium/src/+/main/docs/webui_explainer.md#chrome_send * * @param {string} message name to be passed to the browser. * @param {Array=} args optional. */ window['chrome']['send'] = function(message, args) { __gCrWeb.common.sendWebKitMessage('WebUIMessage', { 'message': message, 'arguments': args || [], }); };
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/ios/web_ui.js
JavaScript
unknown
594
// 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. /** This is used to identify keyboard shortcuts. */ class KeyboardShortcut { private useKeyCode_: boolean = false; private mods_: {[key: string]: boolean} = {}; private key_: string|null = null; private keyCode_: number|null = null; /** * @param shortcut The text used to describe the keys for this * keyboard shortcut. */ constructor(shortcut: string) { shortcut.split('|').forEach((part) => { const partLc = part.toLowerCase(); switch (partLc) { case 'alt': case 'ctrl': case 'meta': case 'shift': this.mods_[partLc + 'Key'] = true; break; default: if (this.key_) { throw Error('Invalid shortcut'); } this.key_ = part; // For single key alpha shortcuts use event.keyCode rather than // event.key to match how chrome handles shortcuts and allow // non-english language input to work. if (part.match(/^[a-z]$/)) { this.useKeyCode_ = true; this.keyCode_ = part.toUpperCase().charCodeAt(0); } } }); } /** * Whether the keyboard shortcut object matches a keyboard event. * @param e The keyboard event object. * @return Whether we found a match or not. */ matchesEvent(e: KeyboardEvent): boolean { if ((this.useKeyCode_ && e.keyCode === this.keyCode_) || e.key === this.key_) { // All keyboard modifiers need to match. const mods = this.mods_; return ['altKey', 'ctrlKey', 'metaKey', 'shiftKey'].every(function(k) { return (e as unknown as {[key: string]: boolean})[k] === !!mods[k]; }); } return false; } } /** A list of keyboard shortcuts which all perform one command. */ export class KeyboardShortcutList { private shortcuts_: KeyboardShortcut[]; /** * @param shortcuts Text-based representation of one or more * keyboard shortcuts, separated by spaces. */ constructor(shortcuts: string) { this.shortcuts_ = shortcuts.split(/\s+/).map(function(shortcut) { return new KeyboardShortcut(shortcut); }); } /** * Returns true if any of the keyboard shortcuts in the list matches a * keyboard event. */ matchesEvent(e: KeyboardEvent): boolean { return this.shortcuts_.some(function(keyboardShortcut) { return keyboardShortcut.matchesEvent(e); }); } }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/keyboard_shortcut_list.ts
TypeScript
unknown
2,557