1
0
mirror of https://github.com/bitwarden/browser synced 2025-12-13 06:43:35 +00:00
Files
browser/libs/components/src/chip-select/chip-select.component.ts
Victoria League 3b5b2d6bd6 [CL-265] CL/extension refresh feature branch (#8696)
* [CL-245] Update palette to new light and dark theme colors (#8633)

* [CL-245] Add new color swatches to storybook (#8697)

* [CL-238] update typography (#8997)

* [CL-230] [CL-296] Update button styles (#9345)

* [CL-237] Update menu styles for extension refresh (#9525)

* [CL-267] Add 100-level color variants and update primary-600 (#9550)

* [CL-286] Update badge to use focus-visible instead of focus (#9551)

* [CL-250] Update badge styles for extension refresh (#9572)

* [CL-234] callout style refresh (#9920)

* [CL-233] Update form field styles (#9776)

* [CL-239][CL-251][CL-342] dialog style refresh (#10096)

* [CL-239] simple dialog style refresh

* [CL-342] fix text overflow in dialog; add story

* [CL-244] readonly fields (#10164)

* [CL-352] Fix Angular errors related to form element changes (#10211)

* [CL-273] Update styles for checkbox and form control (#10146)

* [CL-274] Update styling for radio button (#10333)

* [CL-338] Remove extra space in item content when end slot is empty (#10350)

* [CL-377] Fix extension style conflict for input background (#10351)

* [CL-271] Update styles for toggle (#10377)

* [CL-381] Update spacing around form elements (#10432)

* [CL-229] Update icon button styles (#10405)

* [CL-380] Remove hover state from disabled form fields (#10639)

* [CL-405] Allow toggle group input to be full width (#10658)

* [CL-389] Exclude end slot label content from truncation (#10508)

* [CL-383] Remove manual focus when password toggle is clicked (#10749)

* [CL-278][CL-391] misc bit-item style fixes (#10758)

* [CL-391] use pointer cursor on hover when link or button

* [CL-210] Change base font size from 14px to 16px (#10779)

* [CL-291] Finalize styling for chip select (#10771)

* [CL-257] update banner component styles (#10766)

* [CL-443] Fix sizing issues (#10893)

* [CL-445] Fix small sizing and spacing issues (#10962)

* [CL-382] Reduce element shifting on readonly hover (#10956)

* [CL-396] Update theme colors to new hexes (#10968)

* [CL-395] Remove text headers color (#10997)

* [CL-404] Switch to primary-600 for all focus indicators (#11015)

* [CL-397] Remove primary-500 (#11036)

* [CL-447] Ensure DM Sans displays correctly at all font weights (#11041)

* [CL-448] Scrollbar Styles (#11111)

* CL-252/update toast (#10996)

* [CL-275] Update link styles (#11174)

* [CL-446] Update hover state for unselected chip selects (#11172)

* [CL-454] Improve color a11y for toast and banner interactive elements (#11200)

* [CL-457] Center input text for select and multiselect (#11239)

* [CL-455] Do not use responsive margin for sections in dialogs or extension (#11243)

* [CL-459] Fix chip behavior when opening menu while item is selected (#11227)

* [CL-388] Update vertical nav colors for new palette (#11226)

* scope styled scrollbar to only select elements (#11247)

* edit radio buttons to be block inputs and update spacing (#11291)

* [CL-453] Fix multiselect chip spacing and truncation (#11300)

* [PM-11131] Prevent duplicated sr labels on form field icon buttons (#11383)

* [CL-303] Prevent chip menu from running offscreen (#11348)

* [CL-476] Fix DM Sans font on Windows (#11409)

* implements scrollbar styles for firefox/chrome and safari (#11447)

* [CL-472] Fix search background color in extension (#11466)

* [CL-481] Style updates for bit-item, bit-card, and primary-100 (#11473)

* [CL-478] Remove underline on hover for most components (#11477)

* [CL-477] Remove focus styles for readonly input (#11510)

* [CL-487] Fix vault items virtual scroll height (#11581)

* [PM-8625] Increase popup width (#11686)

* [CL-494] Wrap long words in toggle group (#11659)

* [CL-13820] Add class to remove link underline (#11762)

* [CL-435] Prevent Windows extension from shifting (#11851)

* [CL-503] Add notification color variables (#11802)

* [PM-14043] Update size of toggle group label to fit more content (#11881)

* [CL-498] Set chip menu width minimum to chip select width (#11905)

---------

Co-authored-by: Will Martin <contact@willmartian.com>
Co-authored-by: Oscar Hinton <Hinton@users.noreply.github.com>
Co-authored-by: Nick Krantz <125900171+nick-livefront@users.noreply.github.com>
Co-authored-by: Merissa Weinstein <merissa.k.weinstein@gmail.com>
Co-authored-by: Danielle Flinn <43477473+danielleflinn@users.noreply.github.com>
2024-11-15 09:21:17 -05:00

271 lines
8.1 KiB
TypeScript

import {
AfterViewInit,
Component,
DestroyRef,
ElementRef,
HostBinding,
HostListener,
Input,
QueryList,
ViewChild,
ViewChildren,
booleanAttribute,
inject,
signal,
} from "@angular/core";
import { takeUntilDestroyed } from "@angular/core/rxjs-interop";
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms";
import { compareValues } from "../../../common/src/platform/misc/compare-values";
import { ButtonModule } from "../button";
import { IconButtonModule } from "../icon-button";
import { MenuComponent, MenuItemDirective, MenuModule } from "../menu";
import { Option } from "../select/option";
import { SharedModule } from "../shared";
import { TypographyModule } from "../typography";
/** An option that will be showed in the overlay menu of `ChipSelectComponent` */
export type ChipSelectOption<T> = Option<T> & {
/** The options that will be nested under this option */
children?: ChipSelectOption<T>[];
};
@Component({
selector: "bit-chip-select",
templateUrl: "chip-select.component.html",
standalone: true,
imports: [SharedModule, ButtonModule, IconButtonModule, MenuModule, TypographyModule],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: ChipSelectComponent,
multi: true,
},
],
})
export class ChipSelectComponent<T = unknown> implements ControlValueAccessor, AfterViewInit {
@ViewChild(MenuComponent) menu: MenuComponent;
@ViewChildren(MenuItemDirective) menuItems: QueryList<MenuItemDirective>;
@ViewChild("chipSelectButton") chipSelectButton: ElementRef<HTMLButtonElement>;
/** Text to show when there is no selected option */
@Input({ required: true }) placeholderText: string;
/** Icon to show when there is no selected option or the selected option does not have an icon */
@Input() placeholderIcon: string;
private _options: ChipSelectOption<T>[];
/** The select options to render */
@Input({ required: true })
get options(): ChipSelectOption<T>[] {
return this._options;
}
set options(value: ChipSelectOption<T>[]) {
this._options = value;
this.initializeRootTree(value);
}
/** Disables the entire chip */
@Input({ transform: booleanAttribute }) disabled = false;
/** Chip will stretch to full width of its container */
@Input({ transform: booleanAttribute }) fullWidth?: boolean;
/**
* We have `:focus-within` and `:focus-visible` but no `:focus-visible-within`
*/
protected focusVisibleWithin = signal(false);
@HostListener("focusin", ["$event.target"])
onFocusIn(target: HTMLElement) {
this.focusVisibleWithin.set(target.matches(".fvw-target:focus-visible"));
}
@HostListener("focusout")
onFocusOut() {
this.focusVisibleWithin.set(false);
}
@HostBinding("class")
get classList() {
return ["tw-inline-block", this.fullWidth ? "tw-w-full" : "tw-max-w-52"];
}
private destroyRef = inject(DestroyRef);
/** Tree constructed from `this.options` */
private rootTree: ChipSelectOption<T>;
/** Options that are currently displayed in the menu */
protected renderedOptions: ChipSelectOption<T>;
/** The option that is currently selected by the user */
protected selectedOption: ChipSelectOption<T>;
/**
* The initial calculated width of the menu when it opens, which is used to
* keep the width consistent as the user navigates through submenus
*/
protected menuWidth: number | null = null;
/** The label to show in the chip button */
protected get label(): string {
return this.selectedOption?.label || this.placeholderText;
}
/** The icon to show in the chip button */
protected get icon(): string {
return this.selectedOption?.icon || this.placeholderIcon;
}
/**
* Set the rendered options based on whether or not an option is already selected, so that the correct
* submenu displays.
*/
protected setOrResetRenderedOptions(): void {
this.renderedOptions = this.selectedOption
? this.selectedOption.children?.length > 0
? this.selectedOption
: this.getParent(this.selectedOption)
: this.rootTree;
}
protected handleMenuClosed(): void {
this.setOrResetRenderedOptions();
// reset menu width so that it can be recalculated upon open
this.menuWidth = null;
}
protected selectOption(option: ChipSelectOption<T>, _event: MouseEvent) {
this.selectedOption = option;
this.onChange(option);
}
protected viewOption(option: ChipSelectOption<T>, event: MouseEvent) {
this.renderedOptions = option;
/** We don't want the menu to close */
event.preventDefault();
event.stopImmediatePropagation();
}
/** Click handler for the X button */
protected clear() {
this.renderedOptions = this.rootTree;
this.selectedOption = null;
this.onChange(null);
}
/**
* Find a `ChipSelectOption` by its value
* @param tree the root tree to search
* @param value the option value to look for
* @returns the `ChipSelectOption` associated with the provided value, or null if not found
*/
private findOption(tree: ChipSelectOption<T>, value: T): ChipSelectOption<T> | null {
let result = null;
if (tree.value !== null && compareValues(tree.value, value)) {
return tree;
}
if (Array.isArray(tree.children) && tree.children.length > 0) {
tree.children.some((node) => {
result = this.findOption(node, value);
return result;
});
}
return result;
}
/** Maps child options to their parent, to enable navigating up the tree */
private childParentMap = new Map<ChipSelectOption<T>, ChipSelectOption<T>>();
/** For each descendant in the provided `tree`, update `_parent` to be a refrence to the parent node. This allows us to navigate back in the menu. */
private markParents(tree: ChipSelectOption<T>) {
tree.children?.forEach((child) => {
this.childParentMap.set(child, tree);
this.markParents(child);
});
}
protected getParent(option: ChipSelectOption<T>): ChipSelectOption<T> | null {
return this.childParentMap.get(option);
}
private initializeRootTree(options: ChipSelectOption<T>[]) {
/** Since the component is just initialized with an array of options, we need to construct the root tree. */
const root: ChipSelectOption<T> = {
children: options,
value: null,
};
this.markParents(root);
this.rootTree = root;
this.renderedOptions = this.rootTree;
}
ngAfterViewInit() {
/**
* menuItems will change when the user navigates into or out of a submenu. when that happens, we want to
* direct their focus to the first item in the new menu
*/
this.menuItems.changes.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => {
this.menu.keyManager.setFirstItemActive();
});
}
/**
* Calculate the width of the menu based on whichever is larger, the chip select width or the width of
* the initially rendered options
*/
protected setMenuWidth() {
const chipWidth = this.chipSelectButton.nativeElement.getBoundingClientRect().width;
const firstMenuItemWidth =
this.menu.menuItems.first.elementRef.nativeElement.getBoundingClientRect().width;
this.menuWidth = Math.max(chipWidth, firstMenuItemWidth);
}
/** Control Value Accessor */
private notifyOnChange?: (value: T) => void;
private notifyOnTouched?: () => void;
/** Implemented as part of NG_VALUE_ACCESSOR */
writeValue(obj: T): void {
this.selectedOption = this.findOption(this.rootTree, obj);
this.setOrResetRenderedOptions();
}
/** Implemented as part of NG_VALUE_ACCESSOR */
registerOnChange(fn: (value: T) => void): void {
this.notifyOnChange = fn;
}
/** Implemented as part of NG_VALUE_ACCESSOR */
registerOnTouched(fn: any): void {
this.notifyOnTouched = fn;
}
/** Implemented as part of NG_VALUE_ACCESSOR */
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
/** Implemented as part of NG_VALUE_ACCESSOR */
protected onChange(option: Option<T> | null) {
if (!this.notifyOnChange) {
return;
}
this.notifyOnChange(option?.value ?? null);
}
/** Implemented as part of NG_VALUE_ACCESSOR */
protected onBlur() {
if (!this.notifyOnTouched) {
return;
}
this.notifyOnTouched();
}
}