refactor: Use toggleAttribute natively where possible (#2494)

This commit is contained in:
Dermot Duffy
2026-06-30 17:45:13 -07:00
committed by dermotduffy
parent 2acec49b29
commit 48761f0478
13 changed files with 37 additions and 70 deletions
+5 -6
View File
@@ -2,7 +2,6 @@ import { LitElement, ReactiveControllerHost } from 'lit';
import { ActionEventTarget } from '../action-handler-directive'; import { ActionEventTarget } from '../action-handler-directive';
import { isCardInPanel } from '../ha/panel'; import { isCardInPanel } from '../ha/panel';
import { LovelaceCard } from '../ha/types'; import { LovelaceCard } from '../ha/types';
import { setOrRemoveAttribute } from '../utils/basic';
import { isBeingCasted } from '../utils/casting'; import { isBeingCasted } from '../utils/casting';
import { isAncestorInEventPath } from '../utils/event-ancestor'; import { isAncestorInEventPath } from '../utils/event-ancestor';
import { CardMediaReviewEventTarget } from '../utils/review'; import { CardMediaReviewEventTarget } from '../utils/review';
@@ -90,8 +89,8 @@ export class CardElementManager {
]); ]);
// Whether or not the card is in panel mode on the dashboard. // Whether or not the card is in panel mode on the dashboard.
setOrRemoveAttribute(this._element, isCardInPanel(this._element), 'panel'); this._element.toggleAttribute('panel', isCardInPanel(this._element));
setOrRemoveAttribute(this._element, isBeingCasted(), 'casted'); this._element.toggleAttribute('casted', isBeingCasted());
this._api.getFullscreenManager().connect(); this._api.getFullscreenManager().connect();
@@ -165,9 +164,9 @@ export class CardElementManager {
} }
public elementDisconnected(): void { public elementDisconnected(): void {
setOrRemoveAttribute(this._element, false, 'panel'); this._element.toggleAttribute('panel', false);
setOrRemoveAttribute(this._element, false, 'tabindex'); this._element.toggleAttribute('tabindex', false);
setOrRemoveAttribute(this._element, false, 'casted'); this._element.toggleAttribute('casted', false);
// Suspend issue evaluation so state changes below (e.g. clearing // Suspend issue evaluation so state changes below (e.g. clearing
// mediaLoadedInfo) don't arm timers while the card is detached. Issue state // mediaLoadedInfo) don't arm timers while the card is detached. Issue state
+1 -6
View File
@@ -1,4 +1,3 @@
import { setOrRemoveAttribute } from '../utils/basic';
import { CardExpandAPI } from './types'; import { CardExpandAPI } from './types';
export class ExpandManager { export class ExpandManager {
@@ -29,11 +28,7 @@ export class ExpandManager {
this._expanded = expanded; this._expanded = expanded;
this._setConditionState(); this._setConditionState();
setOrRemoveAttribute( this._api.getCardElementManager().getElement().toggleAttribute('expanded', expanded);
this._api.getCardElementManager().getElement(),
expanded,
'expanded',
);
this._api.getCardElementManager().update(); this._api.getCardElementManager().update();
} }
+1 -6
View File
@@ -1,5 +1,4 @@
import { throttle } from 'lodash-es'; import { throttle } from 'lodash-es';
import { setOrRemoveAttribute } from '../utils/basic';
import { Timer } from '../utils/timer'; import { Timer } from '../utils/timer';
import { CardInteractionAPI } from './types'; import { CardInteractionAPI } from './types';
@@ -33,11 +32,7 @@ export class InteractionManager {
private _setInteraction(val: boolean): void { private _setInteraction(val: boolean): void {
this._interacted = val; this._interacted = val;
setOrRemoveAttribute( this._api.getCardElementManager().getElement().toggleAttribute('interaction', val);
this._api.getCardElementManager().getElement(),
val,
'interaction',
);
this._api.getConditionStateManager().setState({ interaction: val }); this._api.getConditionStateManager().setState({ interaction: val });
} }
+4 -5
View File
@@ -81,11 +81,10 @@ export class StyleManager {
private _setDimmable(): void { private _setDimmable(): void {
const config = this._api.getConfigManager().getConfig(); const config = this._api.getConfigManager().getConfig();
setOrRemoveAttribute( this._api
this._api.getCardElementManager().getElement(), .getCardElementManager()
!!config?.view.dim, .getElement()
'dimmable', .toggleAttribute('dimmable', !!config?.view.dim);
);
} }
private _setMinMaxHeight(): void { private _setMinMaxHeight(): void {
@@ -1,7 +1,6 @@
import { LitElement, ReactiveController } from 'lit'; import { LitElement, ReactiveController } from 'lit';
import { isEqual } from 'lodash-es'; import { isEqual } from 'lodash-es';
import { KeyboardShortcut } from '../config/schema/view'; import { KeyboardShortcut } from '../config/schema/view';
import { setOrRemoveAttribute } from '../utils/basic';
export class KeyAssignerController implements ReactiveController { export class KeyAssignerController implements ReactiveController {
private _host: LitElement; private _host: LitElement;
@@ -42,7 +41,7 @@ export class KeyAssignerController implements ReactiveController {
} }
private _setAssigning(assigning: boolean): void { private _setAssigning(assigning: boolean): void {
this._assigning = assigning; this._assigning = assigning;
setOrRemoveAttribute(this._host, this._assigning, 'assigning'); this._host.toggleAttribute('assigning', this._assigning);
if (this._assigning) { if (this._assigning) {
this._host.addEventListener('keydown', this._keydownEventHandler); this._host.addEventListener('keydown', this._keydownEventHandler);
@@ -2,11 +2,7 @@ import { ReactiveController, ReactiveControllerHost } from 'lit';
import { debounce } from 'lodash-es'; import { debounce } from 'lodash-es';
import { CameraDimensionsConfig } from '../config/schema/cameras'; import { CameraDimensionsConfig } from '../config/schema/cameras';
import { MediaLoadedInfoEventDetail } from '../types'; import { MediaLoadedInfoEventDetail } from '../types';
import { import { aspectRatioToString, setOrRemoveStyleProperty } from '../utils/basic';
aspectRatioToString,
setOrRemoveAttribute,
setOrRemoveStyleProperty,
} from '../utils/basic';
import { updateElementStyleFromMediaLayoutConfig } from '../utils/media-layout'; import { updateElementStyleFromMediaLayoutConfig } from '../utils/media-layout';
const ROTATED_ATTRIBUTE = 'rotated'; const ROTATED_ATTRIBUTE = 'rotated';
@@ -215,7 +211,7 @@ export class MediaDimensionsContainerController implements ReactiveController {
} }
private _setRotation(element: HTMLElement, rotate: boolean): void { private _setRotation(element: HTMLElement, rotate: boolean): void {
setOrRemoveAttribute(element, rotate, ROTATED_ATTRIBUTE); element.toggleAttribute(ROTATED_ATTRIBUTE, rotate);
} }
private _resize(): void { private _resize(): void {
+2 -3
View File
@@ -4,7 +4,6 @@ import { ViewDisplayConfig } from '../config/schema/common/display';
import { import {
forceReflow, forceReflow,
getChildrenFromElement, getChildrenFromElement,
setOrRemoveAttribute,
setOrRemoveStyleProperty, setOrRemoveStyleProperty,
} from '../utils/basic'; } from '../utils/basic';
import { fireAdvancedCameraCardEvent } from '../utils/fire-advanced-camera-card-event'; import { fireAdvancedCameraCardEvent } from '../utils/fire-advanced-camera-card-event';
@@ -322,12 +321,12 @@ export class MediaGridController {
private _updateSelectedStylesOnElements(): void { private _updateSelectedStylesOnElements(): void {
for (const [id, element] of this._gridContents.entries()) { for (const [id, element] of this._gridContents.entries()) {
setOrRemoveAttribute(element, id === this._selected, 'selected'); element.toggleAttribute('selected', id === this._selected);
// Explicitly use an 'unselected' attribute vs a :not(selected) such that // Explicitly use an 'unselected' attribute vs a :not(selected) such that
// a carousel with neither selected nor unselected will behave normally. // a carousel with neither selected nor unselected will behave normally.
// This matches a css selector in viewer-carousel.scss . // This matches a css selector in viewer-carousel.scss .
setOrRemoveAttribute(element, id !== this._selected, 'unselected'); element.toggleAttribute('unselected', id !== this._selected);
} }
} }
+2 -2
View File
@@ -9,7 +9,7 @@ import type { MenuItem } from '../config/schema/elements/custom/menu/types.js';
import type { MenuConfig } from '../config/schema/menu.js'; import type { MenuConfig } from '../config/schema/menu.js';
import type { Interaction } from '../types.js'; import type { Interaction } from '../types.js';
import { getActionConfigGivenAction } from '../utils/action'; import { getActionConfigGivenAction } from '../utils/action';
import { arrayify, isTruthy, setOrRemoveAttribute } from '../utils/basic.js'; import { arrayify, isTruthy } from '../utils/basic.js';
import { AutoHideState, isAutoHidden as evaluateAutoHidden } from './auto-hide.js'; import { AutoHideState, isAutoHidden as evaluateAutoHidden } from './auto-hide.js';
export class MenuController { export class MenuController {
@@ -126,7 +126,7 @@ export class MenuController {
public setExpanded(expanded: boolean): void { public setExpanded(expanded: boolean): void {
this._expanded = expanded; this._expanded = expanded;
setOrRemoveAttribute(this._host, expanded, 'expanded'); this._host.toggleAttribute('expanded', expanded);
this._host.requestUpdate(); this._host.requestUpdate();
} }
+3 -3
View File
@@ -5,7 +5,7 @@ import { ActionsConfig, StatusBarItem } from '../config/schema/actions/types';
import { STATUS_BAR_PRIORITY_DEFAULT } from '../config/schema/common/const'; import { STATUS_BAR_PRIORITY_DEFAULT } from '../config/schema/common/const';
import { StatusBarConfig } from '../config/schema/status-bar'; import { StatusBarConfig } from '../config/schema/status-bar';
import { getActionConfigGivenAction } from '../utils/action'; import { getActionConfigGivenAction } from '../utils/action';
import { arrayify, setOrRemoveAttribute } from '../utils/basic'; import { arrayify } from '../utils/basic';
import { Timer } from '../utils/timer'; import { Timer } from '../utils/timer';
import { AutoHideState, isAutoHidden as evaluateAutoHidden } from './auto-hide'; import { AutoHideState, isAutoHidden as evaluateAutoHidden } from './auto-hide';
@@ -144,10 +144,10 @@ export class StatusBarController {
} }
private _show(): void { private _show(): void {
setOrRemoveAttribute(this._host, false, 'hide'); this._host.toggleAttribute('hide', false);
} }
private _hide(): void { private _hide(): void {
setOrRemoveAttribute(this._host, true, 'hide'); this._host.toggleAttribute('hide', true);
} }
} }
+5 -18
View File
@@ -30,12 +30,7 @@ import {
import { configDefaults } from '../../config/schema/types'; import { configDefaults } from '../../config/schema/types';
import { HomeAssistant } from '../../ha/types'; import { HomeAssistant } from '../../ha/types';
import { stopEventFromActivatingCardWideActions } from '../../utils/action'; import { stopEventFromActivatingCardWideActions } from '../../utils/action';
import { import { formatDateAndTime, isHoverableDevice, isTruthy } from '../../utils/basic';
formatDateAndTime,
isHoverableDevice,
isTruthy,
setOrRemoveAttribute,
} from '../../utils/basic';
import { findBestMediaTimeIndex } from '../../utils/find-best-media-time-index'; import { findBestMediaTimeIndex } from '../../utils/find-best-media-time-index';
import { fireAdvancedCameraCardEvent } from '../../utils/fire-advanced-camera-card-event'; import { fireAdvancedCameraCardEvent } from '../../utils/fire-advanced-camera-card-event';
import { ViewMedia } from '../../view/item'; import { ViewMedia } from '../../view/item';
@@ -195,17 +190,9 @@ export class TimelineController {
if (this._timelineConfig !== (options.timelineConfig ?? null)) { if (this._timelineConfig !== (options.timelineConfig ?? null)) {
this._timelineConfig = options?.timelineConfig ?? null; this._timelineConfig = options?.timelineConfig ?? null;
setOrRemoveAttribute( this._host.toggleAttribute('recordings', !!this._timelineConfig?.show_recordings);
this._host, this._host.toggleAttribute('ribbon', this._timelineConfig?.style === 'ribbon');
!!this._timelineConfig?.show_recordings, this._host.toggleAttribute('stack', this._timelineConfig?.style === 'stack');
'recordings',
);
setOrRemoveAttribute(
this._host,
this._timelineConfig?.style === 'ribbon',
'ribbon',
);
setOrRemoveAttribute(this._host, this._timelineConfig?.style === 'stack', 'stack');
} }
this._thumbnailConfig = options?.thumbnailConfig ?? null; this._thumbnailConfig = options?.thumbnailConfig ?? null;
@@ -215,7 +202,7 @@ export class TimelineController {
this._timelineConfig = options?.timelineConfig ?? null; this._timelineConfig = options?.timelineConfig ?? null;
this._mini = options?.mini ?? false; this._mini = options?.mini ?? false;
setOrRemoveAttribute(this._host, this._shouldShowGroups(), 'groups'); this._host.toggleAttribute('groups', this._shouldShowGroups());
} }
public async setView(viewManagerEpoch: ViewManagerEpoch | null): Promise<void> { public async setView(viewManagerEpoch: ViewManagerEpoch | null): Promise<void> {
+3 -3
View File
@@ -26,7 +26,7 @@ import { localize } from '../../localize/localize.js';
import '../../patches/ha-hls-player.js'; import '../../patches/ha-hls-player.js';
import viewerCarouselStyle from '../../scss/viewer-carousel.scss'; import viewerCarouselStyle from '../../scss/viewer-carousel.scss';
import { stopEventFromActivatingCardWideActions } from '../../utils/action.js'; import { stopEventFromActivatingCardWideActions } from '../../utils/action.js';
import { contentsChanged, setOrRemoveAttribute } from '../../utils/basic.js'; import { contentsChanged } from '../../utils/basic.js';
import { CarouselSelected } from '../../utils/embla/carousel-controller.js'; import { CarouselSelected } from '../../utils/embla/carousel-controller.js';
import { getTextDirection } from '../../utils/text-direction.js'; import { getTextDirection } from '../../utils/text-direction.js';
import { ViewItemClassifier } from '../../view/item-classifier.js'; import { ViewItemClassifier } from '../../view/item-classifier.js';
@@ -235,7 +235,7 @@ export class AdvancedCameraCardViewerCarousel extends LitElement {
const newView = this.viewManagerEpoch?.manager.getView(); const newView = this.viewManagerEpoch?.manager.getView();
if (!newView?.context?.mediaViewer?.seek) { if (!newView?.context?.mediaViewer?.seek) {
setOrRemoveAttribute(this, false, 'unseekable'); this.toggleAttribute('unseekable', false);
} }
const oldView = this.viewManagerEpoch?.oldView; const oldView = this.viewManagerEpoch?.oldView;
@@ -436,7 +436,7 @@ export class AdvancedCameraCardViewerCarousel extends LitElement {
} }
const seekTimeInMedia = selectedMedia.includesTime(seek); const seekTimeInMedia = selectedMedia.includesTime(seek);
setOrRemoveAttribute(this, !seekTimeInMedia, 'unseekable'); this.toggleAttribute('unseekable', !seekTimeInMedia);
if (!seekTimeInMedia && !mediaPlayerController.isPaused()) { if (!seekTimeInMedia && !mediaPlayerController.isPaused()) {
mediaPlayerController.pause(); mediaPlayerController.pause();
} else if (seekTimeInMedia && mediaPlayerController.isPaused()) { } else if (seekTimeInMedia && mediaPlayerController.isPaused()) {
+1 -2
View File
@@ -8,7 +8,6 @@ import {
} from 'lit'; } from 'lit';
import { customElement, property, state } from 'lit/decorators.js'; import { customElement, property, state } from 'lit/decorators.js';
import { ZoomController } from '../components-lib/zoom/zoom-controller.js'; import { ZoomController } from '../components-lib/zoom/zoom-controller.js';
import { setOrRemoveAttribute } from '../utils/basic.js';
import { PartialZoomSettings } from '../components-lib/zoom/types.js'; import { PartialZoomSettings } from '../components-lib/zoom/types.js';
@customElement('advanced-camera-card-zoomer') @customElement('advanced-camera-card-zoomer')
@@ -48,7 +47,7 @@ export class AdvancedCameraCardZoomer extends LitElement {
protected willUpdate(changedProps: PropertyValues): void { protected willUpdate(changedProps: PropertyValues): void {
if (changedProps.has('_zoomed')) { if (changedProps.has('_zoomed')) {
setOrRemoveAttribute(this, this._zoomed, 'zoomed'); this.toggleAttribute('zoomed', this._zoomed);
} }
if (changedProps.has('zoom')) { if (changedProps.has('zoom')) {
@@ -4,7 +4,6 @@ import {
StatusBarConfig, StatusBarConfig,
statusBarConfigSchema, statusBarConfigSchema,
} from '../../src/config/schema/status-bar'; } from '../../src/config/schema/status-bar';
import { setOrRemoveAttribute } from '../../src/utils/basic';
import { createInteractionActionEvent, createLitElement } from '../test-utils'; import { createInteractionActionEvent, createLitElement } from '../test-utils';
const createConfig = (config?: unknown): StatusBarConfig => { const createConfig = (config?: unknown): StatusBarConfig => {
@@ -35,7 +34,7 @@ describe('StatusBarController', () => {
it('should not hide when not in popup style', () => { it('should not hide when not in popup style', () => {
const host = createLitElement(); const host = createLitElement();
setOrRemoveAttribute(host, true, 'hide'); host.toggleAttribute('hide', true);
const controller = new StatusBarController(host); const controller = new StatusBarController(host);
@@ -52,7 +51,7 @@ describe('StatusBarController', () => {
it('should not show when in popup style', () => { it('should not show when in popup style', () => {
const host = createLitElement(); const host = createLitElement();
setOrRemoveAttribute(host, true, 'hide'); host.toggleAttribute('hide', true);
const controller = new StatusBarController(host); const controller = new StatusBarController(host);
@@ -181,7 +180,7 @@ describe('StatusBarController', () => {
describe('should deal with popup styles correctly', () => { describe('should deal with popup styles correctly', () => {
it('should show from empty to sufficient', () => { it('should show from empty to sufficient', () => {
const host = createLitElement(); const host = createLitElement();
setOrRemoveAttribute(host, true, 'hide'); host.toggleAttribute('hide', true);
const controller = new StatusBarController(host); const controller = new StatusBarController(host);
controller.setConfig( controller.setConfig(
@@ -203,7 +202,7 @@ describe('StatusBarController', () => {
it('should not show from empty to insufficient', () => { it('should not show from empty to insufficient', () => {
const host = createLitElement(); const host = createLitElement();
setOrRemoveAttribute(host, true, 'hide'); host.toggleAttribute('hide', true);
const controller = new StatusBarController(host); const controller = new StatusBarController(host);
controller.setConfig( controller.setConfig(
@@ -255,13 +254,13 @@ describe('StatusBarController', () => {
controller.setItems([sufficientString]); controller.setItems([sufficientString]);
// Emulate the popup being hidden. // Emulate the popup being hidden.
setOrRemoveAttribute(host, true, 'hide'); host.toggleAttribute('hide', true);
controller.setItems([sufficientIcon]); controller.setItems([sufficientIcon]);
expect(host.getAttribute('hide')).toBe(null); expect(host.getAttribute('hide')).toBe(null);
// Emulate the popup being hidden. // Emulate the popup being hidden.
setOrRemoveAttribute(host, true, 'hide'); host.toggleAttribute('hide', true);
controller.setItems([sufficientImage]); controller.setItems([sufficientImage]);
expect(host.getAttribute('hide')).toBe(null); expect(host.getAttribute('hide')).toBe(null);
@@ -269,7 +268,7 @@ describe('StatusBarController', () => {
it('should not start popup timer when permanent items are present', () => { it('should not start popup timer when permanent items are present', () => {
const host = createLitElement(); const host = createLitElement();
setOrRemoveAttribute(host, true, 'hide'); host.toggleAttribute('hide', true);
const controller = new StatusBarController(host); const controller = new StatusBarController(host);
controller.setConfig( controller.setConfig(