fix: Fix initialization race condition that occurs in certain circumstances (#1545)

* fix: Fix initialization race condition in certain circumstances

* Minor improvements and camera iris logo
This commit is contained in:
Dermot Duffy
2024-09-19 19:42:38 -07:00
committed by GitHub
parent af4666e023
commit 650d99ec00
26 changed files with 611 additions and 461 deletions
+8 -13
View File
@@ -111,7 +111,6 @@ export class CameraManager {
protected _api: CardCameraAPI;
protected _engineFactory: CameraManagerEngineFactory;
protected _store: CameraManagerStore;
protected _initializationLimit = new PQueue({ concurrency: 1 });
protected _requestLimit = new PQueue();
constructor(
@@ -147,16 +146,8 @@ export class CameraManager {
recursivelyMergeObjectsNotArrays({}, cloneDeep(config?.cameras_global), camera),
);
const resetAndInitialize = async () => {
await this._reset();
await this._initializeCameras(cameras);
};
try {
// This concurrency limit prevents multiple rapidly arriving configs from
// generating reset-n-initialize race conditions (e.g. changing values
// rapidly in the config editor).
await this._initializationLimit.add(resetAndInitialize);
await this._initializeCameras(cameras);
} catch (e: unknown) {
this._api
.getMessageManager()
@@ -166,7 +157,7 @@ export class CameraManager {
return true;
}
protected async _reset(): Promise<void> {
public async reset(): Promise<void> {
await this._store.reset();
}
@@ -246,6 +237,8 @@ export class CameraManager {
async ([cameraConfig, engine]) => await engine.createCamera(hass, cameraConfig),
);
const cameraIDs: Set<string> = new Set();
// Do the additions based off the result-order, to ensure the map order is
// preserved.
cameras.forEach((camera) => {
@@ -258,7 +251,7 @@ export class CameraManager {
);
}
if (this._store.hasCameraID(cameraID)) {
if (cameraIDs.has(cameraID)) {
throw new CameraInitializationError(
localize('error.duplicate_camera_id'),
camera.getConfig(),
@@ -267,9 +260,11 @@ export class CameraManager {
// Always ensure the actual ID used in the card is in the configuration itself.
camera.setID(cameraID);
this._store.addCamera(camera);
cameraIDs.add(cameraID);
});
await this._store.setCameras(cameras);
log(
this._api.getConfigManager().getCardWideConfig(),
'Frigate Card CameraManager initialized (Cameras: ',
+24
View File
@@ -44,6 +44,30 @@ export class CameraManagerStore implements CameraManagerReadOnlyConfigStore {
this._enginesByType.set(camera.getEngine().getEngineType(), camera.getEngine());
}
public async setCameras(cameras: Camera[]): Promise<void> {
// In setting the store cameras, take great care to replace/add first before
// remove. Otherwise, there may be race conditions where the card attempts
// to render a view with (momentarily) no camera.
// See: https://github.com/dermotduffy/frigate-hass-card/issues/1533
// Replace/Add the new cameras.
for (const camera of cameras) {
const oldCamera = this._cameras.get(camera.getID());
if (oldCamera !== camera) {
this.addCamera(camera);
await oldCamera?.destroy();
}
}
// Remove the old cameras.
for (const camera of this._cameras.values()) {
if (!cameras.includes(camera)) {
await camera.destroy();
this._cameras.delete(camera.getID());
}
}
}
public async reset(): Promise<void> {
await allPromises(this._cameras.values(), (camera) => camera.destroy());
this._cameras.clear();
@@ -67,7 +67,12 @@ export class CardElementManager {
this._api.getMediaLoadedInfoManager().initialize();
this._api.getMicrophoneManager().initialize();
this._api.getKeyboardStateManager().initialize();
// These initializers are called when the config is updated, but on initial
// creation of the card hass is not yet available when the config is first
// loaded.
this._api.getDefaultManager().initialize();
this._api.getMediaPlayerManager().initialize();
this._api
.getHASSManager()
@@ -146,6 +151,8 @@ export class CardElementManager {
// reconnection, to ensure the state subscription/unsubscription works
// correctly for triggers.
this._api.getInitializationManager().uninitialize(InitializationAspect.CAMERAS);
this._api.getCameraManager().reset();
this._element.removeEventListener(
'mousemove',
this._api.getInteractionManager().reportInteraction,
+17 -12
View File
@@ -92,16 +92,20 @@ export class ConfigManager {
camera: undefined,
});
this._api.getMediaLoadedInfoManager().clear();
this._api.getInitializationManager().uninitialize(InitializationAspect.VIEW);
this._api.getViewManager().reset();
this._api.getMessageManager().reset();
this._api.getStyleManager().setPerformance();
this._api.getCardElementManager().update();
this._api.getStatusBarItemManager().removeAllDynamicStatusBarItems();
setKeyboardShortcutsFromConfig(this._api, this);
setAutomationsFromConfig(this._api);
this.computeOverrideConfig();
this._api.getCardElementManager().update();
}
public computeOverrideConfig(): void {
@@ -144,17 +148,18 @@ export class ConfigManager {
.uninitialize(InitializationAspect.MICROPHONE_CONNECT);
}
if (
previousConfig &&
!isEqual(
previousConfig?.view.default_reset,
this._overriddenConfig?.view.default_reset,
)
) {
this._api
.getInitializationManager()
.uninitialize(InitializationAspect.DEFAULT_RESET);
}
/* async */ this._initializeBackground(previousConfig);
}
/**
* Initialize config dependent items in the background. For items that the
* card hard requires, use InitializationManager instead.
*/
protected async _initializeBackground(
previousConfig: FrigateCardConfig | null,
): Promise<void> {
await this._api.getDefaultManager().initializeIfNecessary(previousConfig);
await this._api.getMediaPlayerManager().initializeIfNecessary(previousConfig);
this._api.getCardElementManager().update();
}
+34 -38
View File
@@ -1,4 +1,5 @@
import PQueue from 'p-queue';
import { isEqual } from 'lodash-es';
import { FrigateCardConfig } from '../config/types';
import { createGeneralAction } from '../utils/action';
import { isActionAllowedBasedOnInteractionState } from '../utils/interaction-mode';
import { Timer } from '../utils/timer';
@@ -10,20 +11,45 @@ import { CardDefaultManagerAPI } from './types';
export class DefaultManager {
protected _timer = new Timer();
protected _api: CardDefaultManagerAPI;
protected _initializationLimit = new PQueue({ concurrency: 1 });
constructor(api: CardDefaultManagerAPI) {
this._api = api;
}
public async initializeIfNecessary(
previousConfig: FrigateCardConfig | null,
): Promise<void> {
if (
!isEqual(
previousConfig?.view.default_reset,
this._api.getConfigManager().getConfig()?.view.default_reset,
)
) {
await this.initialize();
}
}
/**
* Initialize the default manager. Requires both hass and configuration to be
* effective (so cannot be called from just the configuration manager, as hass
* will not be available yet)
* This needs to be public since the first initialization requires both hass
* and the config, so it is not suitable from calling exclusively from the
* config manager.
*/
public async initialize(): Promise<boolean> {
const result = await this._initializationLimit.add(() => this._reconfigure());
this._startTimer();
this.uninitialize();
const config = this._api.getConfigManager().getConfig()?.view.default_reset;
if (config?.entities.length) {
this._api
.getHASSManager()
.getStateWatcher()
.subscribe(this._stateChangeHandler, config.entities);
}
const timerSeconds = this._api.getConfigManager().getConfig()?.view
.default_reset.every_seconds;
if (timerSeconds) {
this._timer.startRepeated(timerSeconds, () => this._setToDefaultIfAllowed());
}
if (this._api.getConfigManager().getConfig()?.view.default_reset.after_interaction) {
this._api.getAutomationsManager().addAutomations([
@@ -40,7 +66,7 @@ export class DefaultManager {
]);
}
return !!result;
return true;
}
public uninitialize(): void {
@@ -49,28 +75,6 @@ export class DefaultManager {
this._api.getAutomationsManager().deleteAutomations(this);
}
protected async _reconfigure(): Promise<boolean> {
const hass = this._api.getHASSManager().getHASS();
const config = this._api.getConfigManager().getConfig()?.view.default_reset;
if (!hass || !config) {
return false;
}
this._api.getHASSManager().getStateWatcher().unsubscribe(this._stateChangeHandler);
this._api
.getHASSManager()
.getStateWatcher()
.subscribe(this._stateChangeHandler, config.entities);
// If the timer is running, restart it with the newly configured timer.
if (this._timer.isRunning()) {
this._timer.stop();
this._startTimer();
}
return true;
}
protected _stateChangeHandler = (): void => {
this._setToDefaultIfAllowed();
};
@@ -92,12 +96,4 @@ export class DefaultManager {
)
);
}
protected _startTimer(): void {
const timerSeconds = this._api.getConfigManager().getConfig()?.view
.default_reset.every_seconds;
if (timerSeconds) {
this._timer.startRepeated(timerSeconds, () => this._setToDefaultIfAllowed());
}
}
}
+45 -81
View File
@@ -1,3 +1,4 @@
import PQueue from 'p-queue';
import { loadLanguages } from '../localize/localize';
import { sideLoadHomeAssistantElements } from '../utils/ha';
import { Initializer } from '../utils/initializer/initializer';
@@ -6,14 +7,29 @@ import { CardInitializerAPI } from './types';
export enum InitializationAspect {
LANGUAGES = 'languages',
SIDE_LOAD_ELEMENTS = 'side-load-elements',
MEDIA_PLAYERS = 'media-players',
CAMERAS = 'cameras',
MICROPHONE_CONNECT = 'microphone-connect',
DEFAULT_RESET = 'default-reset',
VIEW = 'view',
}
// =========================================================================
// Rules for initialization. Initializers must be reentrant as these situations
// may occur:
//
// 1. Multiple JS async contexts may execute these functions at the same time.
// 2. At any point, something may uninitialize a part of the card (including
// while a different async context is in the middle of running the
// initialization method).
// =========================================================================
export class InitializationManager {
protected _api: CardInitializerAPI;
// A concurrency limit is placed to ensure that on card load multiple async
// contexts do not attempt to initialize the card at the same time. This is
// not strictly necessary, just more efficient, as long as the "Rules for
// initialization" (above) are followed.
protected _initializationQueue = new PQueue({ concurrency: 1 });
protected _initializer: Initializer;
constructor(api: CardInitializerAPI, initializer?: Initializer) {
@@ -27,28 +43,29 @@ export class InitializationManager {
return false;
}
return (
this._initializer.isInitializedMultiple([
InitializationAspect.LANGUAGES,
InitializationAspect.SIDE_LOAD_ELEMENTS,
InitializationAspect.CAMERAS,
...(config.live.microphone.always_connected
? [InitializationAspect.MICROPHONE_CONNECT]
: []),
]) &&
// If there's no view, re-initialize (e.g. config changes).
this._api.getViewManager().hasView()
);
return this._initializer.isInitializedMultiple([
InitializationAspect.LANGUAGES,
InitializationAspect.SIDE_LOAD_ELEMENTS,
InitializationAspect.CAMERAS,
...(config.live.microphone.always_connected
? [InitializationAspect.MICROPHONE_CONNECT]
: []),
InitializationAspect.VIEW,
]);
}
/**
* Initialize the hard requirements for rendering anything.
* @returns `true` if card rendering can continue.
*/
public async initializeMandatory(): Promise<boolean> {
public async initializeMandatory(): Promise<void> {
await this._initializationQueue.add(() => this._initializeMandatory());
}
protected async _initializeMandatory(): Promise<void> {
const hass = this._api.getHASSManager().getHASS();
if (!hass) {
return false;
if (!hass || this.isInitializedMandatory()) {
return;
}
if (
@@ -60,12 +77,12 @@ export class InitializationManager {
await sideLoadHomeAssistantElements(),
}))
) {
return false;
return;
}
const config = this._api.getConfigManager().getConfig();
if (!config) {
return false;
return;
}
if (
@@ -83,76 +100,23 @@ export class InitializationManager {
}),
}))
) {
return false;
}
if (!this._api.getMessageManager().hasMessage()) {
if (!this._api.getViewManager().hasView()) {
// Set a view on initial load. However, if the query string contains a
// view related action, we don't set any view here and allow that content
// to be triggered by the firstUpdated() call that runs query string
// actions. To do otherwise may cause a race condition between the default
// view and the querystring view, see:
// https://github.com/dermotduffy/frigate-hass-card/issues/1200
const hasViewRelatedActions = this._api
.getQueryStringManager()
.hasViewRelatedActions();
if (hasViewRelatedActions) {
this._api.getQueryStringManager().executeViewRelated();
} else {
this._api.getViewManager().setViewDefaultWithNewQuery({ failSafe: true });
}
} else {
// If we already have a view, something (e.g. cameras) may have been
// reinitialized, be sure to ask for an update.
this._api.getCardElementManager().update();
}
}
return true;
}
/**
* Initialize aspects of the card that can load in the 'background'.
* @returns `true` if card rendering can continue.
*/
public async initializeBackgroundIfNecessary(): Promise<boolean> {
const hass = this._api.getHASSManager().getHASS();
const config = this._api.getConfigManager().getConfig();
if (!hass || !config) {
return false;
return;
}
if (
this._initializer.isInitializedMultiple([
InitializationAspect.DEFAULT_RESET,
...(config.menu.buttons.media_player.enabled
? [InitializationAspect.MEDIA_PLAYERS]
: []),
])
this._api.getMessageManager().hasMessage() ||
!(await this._initializer.initializeIfNecessary(
InitializationAspect.VIEW,
this._api.getViewManager().initialize,
))
) {
return true;
}
if (
!(await this._initializer.initializeMultipleIfNecessary({
[InitializationAspect.DEFAULT_RESET]: async () =>
await this._api.getDefaultManager().initialize(),
...(config.menu.buttons.media_player.enabled && {
[InitializationAspect.MEDIA_PLAYERS]: async () =>
await this._api.getMediaPlayerManager().initialize(),
}),
}))
) {
return false;
return;
}
this._api.getCardElementManager().update();
return true;
}
public uninitialize(aspect: InitializationAspect) {
return this._initializer.uninitialize(aspect);
public uninitialize(aspect: InitializationAspect): void {
this._initializer.uninitialize(aspect);
}
}
+16 -2
View File
@@ -1,4 +1,4 @@
import { CameraConfig } from '../config/types';
import { CameraConfig, FrigateCardConfig } from '../config/types';
import { MEDIA_PLAYER_SUPPORT_BROWSE_MEDIA } from '../const';
import { localize } from '../localize/localize';
import { errorToConsole } from '../utils/basic';
@@ -25,9 +25,23 @@ export class MediaPlayerManager {
return this._mediaPlayers.length > 0;
}
public async initializeIfNecessary(
previousConfig: FrigateCardConfig | null,
): Promise<void> {
if (
previousConfig?.menu.buttons.media_player.enabled !==
this._api.getConfigManager().getConfig()?.menu.buttons.media_player.enabled
) {
await this.initialize();
}
}
public async initialize(): Promise<boolean> {
const hass = this._api.getHASSManager().getHASS();
if (!hass) {
if (
!hass ||
!this._api.getConfigManager().getConfig()?.menu.buttons.media_player.enabled
) {
return false;
}
+9 -9
View File
@@ -23,18 +23,18 @@ export class QueryStringManager {
return !!this._calculateIntent().view;
}
public executeNonViewRelated = (): void => {
this._executeNonViewRelated(this._calculateIntent());
public executeNonViewRelated = async (): Promise<void> => {
await this._executeNonViewRelated(this._calculateIntent());
};
public executeViewRelated = (): void => {
this._executeViewRelated(this._calculateIntent());
public executeViewRelated = async (): Promise<void> => {
await this._executeViewRelated(this._calculateIntent());
};
public executeAll = (): void => {
public executeAll = async (): Promise<void> => {
const intent = this._calculateIntent();
this._executeViewRelated(intent);
this._executeNonViewRelated(intent);
await this._executeViewRelated(intent);
await this._executeNonViewRelated(intent);
};
protected async _executeViewRelated(intent: QueryStringViewIntent): Promise<void> {
@@ -62,7 +62,7 @@ export class QueryStringManager {
}
}
protected _executeNonViewRelated(intent: QueryStringViewIntent): void {
protected async _executeNonViewRelated(intent: QueryStringViewIntent): Promise<void> {
if (
// Only execute non-view actions when the card has rendered at least once.
!this._api.getCardElementManager().hasUpdated() ||
@@ -71,7 +71,7 @@ export class QueryStringManager {
return;
}
this._api.getActionsManager().executeActions(intent.other);
await this._api.getActionsManager().executeActions(intent.other);
}
protected _calculateIntent(): QueryStringViewIntent {
+3
View File
@@ -91,6 +91,7 @@ export interface CardConfigAPI {
getDefaultManager(): DefaultManager;
getInitializationManager(): InitializationManager;
getMediaLoadedInfoManager(): MediaLoadedInfoManager;
getMediaPlayerManager(): MediaPlayerManager;
getMessageManager(): MessageManager;
getStatusBarItemManager(): StatusBarItemManager;
getStyleManager(): StyleManager;
@@ -201,6 +202,7 @@ export interface CardMediaLoadedAPI {
export interface CardMediaPlayerAPI {
getCameraManager(): CameraManager;
getConfigManager(): ConfigManager;
getEntityRegistryManager(): EntityRegistryManager;
getHASSManager(): HASSManager;
getMessageManager(): MessageManager;
@@ -257,6 +259,7 @@ export interface CardViewAPI {
getHASSManager(): HASSManager;
getMediaLoadedInfoManager(): MediaLoadedInfoManager;
getMessageManager(): MessageManager;
getQueryStringManager(): QueryStringManager;
getStyleManager(): StyleManager;
getTriggersManager(): TriggersManager;
}
+18
View File
@@ -133,6 +133,24 @@ export class ViewManager implements ViewManagerInterface {
);
}
public initialize = async (): Promise<boolean> => {
// Set a view on initial load. However, if the query string contains a view
// related action, we don't set any view here and allow that content to be
// triggered by the firstUpdated() call that runs query string actions. To
// do otherwise may cause a race condition between the default view and the
// querystring view, see:
// https://github.com/dermotduffy/frigate-hass-card/issues/1200
const hasViewRelatedActions = this._api
.getQueryStringManager()
.hasViewRelatedActions();
if (hasViewRelatedActions) {
await this._api.getQueryStringManager().executeViewRelated();
} else {
await this.setViewDefaultWithNewQuery({ failSafe: true });
}
return true;
};
protected _setView(view: View | null): void {
const oldView = this._view;
+27 -36
View File
@@ -15,7 +15,7 @@ import { FrigateCardElements } from './components/elements.js';
import './components/menu.js';
import { FrigateCardMenu } from './components/menu.js';
import './components/message.js';
import { renderMessage, renderProgressIndicator } from './components/message.js';
import { renderMessage } from './components/message.js';
import './components/overlay.js';
import { FrigateCardOverlay } from './components/overlay.js';
import './components/status-bar';
@@ -188,10 +188,6 @@ class FrigateCard extends LitElement {
return true;
}
protected willUpdate(): void {
this._controller.getInitializationManager().initializeBackgroundIfNecessary();
}
protected _renderMenuStatusContainer(
position: 'top' | 'bottom' | 'overlay',
): TemplateResult | void {
@@ -373,37 +369,32 @@ class FrigateCard extends LitElement {
${this._renderMenuStatusContainer('top')}
<div ${ref(this._refMain)} class="${classMap(mainClasses)}">
${this._renderMenuStatusContainer('overlay')}
${!cameraManager.isInitialized() &&
!this._controller.getMessageManager().hasMessage()
? renderProgressIndicator({
cardWideConfig: this._controller.getConfigManager().getCardWideConfig(),
})
: // Always want to render <frigate-card-views> even if there's a message, to
// ensure live preload is always present (even if not displayed).
html`<frigate-card-views
${ref(this._refViews)}
.hass=${this._hass}
.viewManagerEpoch=${this._controller.getViewManager().getEpoch()}
.cameraManager=${cameraManager}
.resolvedMediaCache=${this._controller.getResolvedMediaCache()}
.nonOverriddenConfig=${this._controller
.getConfigManager()
.getNonOverriddenConfig()}
.overriddenConfig=${this._controller.getConfigManager().getConfig()}
.cardWideConfig=${this._controller
.getConfigManager()
.getCardWideConfig()}
.rawConfig=${this._controller.getConfigManager().getRawConfig()}
.configManager=${this._controller.getConfigManager()}
.conditionsManagerEpoch=${this._controller
.getConditionsManager()
?.getEpoch()}
.hide=${!!this._controller.getMessageManager().hasMessage()}
.microphoneManager=${this._controller.getMicrophoneManager()}
.triggeredCameraIDs=${this._config?.view.triggers.show_trigger_status
? this._controller.getTriggersManager().getTriggeredCameraIDs()
: undefined}
></frigate-card-views>`}
${
// Always want to render <frigate-card-views> even if there's a message, to
// ensure live preload is always present (even if not displayed).
html`<frigate-card-views
${ref(this._refViews)}
.hass=${this._hass}
.viewManagerEpoch=${this._controller.getViewManager().getEpoch()}
.cameraManager=${cameraManager}
.resolvedMediaCache=${this._controller.getResolvedMediaCache()}
.nonOverriddenConfig=${this._controller
.getConfigManager()
.getNonOverriddenConfig()}
.overriddenConfig=${this._controller.getConfigManager().getConfig()}
.cardWideConfig=${this._controller.getConfigManager().getCardWideConfig()}
.rawConfig=${this._controller.getConfigManager().getRawConfig()}
.configManager=${this._controller.getConfigManager()}
.conditionsManagerEpoch=${this._controller
.getConditionsManager()
?.getEpoch()}
.hide=${!!this._controller.getMessageManager().hasMessage()}
.microphoneManager=${this._controller.getMicrophoneManager()}
.triggeredCameraIDs=${this._config?.view.triggers.show_trigger_status
? this._controller.getTriggersManager().getTriggeredCameraIDs()
: undefined}
></frigate-card-views>`
}
${
// Keep message rendering to last to show messages that may have been
// generated during the render.
+6
View File
@@ -21,3 +21,9 @@
$ convert -extent 2048x1152 -flop -gravity center 47543120431_b285c45ac8_k.jpg frigate-bird-in-sky.jpg
$ mogrify -strip -interlace Plane -quality 85% -scale 492x277 frigate-bird-in-sky.jpg
```
## camera-iris.svg
**Link**: https://pictogrammers.com/library/mdi/icon/camera-iris/
**License**: https://www.apache.org/licenses/LICENSE-2.0
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M13.73,15L9.83,21.76C10.53,21.91 11.25,22 12,22C14.4,22 16.6,21.15 18.32,19.75L14.66,13.4M2.46,15C3.38,17.92 5.61,20.26 8.45,21.34L12.12,15M8.54,12L4.64,5.25C3,7 2,9.39 2,12C2,12.68 2.07,13.35 2.2,14H9.69M21.8,10H14.31L14.6,10.5L19.36,18.75C21,16.97 22,14.6 22,12C22,11.31 21.93,10.64 21.8,10M21.54,9C20.62,6.07 18.39,3.74 15.55,2.66L11.88,9M9.4,10.5L14.17,2.24C13.47,2.09 12.75,2 12,2C9.6,2 7.4,2.84 5.68,4.25L9.34,10.6L9.4,10.5Z" /></svg>

After

Width:  |  Height:  |  Size: 509 B

+9 -5
View File
@@ -1,6 +1,8 @@
import {
HomeAssistant,
LovelaceCard,
LovelaceCardConfig,
LovelaceCardEditor,
Themes,
} from '@dermotduffy/custom-card-helpers';
import { StyleInfo } from 'lit/directives/style-map.js';
@@ -86,12 +88,14 @@ export interface FrigateCardMediaPlayer {
isPaused(): boolean;
}
export type LovelaceCardWithEditor = LovelaceCard & {
constructor: {
getConfigElement(): Promise<LovelaceCardEditor>;
};
};
export interface CardHelpers {
createCardElement(config: LovelaceCardConfig): Promise<{
constructor: {
getConfigElement(): HTMLElement;
};
}>;
createCardElement(config: LovelaceCardConfig): Promise<LovelaceCardWithEditor>;
}
export type PTZMovementType = 'relative' | 'continuous';
+12 -7
View File
@@ -11,6 +11,7 @@ import {
CardHelpers,
ExtendedHomeAssistant,
FrigateCardError,
LovelaceCardWithEditor,
SignedPath,
signedPathSchema,
StateParameters,
@@ -316,17 +317,21 @@ export const sideLoadHomeAssistantElements = async (): Promise<boolean> => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const helpers: CardHelpers = await (window as any).loadCardHelpers();
// The picture-glance editor loads everything this card needs.
const pictureGlance = await helpers.createCardElement({
// This bizarre combination of hacks creates a dummy picture glance card, then
// waits for it to be fully loaded/upgraded as a custom element, so it will
// have the getConfigElement() method which is necessary to load all the
// elements this card requires.
await helpers.createCardElement({
type: 'picture-glance',
entities: [],
camera_image: 'dummy-to-load-editor-components',
});
if (pictureGlance.constructor.getConfigElement) {
await pictureGlance.constructor.getConfigElement();
return true;
}
return false;
const pgcConstructor = await customElements.whenDefined('hui-picture-glance-card');
const pgc = new pgcConstructor() as LovelaceCardWithEditor;
await pgc.constructor.getConfigElement();
return true;
};
/**
+18 -38
View File
@@ -1,21 +1,14 @@
import { allPromises } from '../basic';
enum InitializationState {
INITIALIZING = 'initializing',
INITIALIZED = 'initialized',
}
type InitializationCallback = () => Promise<boolean>;
/**
* Manages initialization state & calling initializers.
* Manages initialization state & calling initializers. There is no guarantee
* something will not be initialized twice unless there are concurrency controls
* applied to the usage of this class.
*/
export class Initializer {
protected _state: Map<string, InitializationState>;
constructor() {
this._state = new Map();
}
protected _initialized: Set<string> = new Set();
public async initializeMultipleIfNecessary(
aspects: Record<string, InitializationCallback>,
@@ -27,43 +20,30 @@ export class Initializer {
return results.every(Boolean);
}
/**
*
* @param aspect The aspect to initialize.
* @param initializer The initializer to call.
* @returns `true` if the state is confirmed as initialized, `false`
* otherwise (i.e. initializing).
*/
public async initializeIfNecessary(
aspect: string,
initializer?: InitializationCallback,
): Promise<boolean> {
const state = this._state.get(aspect);
if (state !== InitializationState.INITIALIZED) {
if (state !== InitializationState.INITIALIZING) {
if (initializer) {
this._state.set(aspect, InitializationState.INITIALIZING);
if (await initializer()) {
this._state.set(aspect, InitializationState.INITIALIZED);
} else {
this.uninitialize(aspect);
}
} else {
this._state.set(aspect, InitializationState.INITIALIZED);
}
return true;
}
return false;
if (this._initialized.has(aspect)) {
return true;
}
return true;
if (!initializer) {
this._initialized.add(aspect);
return true;
}
if (await initializer()) {
this._initialized.add(aspect);
return true;
}
return false;
}
public uninitialize(aspect: string) {
return this._state.delete(aspect);
public uninitialize(aspect: string): void {
this._initialized.delete(aspect);
}
public isInitialized(aspect: string): boolean {
return this._state.get(aspect) == InitializationState.INITIALIZED;
return this._initialized.has(aspect);
}
public isInitializedMultiple(aspects: string[]): boolean {