Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(material/button): combine MatButton and MatAnchor #30492

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 47 additions & 65 deletions src/material/button/button-base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ import {
booleanAttribute,
Directive,
ElementRef,
HostAttributeToken,
inject,
InjectionToken,
Input,
NgZone,
numberAttribute,
OnDestroy,
OnInit,
Renderer2,
} from '@angular/core';
import {_StructuralStylesLoader, MatRippleLoader, ThemePalette} from '@angular/material/core';
Expand Down Expand Up @@ -52,6 +52,7 @@ export const MAT_BUTTON_HOST = {
// wants to target all Material buttons.
'[class.mat-mdc-button-base]': 'true',
'[class]': 'color ? "mat-" + color : ""',
'[attr.tabindex]': '_getTabIndex()',
};

/** List of classes to add to buttons instances based on host attribute selector. */
Expand Down Expand Up @@ -94,13 +95,17 @@ export class MatButtonBase implements AfterViewInit, OnDestroy {
_animationMode = inject(ANIMATION_MODULE_TYPE, {optional: true});

private readonly _focusMonitor = inject(FocusMonitor);
private _cleanupClick: (() => void) | undefined;

/**
* Handles the lazy creation of the MatButton ripple.
* Used to improve initial load time of large applications.
*/
protected _rippleLoader: MatRippleLoader = inject(MatRippleLoader);

/** Whether the button is set on an anchor node. */
protected _isAnchor: boolean;

/** Whether this button is a FAB. Used to apply the correct class on the ripple. */
protected _isFab = false;

Expand Down Expand Up @@ -153,18 +158,28 @@ export class MatButtonBase implements AfterViewInit, OnDestroy {
@Input({transform: booleanAttribute})
disabledInteractive: boolean;

@Input({
transform: (value: unknown) => (value == null ? undefined : numberAttribute(value)),
})
tabIndex: number;

constructor(...args: unknown[]);

constructor() {
inject(_CdkPrivateStyleLoader).load(_StructuralStylesLoader);
const config = inject(MAT_BUTTON_CONFIG, {optional: true});
const element = this._elementRef.nativeElement;
const element: HTMLElement = this._elementRef.nativeElement;
const classList = (element as HTMLElement).classList;

this._isAnchor = element.tagName === 'A';
this.disabledInteractive = config?.disabledInteractive ?? false;
this.color = config?.color ?? null;
this._rippleLoader?.configureRipple(element, {className: 'mat-mdc-button-ripple'});

if (this._isAnchor) {
this._setupAsAnchor();
}

// For each of the variant selectors that is present in the button's host
// attributes, add the correct corresponding MDC classes.
for (const {attribute, mdcClasses} of HOST_SELECTOR_MDC_CLASS_PAIR) {
Expand All @@ -179,6 +194,7 @@ export class MatButtonBase implements AfterViewInit, OnDestroy {
}

ngOnDestroy() {
this._cleanupClick?.();
this._focusMonitor.stopMonitoring(this._elementRef);
this._rippleLoader?.destroyRipple(this._elementRef.nativeElement);
}
Expand All @@ -193,10 +209,9 @@ export class MatButtonBase implements AfterViewInit, OnDestroy {
}

protected _getAriaDisabled() {
if (this.ariaDisabled != null) {
return this.ariaDisabled;
if (this._isAnchor) {
return this.ariaDisabled != null ? this.ariaDisabled : this.disabled || null;
}

return this.disabled && this.disabledInteractive ? true : null;
}

Expand All @@ -210,74 +225,41 @@ export class MatButtonBase implements AfterViewInit, OnDestroy {
this.disableRipple || this.disabled,
);
}
}

/** Shared host configuration for buttons using the `<a>` tag. */
export const MAT_ANCHOR_HOST = {
// Note that this is basically a noop on anchors,
// but it appears that some internal apps depend on it.
'[attr.disabled]': '_getDisabledAttribute()',
'[class.mat-mdc-button-disabled]': 'disabled',
'[class.mat-mdc-button-disabled-interactive]': 'disabledInteractive',
'[class._mat-animation-noopable]': '_animationMode === "NoopAnimations"',

// Note that we ignore the user-specified tabindex when it's disabled for
// consistency with the `mat-button` applied on native buttons where even
// though they have an index, they're not tabbable.
'[attr.tabindex]': 'disabled && !disabledInteractive ? -1 : tabIndex',
'[attr.aria-disabled]': '_getAriaDisabled()',
// MDC automatically applies the primary theme color to the button, but we want to support
// an unthemed version. If color is undefined, apply a CSS class that makes it easy to
// select and style this "theme".
'[class.mat-unthemed]': '!color',
// Add a class that applies to all buttons. This makes it easier to target if somebody
// wants to target all Material buttons.
'[class.mat-mdc-button-base]': 'true',
'[class]': 'color ? "mat-" + color : ""',
};
protected _getTabIndex() {
if (this._isAnchor) {
return this.disabled && !this.disabledInteractive ? -1 : this.tabIndex;
}
return this.tabIndex;
}

/**
* Anchor button base.
*/
@Directive()
export class MatAnchorBase extends MatButtonBase implements OnInit, OnDestroy {
private _renderer = inject(Renderer2);
private _cleanupClick: () => void;
private _setupAsAnchor() {
const renderer = inject(Renderer2);
const initialTabIndex = inject(new HostAttributeToken('tabindex'), {optional: true});

@Input({
transform: (value: unknown) => {
return value == null ? undefined : numberAttribute(value);
},
})
tabIndex: number;
if (initialTabIndex !== null) {
this.tabIndex = numberAttribute(initialTabIndex, undefined);
}

ngOnInit(): void {
this._ngZone.runOutsideAngular(() => {
this._cleanupClick = this._renderer.listen(
this._cleanupClick = renderer.listen(
this._elementRef.nativeElement,
'click',
this._haltDisabledEvents,
(event: Event) => {
if (this.disabled) {
event.preventDefault();
event.stopImmediatePropagation();
}
},
);
});
}

override ngOnDestroy(): void {
super.ngOnDestroy();
this._cleanupClick?.();
}

_haltDisabledEvents = (event: Event): void => {
// A disabled button shouldn't apply any actions
if (this.disabled) {
event.preventDefault();
event.stopImmediatePropagation();
}
};

protected override _getAriaDisabled() {
if (this.ariaDisabled != null) {
return this.ariaDisabled;
}
return this.disabled || null;
}
}

// tslint:disable:variable-name
/**
* Anchor button base.
*/
export const MatAnchorBase = MatButtonBase;
export type MatAnchorBase = MatButtonBase;
// tslint:enable:variable-name
21 changes: 8 additions & 13 deletions src/material/button/button.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
*/

import {ChangeDetectionStrategy, Component, ViewEncapsulation} from '@angular/core';
import {MAT_ANCHOR_HOST, MAT_BUTTON_HOST, MatAnchorBase, MatButtonBase} from './button-base';
import {MAT_BUTTON_HOST, MatButtonBase} from './button-base';

/**
* Material Design button component. Users interact with a button to perform an action.
Expand All @@ -21,17 +21,19 @@ import {MAT_ANCHOR_HOST, MAT_BUTTON_HOST, MatAnchorBase, MatButtonBase} from './
@Component({
selector: `
button[mat-button], button[mat-raised-button], button[mat-flat-button],
button[mat-stroked-button]
button[mat-stroked-button], a[mat-button], a[mat-raised-button], a[mat-flat-button],
a[mat-stroked-button]
`,
templateUrl: 'button.html',
styleUrls: ['button.css', 'button-high-contrast.css'],
host: MAT_BUTTON_HOST,
exportAs: 'matButton',
exportAs: 'matButton, matAnchor',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MatButton extends MatButtonBase {}

// tslint:disable:variable-name
/**
* Material Design button component for anchor elements. Anchor elements are used to provide
* links for the user to navigate across different routes or pages.
Expand All @@ -42,13 +44,6 @@ export class MatButton extends MatButtonBase {}
* specification. `MatAnchor` additionally captures an additional "flat" appearance, which matches
* "contained" but without elevation.
*/
@Component({
selector: `a[mat-button], a[mat-raised-button], a[mat-flat-button], a[mat-stroked-button]`,
exportAs: 'matButton, matAnchor',
host: MAT_ANCHOR_HOST,
templateUrl: 'button.html',
styleUrls: ['button.css', 'button-high-contrast.css'],
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MatAnchor extends MatAnchorBase {}
export const MatAnchor = MatButton;
export type MatAnchor = MatButton;
// tslint:enable:variable-name
67 changes: 11 additions & 56 deletions src/material/button/fab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@ import {
inject,
} from '@angular/core';

import {MatAnchor} from './button';
import {MAT_ANCHOR_HOST, MAT_BUTTON_HOST, MatButtonBase} from './button-base';
import {MAT_BUTTON_HOST, MatButtonBase} from './button-base';
import {ThemePalette} from '@angular/material/core';

/** Default FAB options that can be overridden. */
Expand Down Expand Up @@ -60,15 +59,15 @@ const defaults = MAT_FAB_DEFAULT_OPTIONS_FACTORY();
* The `MatFabButton` class has two appearances: normal and extended.
*/
@Component({
selector: `button[mat-fab]`,
selector: `button[mat-fab], a[mat-fab]`,
templateUrl: 'button.html',
styleUrl: 'fab.css',
host: {
...MAT_BUTTON_HOST,
'[class.mdc-fab--extended]': 'extended',
'[class.mat-mdc-extended-fab]': 'extended',
},
exportAs: 'matButton',
exportAs: 'matButton, matAnchor',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
Expand All @@ -94,11 +93,11 @@ export class MatFabButton extends MatButtonBase {
* See https://material.io/components/buttons-floating-action-button/
*/
@Component({
selector: `button[mat-mini-fab]`,
selector: `button[mat-mini-fab], a[mat-mini-fab]`,
templateUrl: 'button.html',
styleUrl: 'fab.css',
host: MAT_BUTTON_HOST,
exportAs: 'matButton',
exportAs: 'matButton, matAnchor',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
Expand All @@ -116,66 +115,22 @@ export class MatMiniFabButton extends MatButtonBase {
}
}

// tslint:disable:variable-name
/**
* Material Design floating action button (FAB) component for anchor elements. Anchor elements
* are used to provide links for the user to navigate across different routes or pages.
* See https://material.io/components/buttons-floating-action-button/
*
* The `MatFabAnchor` class has two appearances: normal and extended.
*/
@Component({
selector: `a[mat-fab]`,
templateUrl: 'button.html',
styleUrl: 'fab.css',
host: {
...MAT_ANCHOR_HOST,
'[class.mdc-fab--extended]': 'extended',
'[class.mat-mdc-extended-fab]': 'extended',
},
exportAs: 'matButton, matAnchor',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MatFabAnchor extends MatAnchor {
private _options = inject<MatFabDefaultOptions>(MAT_FAB_DEFAULT_OPTIONS, {optional: true});

override _isFab = true;

@Input({transform: booleanAttribute}) extended: boolean;

constructor(...args: unknown[]);

constructor() {
super();
this._options = this._options || defaults;
this.color = this._options!.color || defaults.color;
}
}
export const MatFabAnchor = MatFabButton;
export type MatFabAnchor = MatFabButton;

/**
* Material Design mini floating action button (FAB) component for anchor elements. Anchor elements
* are used to provide links for the user to navigate across different routes or pages.
* See https://material.io/components/buttons-floating-action-button/
*/
@Component({
selector: `a[mat-mini-fab]`,
templateUrl: 'button.html',
styleUrl: 'fab.css',
host: MAT_ANCHOR_HOST,
exportAs: 'matButton, matAnchor',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MatMiniFabAnchor extends MatAnchor {
private _options = inject<MatFabDefaultOptions>(MAT_FAB_DEFAULT_OPTIONS, {optional: true});

override _isFab = true;

constructor(...args: unknown[]);

constructor() {
super();
this._options = this._options || defaults;
this.color = this._options!.color || defaults.color;
}
}
export const MatMiniFabAnchor = MatMiniFabButton;
export type MatMiniFabAnchor = MatMiniFabButton;
// tslint:enable:variable-name
Loading
Loading