Split automations into HA-style `triggers`, ongoing `conditions`, and
`actions`, with compatibility migrations for existing Advanced Camera
Card configs.
## Summary
At a glance (details below):
- **Added** `triggers:` -- a required, HA-shaped block: stock `state` /
`numeric_state` / `template` plus card-specific triggers (`camera`,
`view`, `fullscreen`, ...).
- **Added** the HA-native `if` / `then` / `else` action.
- **Removed** `actions_not` (replaced by `if` / `then` / `else`).
- **Removed** the ambient `advanced_camera_card` template namespace (use
`acc` instead).
- **Changed** the trigger template surface to a top-level `trigger.*`
variable (as in HA); the nested `acc.trigger.*` paths are removed.
- **Changed** `conditions:` to ongoing gates only -- they no longer wake
an automation, and change-only forms (`config`, valueless `camera` /
`view` / `state`) become triggers, not conditions.
- **Changed** action templates to render per step, so a later action
sees state an earlier one changed.
- **Compatibility:** HA-shaped YAML is accepted (singular keys,
single-or-list, `and` / `or` / `not` shorthand, `entity` / `entity_id`).
- **Migration:** existing configs upgrade automatically; anything that
cannot be converted faithfully is recorded under `__UPGRADE_FAILURE__`
for manual fixup.
## Breaking Changes
### 1. Automations now require triggers
Before this PR, `automations[].conditions` served two roles:
- They decided whether the automation should run.
- They also acted as the thing that woke the automation up.
After this PR:
- `triggers` wake the automation.
- `conditions` only gate it at the instant a trigger fires.
Most existing automations are migrated automatically from `conditions:`
to `triggers:`.
### 2. `actions_not` is retired
Legacy `actions_not` is replaced by an HA-style `if` action with `then`
/ `else`.
Faithful conversions are automatic. Cases that cannot be faithfully
converted are recorded under `__UPGRADE_FAILURE__.automations` and must
be migrated manually.
### 3. Template surface aligned with Home Assistant
Two related template changes, both auto-migrated:
- **Top-level `trigger.*`.** Automation actions now receive a top-level
`trigger` template variable, like Home Assistant. Legacy nested paths
such as `acc.trigger.state.to` and
`advanced_camera_card.trigger.camera.to` are migrated automatically when
they appear inside template strings.
- **The ambient `advanced_camera_card` template namespace is removed.**
The long-form ambient namespace (`advanced_camera_card.camera`,
`advanced_camera_card.view`, `advanced_camera_card.config`) is retired
in favour of its shorter `acc` alias -- supported since v7.1.0, and the
only spelling the new trigger surface uses. Existing templates are
migrated automatically by rewriting the `advanced_camera_card.` prefix
to `acc.`.
### 4. Trigger-only condition forms are no longer valid conditions
Some legacy "conditions" were really change detectors. These are now
triggers only:
- `condition: config`
- valueless `camera`
- valueless `view`
- valueless `state` / picture-elements state condition with neither
`state` nor `state_not`
These are automatically promoted in automations and stripped from
overrides/elements where they would no longer be meaningful as ongoing
conditions.
### 5. Template truthiness now follows Home Assistant behavior
Template conditions and template triggers intentionally use different
truthiness rules, matching HA:
- A template condition passes only when the rendered value is `true`
(case-insensitive), matching HA's `condition.py`.
- A template trigger uses HA's broader `result_as_boolean` coercion: a
non-zero number, or `1` / `true` / `yes` / `on` / `enable`
(case-insensitive), counts as true.
### 6. Action templates render when each action executes
Action templates are now rendered per action step, not once for the
whole sequence. This means a later action can see card-local state
changed by an earlier action in the same sequence.
The `trigger` context is fixed for the automation run. HA entity state
updates still depend on the frontend receiving updated HASS state over
the websocket.
## Automatic Migrations
### Automation `conditions:` to `triggers:`
Simple legacy automation:
```yaml
# Before
automations:
- conditions:
- condition: fullscreen
fullscreen: true
actions:
- action: custom:advanced-camera-card-action
advanced_camera_card_action: substream_on
```
```yaml
# After, automatic
automations:
- triggers:
- trigger: fullscreen
fullscreen: true
actions:
- action: custom:advanced-camera-card-action
advanced_camera_card_action: substream_on
```
State conditions become HA-style state triggers:
```yaml
# Before
automations:
- conditions:
- condition: state
entity_id: binary_sensor.front_door
state: 'on'
actions:
- action: custom:advanced-camera-card-action
advanced_camera_card_action: live
```
```yaml
# After, automatic
automations:
- triggers:
- trigger: state
entity_id: binary_sensor.front_door
to: 'on'
actions:
- action: custom:advanced-camera-card-action
advanced_camera_card_action: live
```
Multiple conditions become both triggers and ongoing conditions:
```yaml
# Before
automations:
- conditions:
- condition: camera
cameras: [front_door]
- condition: fullscreen
fullscreen: true
actions:
- action: custom:advanced-camera-card-action
advanced_camera_card_action: substream_on
```
```yaml
# After, automatic
automations:
- triggers:
- trigger: camera
cameras: [front_door]
- trigger: fullscreen
fullscreen: true
conditions:
- condition: camera
cameras: [front_door]
- condition: fullscreen
fullscreen: true
actions:
- action: custom:advanced-camera-card-action
advanced_camera_card_action: substream_on
```
The flattened trigger list is an implicit OR. The retained `conditions:`
list is an implicit AND checked when any trigger fires.
### Trigger-only legacy conditions
Legacy `config` conditions become `config` triggers:
```yaml
# Before
automations:
- conditions:
- condition: config
paths: [menu.style]
actions:
- action: custom:advanced-camera-card-action
advanced_camera_card_action: status_bar
```
```yaml
# After, automatic
automations:
- triggers:
- trigger: config
paths: [menu.style]
actions:
- action: custom:advanced-camera-card-action
advanced_camera_card_action: status_bar
```
Trigger-only leaves are removed from retained `conditions:` blocks
because they no longer describe an ongoing state.
### `actions_not` to `if` / `then` / `else`
```yaml
# Before
automations:
- conditions:
- condition: state
entity_id: input_boolean.camera_alerts
state: 'on'
actions:
- action: custom:advanced-camera-card-action
advanced_camera_card_action: live
actions_not:
- action: none
```
```yaml
# After, automatic
automations:
- triggers:
- trigger: state
entity_id: input_boolean.camera_alerts
actions:
- if:
- condition: state
entity_id: input_boolean.camera_alerts
state: 'on'
then:
- action: custom:advanced-camera-card-action
advanced_camera_card_action: live
else:
- action: none
```
If the legacy automation had no conditions, or only trigger-only
conditions, `actions_not` is dropped because the old `else` branch could
not be reproduced as an ongoing predicate.
### Trigger template paths
```yaml
# Before
message: 'Door is {{ acc.trigger.state.to }} from {{ acc.trigger.state.from }}'
```
```yaml
# After, automatic
message: 'Door is {{ trigger.to_state.state }} from {{ trigger.from_state.state }}'
```
Path rewrites performed automatically:
| Old path | New path |
| -------------------------- | -------------------------- |
| `acc.trigger.state.entity` | `trigger.entity_id` |
| `acc.trigger.state.from` | `trigger.from_state.state` |
| `acc.trigger.state.to` | `trigger.to_state.state` |
| `acc.trigger.camera.from` | `trigger.from_acc.camera` |
| `acc.trigger.camera.to` | `trigger.to_acc.camera` |
| `acc.trigger.view.from` | `trigger.from_acc.view` |
| `acc.trigger.view.to` | `trigger.to_acc.view` |
| `acc.trigger.config.from` | `trigger.from_acc.config` |
| `acc.trigger.config.to` | `trigger.to_acc.config` |
The same rewrites are applied for the older
`advanced_camera_card.trigger.*` namespace.
### Ambient template namespace
Any remaining long-form ambient `advanced_camera_card.*` references
(outside the trigger surface) are rewritten to the `acc.*` alias:
```yaml
# Before
title: 'Now viewing {{ advanced_camera_card.camera }}'
```
```yaml
# After, automatic
title: 'Now viewing {{ acc.camera }}'
```
## Manual Migration Cases
### `__UPGRADE_FAILURE__.automations`
If a legacy automation cannot be converted faithfully, the original
automation is recorded under:
```yaml
__UPGRADE_FAILURE__:
automations:
- ...
```
These entries require manual migration.
The main known case is legacy `actions_not` with a condition whose
trigger can only fire on a rising edge, such as:
- `condition: template`
- `condition: screen`
- `condition: numeric_state` without an entity-backed state to watch
Those conditions can start the `then` branch, but cannot reliably start
the `else` branch when they stop matching.
### Unsupported HA conditions and triggers
This PR aligns the card with HA where supported, but it is not a full HA
automation engine.
Unsupported HA condition families include:
- `time`
- `zone`
- `sun`
- `location`
- `device`
- `condition: trigger`
Unsupported HA trigger platforms include:
- `event`
- `time`
- `time_pattern`
- `sun`
- `zone`
- `calendar`
- `webhook`
- `tag`
- `device`
- `mqtt`
The card-specific camera `triggers:` feature (which auto-selects and
wakes the card on camera events such as motion) is a separate feature
from automation `triggers:`, despite the shared word.
### Trigger IDs and variables
HA keys such as `id`, `alias`, and `variables` are accepted so pasted HA
YAML validates, but they are ignored by the card. There is no
`trigger.id` support in this PR.
## New Compatibility Features
This PR also makes card config more forgiving for HA-style YAML:
- `trigger`, `condition`, and `action` singular keys are accepted and
normalized to `triggers`, `conditions`, and `actions`.
- Single trigger, condition, and action objects are accepted where lists
are expected.
- `if`, `then`, and `else` accept a single item or a list.
- Composite condition shorthand is accepted:
- `{ and: [...] }`
- `{ or: [...] }`
- `{ not: [...] }`
- `{ condition: [...] }` as an implicit AND
- State conditions resolve expected state values that name another
entity, matching HA/Lovelace behavior.
- Both `entity` and `entity_id` are accepted on state and numeric
conditions and triggers (a superset of HA's two dialects), so there is
no forced rename.
- `state_not` remains supported as a card/Lovelace-friendly extension.
## Trigger Payloads
Automation action templates receive a top-level `trigger` object.
For stock `state` and `numeric_state` triggers:
```yaml
trigger.platform
trigger.entity_id
trigger.entity
trigger.from_state
trigger.to_state
```
For template triggers:
```yaml
trigger.platform
```
For card-specific triggers:
```yaml
trigger.platform # "acc"
trigger.type
trigger.from_acc
trigger.to_acc
```
The card does not currently expose HA's `id`, `idx`, `for`, `attribute`,
`above`, `below`, or `alias` trigger fields.
BREAKING CHANGE: Automations now follow Home Assistant's `triggers:` /
`conditions:` / `actions:` model. Automations require a `triggers:`
block and `conditions:` no longer wake an automation; `actions_not` is
removed in favour of an `if` / `then` / `else` action; the nested
`acc.trigger.*` template paths and the ambient `advanced_camera_card`
template namespace are removed (use the top-level `trigger.*` surface
and the `acc` alias); trigger-only condition forms (`config`, valueless
`camera` / `view` / `state`) are no longer valid conditions; and
template-condition vs template-trigger truthiness now follow HA.
Existing configs are upgraded automatically where a faithful conversion
exists; anything that cannot be converted is recorded under
`__UPGRADE_FAILURE__` for manual migration.
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
908 lines
28 KiB
TypeScript
908 lines
28 KiB
TypeScript
import { HassEntities, HassEntity, STATE_RUNNING } from 'home-assistant-js-websocket';
|
|
import { LitElement } from 'lit';
|
|
import screenfull from 'screenfull';
|
|
import { expect, vi } from 'vitest';
|
|
import { mock } from 'vitest-mock-extended';
|
|
import { Camera } from '../src/camera-manager/camera';
|
|
import { Capabilities } from '../src/camera-manager/capabilities';
|
|
import { CameraManagerEngine } from '../src/camera-manager/engine';
|
|
import {
|
|
FrigateEvent,
|
|
FrigateRecording,
|
|
FrigateReview,
|
|
} from '../src/camera-manager/frigate/types';
|
|
import { GenericCameraManagerEngine } from '../src/camera-manager/generic/engine-generic';
|
|
import { CameraManager } from '../src/camera-manager/manager';
|
|
import { CameraManagerStore } from '../src/camera-manager/store';
|
|
import {
|
|
CameraEventCallback,
|
|
EventQuery,
|
|
QueryType,
|
|
RecordingQuery,
|
|
ReviewQuery,
|
|
} from '../src/camera-manager/types';
|
|
import { ActionsManager } from '../src/card-controller/actions/actions-manager';
|
|
import { AutomationsManager } from '../src/card-controller/automations-manager';
|
|
import { CallManager } from '../src/card-controller/call/manager';
|
|
import { CameraTriggersManager } from '../src/card-controller/camera-triggers-manager';
|
|
import { CameraURLManager } from '../src/card-controller/camera-url-manager';
|
|
import {
|
|
CardElementManager,
|
|
CardHTMLElement,
|
|
} from '../src/card-controller/card-element-manager';
|
|
import { ConfigManager } from '../src/card-controller/config/config-manager';
|
|
import { CardController } from '../src/card-controller/controller';
|
|
import { DefaultManager } from '../src/card-controller/default-manager';
|
|
import { EffectsManager } from '../src/card-controller/effects/effects-manager';
|
|
import { ExpandManager } from '../src/card-controller/expand-manager';
|
|
import { FoldersManager } from '../src/card-controller/folders/manager';
|
|
import { FolderQuery } from '../src/card-controller/folders/types';
|
|
import { FullscreenManager } from '../src/card-controller/fullscreen/fullscreen-manager';
|
|
import { EventWatcherSubscriptionInterface } from '../src/card-controller/hass/event-watcher';
|
|
import { HASSManager } from '../src/card-controller/hass/hass-manager';
|
|
import { StateWatcherSubscriptionInterface } from '../src/card-controller/hass/state-watcher';
|
|
import { InitializationManager } from '../src/card-controller/initialization-manager';
|
|
import { InteractionManager } from '../src/card-controller/interaction-manager';
|
|
import { IssueManager } from '../src/card-controller/issues/issue-manager';
|
|
import { IssueStateManager } from '../src/card-controller/issues/state-manager';
|
|
import { KeyboardStateManager } from '../src/card-controller/keyboard-state-manager';
|
|
import { LockManager } from '../src/card-controller/lock/manager';
|
|
import { MediaLoadedInfoManager } from '../src/card-controller/media-info-manager';
|
|
import { MediaPlayerManager } from '../src/card-controller/media-player-manager';
|
|
import { MicrophoneManager } from '../src/card-controller/microphone-manager';
|
|
import { NotificationManager } from '../src/card-controller/notification-manager';
|
|
import { PIPManager } from '../src/card-controller/pip-manager';
|
|
import { QueryStringManager } from '../src/card-controller/query-string-manager';
|
|
import { StatusBarItemManager } from '../src/card-controller/status-bar-item-manager';
|
|
import { StyleManager } from '../src/card-controller/style-manager';
|
|
import { ViewItemManager } from '../src/card-controller/view/item-manager';
|
|
import { ViewManager } from '../src/card-controller/view/view-manager';
|
|
import { SubmenuInteraction, SubmenuItem } from '../src/components/submenu/types';
|
|
import { ConditionStateManager } from '../src/condition-trigger/conditions/state-manager';
|
|
import { CameraConfig, cameraConfigSchema } from '../src/config/schema/cameras';
|
|
import { FolderConfig } from '../src/config/schema/folders';
|
|
import {
|
|
PerformanceConfig,
|
|
performanceConfigSchema,
|
|
} from '../src/config/schema/performance';
|
|
import {
|
|
AdvancedCameraCardConfig,
|
|
advancedCameraCardConfigSchema,
|
|
} from '../src/config/schema/types';
|
|
import { RawAdvancedCameraCardConfig } from '../src/config/types';
|
|
import {
|
|
BrowseMedia,
|
|
BrowseMediaMetadata,
|
|
RichBrowseMedia,
|
|
} from '../src/ha/browse-media/types';
|
|
import { Device } from '../src/ha/registry/device/types';
|
|
import { Entity, EntityRegistryManager } from '../src/ha/registry/entity/types';
|
|
import { CurrentUser, HassStateDifference, HomeAssistant } from '../src/ha/types';
|
|
import { QuerySource } from '../src/query-source';
|
|
import { Severity } from '../src/severity';
|
|
import {
|
|
CapabilitiesRaw,
|
|
Interaction,
|
|
MediaLoadedInfo,
|
|
MediaLoadedInfoEventDetail,
|
|
} from '../src/types';
|
|
import {
|
|
EventViewMedia,
|
|
ReviewViewMedia,
|
|
ViewMedia,
|
|
ViewMediaType,
|
|
} from '../src/view/item';
|
|
import { QueryResults } from '../src/view/query-results';
|
|
import { ViewItemCapabilities } from '../src/view/types';
|
|
import { View, ViewParameters } from '../src/view/view';
|
|
|
|
export const createCameraConfig = (config?: unknown): CameraConfig => {
|
|
return cameraConfigSchema.parse(config ?? {});
|
|
};
|
|
|
|
export const createRawConfig = (
|
|
config?: Partial<RawAdvancedCameraCardConfig>,
|
|
): RawAdvancedCameraCardConfig => {
|
|
return {
|
|
type: 'advanced-camera-card',
|
|
cameras: [{}],
|
|
...config,
|
|
};
|
|
};
|
|
|
|
export const createConfig = (
|
|
config?: RawAdvancedCameraCardConfig,
|
|
): AdvancedCameraCardConfig => {
|
|
return advancedCameraCardConfigSchema.parse(createRawConfig(config));
|
|
};
|
|
|
|
export const createInitializedCamera = async (
|
|
config: CameraConfig,
|
|
engine: CameraManagerEngine,
|
|
capabilities?: Capabilities,
|
|
stateWatcher?: StateWatcherSubscriptionInterface,
|
|
): Promise<Camera> => {
|
|
const camera = new Camera(config, engine);
|
|
await camera.initialize({
|
|
hass: createHASS(),
|
|
stateWatcher: stateWatcher ?? mock<StateWatcherSubscriptionInterface>(),
|
|
eventWatcher: mock<EventWatcherSubscriptionInterface>(),
|
|
...(capabilities ? { capabilityOptions: { capabilities } } : {}),
|
|
});
|
|
return camera;
|
|
};
|
|
|
|
export const createHASS = (states?: HassEntities, user?: CurrentUser): HomeAssistant => {
|
|
const hass = mock<HomeAssistant>();
|
|
if (states) {
|
|
hass.states = states;
|
|
}
|
|
if (user) {
|
|
hass.user = user;
|
|
}
|
|
hass.config.components = [];
|
|
|
|
// Default to a fully-started HA so existing tests that don't care about
|
|
// startup state still represent a "ready" instance.
|
|
hass.config.state = STATE_RUNNING;
|
|
hass.connection.subscribeMessage = vi.fn();
|
|
hass.connection.subscribeEvents = vi.fn();
|
|
|
|
// ha-nunjucks calls sendMessagePromise to fetch label registry; return empty array to prevent crash.
|
|
hass.connection.sendMessagePromise = vi.fn().mockResolvedValue([]);
|
|
return hass;
|
|
};
|
|
|
|
export const createUser = (user?: Partial<CurrentUser>): CurrentUser => ({
|
|
id: 'user',
|
|
is_owner: false,
|
|
is_admin: false,
|
|
name: 'User',
|
|
credentials: [],
|
|
mfa_modules: [],
|
|
...user,
|
|
});
|
|
|
|
export const createRegistryDevice = (device?: Partial<Device>): Device => {
|
|
return {
|
|
id: device?.id ?? 'id',
|
|
model: device?.model ?? null,
|
|
config_entries: device?.config_entries ?? [],
|
|
manufacturer: device?.manufacturer ?? null,
|
|
};
|
|
};
|
|
|
|
export const createRegistryEntity = (entity?: Partial<Entity>): Entity => {
|
|
return {
|
|
config_entry_id: entity?.config_entry_id ?? null,
|
|
device_id: entity?.device_id ?? null,
|
|
disabled_by: entity?.disabled_by ?? null,
|
|
entity_id: entity?.entity_id ?? 'entity_id',
|
|
hidden_by: entity?.hidden_by ?? null,
|
|
platform: entity?.platform ?? 'platform',
|
|
translation_key: entity?.translation_key ?? null,
|
|
...(entity?.unique_id && { unique_id: entity?.unique_id }),
|
|
};
|
|
};
|
|
|
|
export const createStateEntity = (entity?: Partial<HassEntity>): HassEntity => {
|
|
return {
|
|
entity_id: entity?.entity_id ?? 'entity_id',
|
|
state: entity?.state ?? 'on',
|
|
last_changed: entity?.last_changed ?? 'never',
|
|
last_updated: entity?.last_updated ?? 'never',
|
|
attributes: entity?.attributes ?? {},
|
|
context: entity?.context ?? {
|
|
id: 'id',
|
|
parent_id: 'parent_id',
|
|
user_id: 'user_id',
|
|
},
|
|
};
|
|
};
|
|
|
|
export const createFrigateEvent = (event?: Partial<FrigateEvent>) => {
|
|
return {
|
|
camera: 'camera',
|
|
end_time: 1683397124,
|
|
false_positive: false,
|
|
has_clip: true,
|
|
has_snapshot: true,
|
|
id: '1683396875.643998-hmzrh5',
|
|
label: 'person',
|
|
sub_label: null,
|
|
start_time: 1683395000,
|
|
top_score: 0.841796875,
|
|
zones: [],
|
|
retain_indefinitely: false,
|
|
...event,
|
|
};
|
|
};
|
|
|
|
export const createFrigateRecording = (recording?: Partial<FrigateRecording>) => {
|
|
return {
|
|
cameraID: 'cameraID',
|
|
startTime: new Date('2023-04-29T14:00:00'),
|
|
endTime: new Date('2023-04-29T14:59:59'),
|
|
events: 42,
|
|
...recording,
|
|
};
|
|
};
|
|
|
|
export const createFrigateReview = (review?: Partial<FrigateReview>) => {
|
|
return {
|
|
id: 'review_id',
|
|
camera: 'camera',
|
|
severity: 'alert' as const,
|
|
start_time: 1683395000,
|
|
end_time: 1683397124,
|
|
thumb_path: 'thumb.jpg',
|
|
has_been_reviewed: false,
|
|
data: {
|
|
objects: ['person'],
|
|
zones: [],
|
|
audio: [],
|
|
},
|
|
...review,
|
|
};
|
|
};
|
|
|
|
export const createView = (options?: Partial<ViewParameters>): View => {
|
|
return new View({
|
|
view: 'live',
|
|
camera: 'camera',
|
|
...options,
|
|
});
|
|
};
|
|
|
|
export const createViewWithMedia = (options?: Partial<ViewParameters>): View => {
|
|
const media = generateViewMediaArray({ count: 5 });
|
|
return createView({
|
|
queryResults: new QueryResults({
|
|
results: media,
|
|
selectedIndex: 0,
|
|
}),
|
|
...options,
|
|
});
|
|
};
|
|
|
|
export const createStore = (
|
|
cameras?: {
|
|
cameraID: string;
|
|
engine?: CameraManagerEngine;
|
|
config?: CameraConfig;
|
|
capabilities?: Capabilities | null;
|
|
eventCallback?: CameraEventCallback;
|
|
}[],
|
|
): CameraManagerStore => {
|
|
const store = new CameraManagerStore();
|
|
for (const cameraProps of cameras ?? []) {
|
|
const eventCallback = cameraProps.eventCallback ?? vi.fn();
|
|
const capabilities =
|
|
cameraProps.capabilities === undefined
|
|
? createCapabilities()
|
|
: cameraProps.capabilities ?? undefined;
|
|
const camera = new Camera(
|
|
cameraProps.config ?? createCameraConfig(),
|
|
cameraProps.engine ??
|
|
new GenericCameraManagerEngine(
|
|
mock<StateWatcherSubscriptionInterface>(),
|
|
mock<EventWatcherSubscriptionInterface>(),
|
|
mock<EntityRegistryManager>(),
|
|
eventCallback,
|
|
),
|
|
{ eventCallback, capabilities },
|
|
);
|
|
camera.setID(cameraProps.cameraID);
|
|
store.addCamera(camera);
|
|
}
|
|
return store;
|
|
};
|
|
|
|
export const createCameraManager = (store?: CameraManagerStore): CameraManager => {
|
|
const cameraStore = store ?? createStore();
|
|
const cameraManager = mock<CameraManager>();
|
|
vi.mocked(cameraManager.getStore).mockReturnValue(cameraStore);
|
|
vi.mocked(cameraManager.getCameraCapabilities).mockImplementation(
|
|
(cameraID: string): Capabilities | null => {
|
|
return cameraStore.getCamera(cameraID)?.getCapabilities() ?? null;
|
|
},
|
|
);
|
|
|
|
return cameraManager;
|
|
};
|
|
|
|
export const createCapabilities = (capabilities?: CapabilitiesRaw): Capabilities => {
|
|
return new Capabilities({
|
|
'favorite-events': false,
|
|
'favorite-recordings': false,
|
|
'remote-control-entity': true,
|
|
clips: false,
|
|
live: false,
|
|
recordings: false,
|
|
seek: false,
|
|
snapshots: false,
|
|
...capabilities,
|
|
});
|
|
};
|
|
|
|
export const createMediaCapabilities = (
|
|
options?: Partial<ViewItemCapabilities>,
|
|
): ViewItemCapabilities => {
|
|
return {
|
|
canFavorite: false,
|
|
canDownload: false,
|
|
...options,
|
|
};
|
|
};
|
|
|
|
export const createMediaLoadedInfo = (
|
|
options?: Partial<MediaLoadedInfo>,
|
|
): MediaLoadedInfo => {
|
|
return {
|
|
width: 100,
|
|
height: 100,
|
|
targetID: 'target-1',
|
|
...options,
|
|
};
|
|
};
|
|
|
|
export const createMediaLoadedInfoEvent = (options?: {
|
|
info?: MediaLoadedInfo;
|
|
signal?: AbortSignal;
|
|
// When set, overrides `composedPath()` to return `[source]`. Use this for
|
|
// tests that hand the event directly to a handler (e.g. `handleLoadEvent`)
|
|
// instead of dispatching it; jsdom only populates `composedPath` on real
|
|
// dispatch.
|
|
source?: HTMLElement;
|
|
}): CustomEvent<MediaLoadedInfoEventDetail> => {
|
|
const ev = new CustomEvent<MediaLoadedInfoEventDetail>(
|
|
'advanced-camera-card:media:loaded',
|
|
{
|
|
bubbles: true,
|
|
composed: true,
|
|
detail: {
|
|
info: options?.info ?? createMediaLoadedInfo(),
|
|
signal: options?.signal ?? new AbortController().signal,
|
|
},
|
|
},
|
|
);
|
|
if (options?.source) {
|
|
Object.defineProperty(ev, 'composedPath', { value: () => [options.source] });
|
|
}
|
|
return ev;
|
|
};
|
|
|
|
export const createPerformanceConfig = (config: unknown): PerformanceConfig => {
|
|
return performanceConfigSchema.parse(config);
|
|
};
|
|
|
|
export const generateViewMediaArray = (options?: {
|
|
cameraIDs?: string[];
|
|
count?: number;
|
|
}): ViewMedia[] => {
|
|
const media: ViewMedia[] = [];
|
|
for (let i = 0; i < (options?.count ?? 100); ++i) {
|
|
for (const cameraID of options?.cameraIDs ?? ['kitchen', 'office']) {
|
|
media.push(
|
|
new TestViewMedia({
|
|
cameraID: cameraID,
|
|
id: `id-${cameraID}-${i}`,
|
|
}),
|
|
);
|
|
}
|
|
}
|
|
return media;
|
|
};
|
|
|
|
// ViewMedia itself has no native way to set startTime and ID that aren't linked
|
|
// to an engine.
|
|
export class TestViewMedia extends ViewMedia implements EventViewMedia, ReviewViewMedia {
|
|
private _icon: string | null = null;
|
|
private _id: string | null;
|
|
private _startTime: Date | null;
|
|
private _endTime: Date | null;
|
|
private _inProgress: boolean | null;
|
|
private _contentID: string | null;
|
|
private _title: string | null;
|
|
private _thumbnail: string | null;
|
|
private _what: string[] | null = null;
|
|
private _score: number | null = null;
|
|
private _tags: string[] | null = null;
|
|
private _where: string[] | null = null;
|
|
private _severity: Severity | null = null;
|
|
private _reviewed: boolean | null = null;
|
|
private _description: string | null = null;
|
|
private _favorite: boolean | null = null;
|
|
|
|
constructor(options?: {
|
|
id?: string | null;
|
|
startTime?: Date | null;
|
|
mediaType?: ViewMediaType;
|
|
cameraID?: string | null;
|
|
folder?: FolderConfig | null;
|
|
endTime?: Date | null;
|
|
inProgress?: boolean;
|
|
contentID?: string;
|
|
title?: string | null;
|
|
description?: string | null;
|
|
thumbnail?: string | null;
|
|
icon?: string | null;
|
|
what?: string[] | null;
|
|
score?: number | null;
|
|
tags?: string[] | null;
|
|
where?: string[] | null;
|
|
severity?: Severity | null;
|
|
reviewed?: boolean | null;
|
|
favorite?: boolean | null;
|
|
}) {
|
|
super(options?.mediaType ?? ViewMediaType.Clip, {
|
|
...(options?.cameraID !== null &&
|
|
!options?.folder && { cameraID: options?.cameraID ?? 'camera' }),
|
|
...(options?.folder && { folder: options.folder }),
|
|
});
|
|
this._id = options?.id !== undefined ? options.id : 'id';
|
|
this._startTime = options?.startTime ?? null;
|
|
this._endTime = options?.endTime ?? null;
|
|
this._inProgress = options?.inProgress !== undefined ? options.inProgress : false;
|
|
this._contentID = options?.contentID ?? null;
|
|
this._title = options?.title !== undefined ? options.title : null;
|
|
this._description = options?.description !== undefined ? options.description : null;
|
|
this._thumbnail = options?.thumbnail !== undefined ? options.thumbnail : null;
|
|
this._icon = options?.icon !== undefined ? options.icon : null;
|
|
this._what = options?.what !== undefined ? options.what : null;
|
|
this._score = options?.score !== undefined ? options.score : null;
|
|
this._tags = options?.tags !== undefined ? options.tags : null;
|
|
this._where = options?.where !== undefined ? options.where : null;
|
|
this._severity = options?.severity !== undefined ? options.severity : null;
|
|
this._reviewed = options?.reviewed !== undefined ? options.reviewed : null;
|
|
this._favorite = options?.favorite !== undefined ? options.favorite : null;
|
|
}
|
|
public getIcon(): string | null {
|
|
return this._icon;
|
|
}
|
|
public getID(): string | null {
|
|
return this._id;
|
|
}
|
|
public getStartTime(): Date | null {
|
|
return this._startTime;
|
|
}
|
|
public getEndTime(): Date | null {
|
|
return this._endTime;
|
|
}
|
|
public inProgress(): boolean | null {
|
|
return this._inProgress;
|
|
}
|
|
public getContentID(): string | null {
|
|
return this._contentID;
|
|
}
|
|
public getTitle(): string | null {
|
|
return this._title;
|
|
}
|
|
public getDescription(): string | null {
|
|
return this._description;
|
|
}
|
|
public getThumbnail(): string | null {
|
|
return this._thumbnail;
|
|
}
|
|
public getWhat(): string[] | null {
|
|
return this._what;
|
|
}
|
|
public getScore(): number | null {
|
|
return this._score;
|
|
}
|
|
public getTags(): string[] | null {
|
|
return this._tags;
|
|
}
|
|
public getWhere(): string[] | null {
|
|
return this._where;
|
|
}
|
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
public isGroupableWith(_that: EventViewMedia): boolean {
|
|
return false;
|
|
}
|
|
public getSeverity(): Severity | null {
|
|
return this._severity;
|
|
}
|
|
public isReviewed(): boolean | null {
|
|
return this._reviewed;
|
|
}
|
|
public setReviewed(reviewed: boolean): void {
|
|
this._reviewed = reviewed;
|
|
}
|
|
public isFavorite(): boolean | null {
|
|
return this._favorite;
|
|
}
|
|
public setFavorite(favorite: boolean): void {
|
|
this._favorite = favorite;
|
|
}
|
|
}
|
|
|
|
export const ResizeObserverMock = vi.fn(() => ({
|
|
disconnect: vi.fn(),
|
|
observe: vi.fn(),
|
|
unobserve: vi.fn(),
|
|
}));
|
|
|
|
export const IntersectionObserverMock = vi.fn(() => ({
|
|
disconnect: vi.fn(),
|
|
observe: vi.fn(),
|
|
unobserve: vi.fn(),
|
|
}));
|
|
|
|
export const MutationObserverMock = vi.fn(() => ({
|
|
disconnect: vi.fn(),
|
|
observe: vi.fn(),
|
|
unobserve: vi.fn(),
|
|
}));
|
|
|
|
export const requestAnimationFrameMock = (callback: FrameRequestCallback) => {
|
|
callback(new Date().getTime());
|
|
return 1;
|
|
};
|
|
|
|
export const getMockIntersectionObserver = (n = 0): IntersectionObserver | null => {
|
|
const mockResult = vi.mocked(IntersectionObserver).mock.results[n];
|
|
if (mockResult.type !== 'return') {
|
|
return null;
|
|
}
|
|
return mockResult.value;
|
|
};
|
|
|
|
export const callIntersectionHandler = async (
|
|
intersecting = true,
|
|
n = 0,
|
|
): Promise<void> => {
|
|
const observer = getMockIntersectionObserver(n);
|
|
if (!observer) {
|
|
return;
|
|
}
|
|
await (
|
|
vi.mocked(IntersectionObserver).mock.calls[n][0] as
|
|
| IntersectionObserverCallback
|
|
| ((_: unknown) => Promise<void>)
|
|
)(
|
|
// Note this is a very incomplete / invalid IntersectionObserverEntry that
|
|
// just provides the bare basics current implementation uses.
|
|
intersecting ? [{ isIntersecting: true } as IntersectionObserverEntry] : [],
|
|
observer,
|
|
);
|
|
};
|
|
|
|
export const callMutationHandler = async (n = 0): Promise<void> => {
|
|
const mockResult = vi.mocked(MutationObserver).mock.results[n];
|
|
if (mockResult.type !== 'return') {
|
|
return;
|
|
}
|
|
const observer = mockResult.value;
|
|
await (
|
|
vi.mocked(MutationObserver).mock.calls[n][0] as
|
|
| MutationCallback
|
|
| ((_: unknown) => Promise<void>)
|
|
)(
|
|
// Note this is a very incomplete / invalid IntersectionObserverEntry that
|
|
// just provides the bare basics current implementation uses.
|
|
[],
|
|
observer,
|
|
);
|
|
};
|
|
|
|
export const callVisibilityHandler = async (visible: boolean): Promise<void> => {
|
|
Object.defineProperty(document, 'visibilityState', {
|
|
value: visible ? 'visible' : 'hidden',
|
|
writable: true,
|
|
});
|
|
|
|
const mock = vi.mocked(global.document.addEventListener).mock;
|
|
for (const [evt, cb] of mock.calls) {
|
|
if (evt === 'visibilitychange' && typeof cb === 'function') {
|
|
await (cb as EventListener | ((_: unknown) => Promise<void>))(new Event('foo'));
|
|
}
|
|
}
|
|
};
|
|
|
|
export const getResizeObserver = (n = 0): ResizeObserver | null => {
|
|
const mockResult = vi.mocked(ResizeObserver).mock.results[n];
|
|
if (mockResult.type !== 'return') {
|
|
return null;
|
|
}
|
|
return mockResult.value;
|
|
};
|
|
|
|
export const callResizeHandler = (
|
|
entries: {
|
|
target: HTMLElement;
|
|
width: number;
|
|
height: number;
|
|
}[] = [],
|
|
n = 0,
|
|
): void => {
|
|
const observer = getResizeObserver(n);
|
|
if (!observer) {
|
|
return;
|
|
}
|
|
vi.mocked(ResizeObserver).mock.calls[n][0](
|
|
// Note this is a very incomplete / invalid ResizeObserverEntry that
|
|
// just provides the bare basics current implementation uses.
|
|
entries.map(
|
|
(entry) =>
|
|
({
|
|
target: entry.target,
|
|
contentRect: {
|
|
height: entry.height,
|
|
width: entry.width,
|
|
},
|
|
}) as unknown as ResizeObserverEntry,
|
|
),
|
|
observer,
|
|
);
|
|
};
|
|
|
|
export const createSlotHost = (options?: {
|
|
slot?: HTMLSlotElement;
|
|
children?: HTMLElement[];
|
|
parent?: LitElement;
|
|
}): LitElement => {
|
|
const parent = options?.parent ?? createLitElement();
|
|
parent.attachShadow({ mode: 'open' });
|
|
|
|
if (options?.slot) {
|
|
parent.shadowRoot?.append(options.slot);
|
|
}
|
|
if (options?.children) {
|
|
// Children will automatically be slotted into the default slot when it is
|
|
// created.
|
|
parent.append(...options.children);
|
|
}
|
|
return parent;
|
|
};
|
|
|
|
export const createSlot = (): HTMLSlotElement => {
|
|
return document.createElement('slot');
|
|
};
|
|
|
|
export const createParent = (options?: { children?: HTMLElement[] }): HTMLElement => {
|
|
const parent = document.createElement('div');
|
|
parent.append(...(options?.children ?? []));
|
|
return parent;
|
|
};
|
|
|
|
export const createCardHTMLElement = (): CardHTMLElement => {
|
|
const element = createLitElement() as CardHTMLElement;
|
|
element.getCardSize = vi.fn();
|
|
element.setConfig = vi.fn();
|
|
return element;
|
|
};
|
|
|
|
export const createLitElement = (): LitElement => {
|
|
const element = document.createElement('div') as unknown as LitElement;
|
|
element.addController = vi.fn();
|
|
element.removeController = vi.fn();
|
|
element.requestUpdate = vi.fn();
|
|
|
|
const promise: Promise<boolean> = new Promise((resolve) => {
|
|
resolve(false);
|
|
});
|
|
|
|
// Need to overwrite a read-only property.
|
|
Object.defineProperty(element, 'updateComplete', {
|
|
value: promise,
|
|
});
|
|
return element;
|
|
};
|
|
|
|
export const createCardAPI = (): CardController => {
|
|
const api = mock<CardController>();
|
|
|
|
api.getActionsManager.mockReturnValue(mock<ActionsManager>());
|
|
api.getAutomationsManager.mockReturnValue(mock<AutomationsManager>());
|
|
api.getCallManager.mockReturnValue(mock<CallManager>());
|
|
api.getDefaultManager.mockReturnValue(mock<DefaultManager>());
|
|
api.getCameraManager.mockReturnValue(mock<CameraManager>());
|
|
api.getCameraURLManager.mockReturnValue(mock<CameraURLManager>());
|
|
api.getCardElementManager.mockReturnValue(mock<CardElementManager>());
|
|
api.getConditionStateManager.mockReturnValue(mock<ConditionStateManager>());
|
|
api.getConfigManager.mockReturnValue(mock<ConfigManager>());
|
|
api.getEffectsManager.mockReturnValue(mock<EffectsManager>());
|
|
api.getEntityRegistryManager.mockReturnValue(mock<EntityRegistryManager>());
|
|
api.getExpandManager.mockReturnValue(mock<ExpandManager>());
|
|
api.getFoldersManager.mockReturnValue(mock<FoldersManager>());
|
|
api.getFullscreenManager.mockReturnValue(mock<FullscreenManager>());
|
|
api.getHASSManager.mockReturnValue(mock<HASSManager>());
|
|
api.getInitializationManager.mockReturnValue(mock<InitializationManager>());
|
|
api.getInteractionManager.mockReturnValue(mock<InteractionManager>());
|
|
api.getKeyboardStateManager.mockReturnValue(mock<KeyboardStateManager>());
|
|
api.getLockManager.mockReturnValue(mock<LockManager>());
|
|
api.getMediaLoadedInfoManager.mockReturnValue(mock<MediaLoadedInfoManager>());
|
|
api.getMediaPlayerManager.mockReturnValue(mock<MediaPlayerManager>());
|
|
api.getMicrophoneManager.mockReturnValue(mock<MicrophoneManager>());
|
|
api.getNotificationManager.mockReturnValue(mock<NotificationManager>());
|
|
api.getPIPManager.mockReturnValue(mock<PIPManager>());
|
|
|
|
const issueManager = mock<IssueManager>();
|
|
issueManager.getStateManager.mockReturnValue(mock<IssueStateManager>());
|
|
api.getIssueManager.mockReturnValue(issueManager);
|
|
|
|
api.getQueryStringManager.mockReturnValue(mock<QueryStringManager>());
|
|
api.getStatusBarItemManager.mockReturnValue(mock<StatusBarItemManager>());
|
|
api.getStyleManager.mockReturnValue(mock<StyleManager>());
|
|
api.getCameraTriggersManager.mockReturnValue(mock<CameraTriggersManager>());
|
|
api.getViewItemManager.mockReturnValue(mock<ViewItemManager>());
|
|
api.getViewManager.mockReturnValue(mock<ViewManager>());
|
|
|
|
return api;
|
|
};
|
|
|
|
export const callStateWatcherCallback = (
|
|
stateWatcher: StateWatcherSubscriptionInterface,
|
|
diff: HassStateDifference,
|
|
n = 0,
|
|
): void => {
|
|
const mock = vi.mocked(stateWatcher.subscribe).mock;
|
|
expect(mock.calls.length).greaterThan(n);
|
|
mock.calls[n][0](diff);
|
|
};
|
|
|
|
export const callEventWatcherCallback = (
|
|
eventWatcher: EventWatcherSubscriptionInterface,
|
|
data: unknown,
|
|
n = 0,
|
|
): void => {
|
|
const mock = vi.mocked(eventWatcher.subscribe).mock;
|
|
expect(mock.calls.length).greaterThan(n);
|
|
mock.calls[n][1].callback(data);
|
|
};
|
|
|
|
/**
|
|
* Flush resolved promises.
|
|
*/
|
|
export const flushPromises = async (): Promise<void> => {
|
|
await new Promise(process.nextTick);
|
|
};
|
|
|
|
export const createInteractionActionEvent = (
|
|
action: string,
|
|
): CustomEvent<Interaction> => {
|
|
return new CustomEvent<Interaction>('@action', {
|
|
detail: {
|
|
action: action,
|
|
},
|
|
});
|
|
};
|
|
|
|
export const createSubmenuInteractionActionEvent = (
|
|
action: string,
|
|
item: SubmenuItem,
|
|
): CustomEvent<SubmenuInteraction> => {
|
|
return new CustomEvent<SubmenuInteraction>('@action', {
|
|
detail: {
|
|
action,
|
|
item,
|
|
},
|
|
});
|
|
};
|
|
|
|
export const setScreenfulEnabled = (enabled: boolean): void => {
|
|
Object.defineProperty(screenfull, 'isEnabled', { value: enabled, writable: true });
|
|
};
|
|
|
|
export const createTouch = (touch?: Partial<Touch>): Touch => ({
|
|
clientX: touch?.clientX ?? 0,
|
|
clientY: touch?.clientY ?? 0,
|
|
force: touch?.force ?? 0,
|
|
identifier: touch?.identifier ?? 0,
|
|
pageX: touch?.pageX ?? 0,
|
|
pageY: touch?.pageY ?? 0,
|
|
radiusX: touch?.radiusX ?? 0,
|
|
radiusY: touch?.radiusY ?? 0,
|
|
rotationAngle: touch?.rotationAngle ?? 0,
|
|
screenX: touch?.screenX ?? 0,
|
|
screenY: touch?.screenY ?? 0,
|
|
target: touch?.target ?? document.createElement('div'),
|
|
});
|
|
|
|
export const createTouchEvent = (
|
|
type: string,
|
|
options?: { touches?: Touch[]; changedTouches?: Touch[] },
|
|
): TouchEvent => {
|
|
return new TouchEvent(type, {
|
|
bubbles: false,
|
|
touches: options?.touches,
|
|
changedTouches: options?.changedTouches,
|
|
});
|
|
};
|
|
|
|
export const createFolder = (config?: Partial<FolderConfig>): FolderConfig => {
|
|
return {
|
|
type: 'ha',
|
|
id: crypto.randomUUID(),
|
|
ha: {
|
|
path: [{ id: 'media-source://' }],
|
|
},
|
|
...config,
|
|
};
|
|
};
|
|
|
|
export const createBrowseMedia = (media?: Partial<BrowseMedia>): BrowseMedia => {
|
|
return {
|
|
title: 'Test Media',
|
|
media_class: 'video',
|
|
media_content_type: 'video/mp4',
|
|
media_content_id: 'content_id',
|
|
can_play: true,
|
|
can_expand: false,
|
|
thumbnail: null,
|
|
children: null,
|
|
...media,
|
|
};
|
|
};
|
|
|
|
export const createRichBrowseMedia = (
|
|
media?: Partial<RichBrowseMedia<BrowseMediaMetadata>>,
|
|
): RichBrowseMedia<BrowseMediaMetadata> => {
|
|
return {
|
|
...createBrowseMedia(media),
|
|
_metadata: media?._metadata ?? {
|
|
cameraID: 'camera.test',
|
|
startDate: new Date('2024-11-19T07:23:00'),
|
|
endDate: new Date('2025-11-19T07:24:00'),
|
|
},
|
|
};
|
|
};
|
|
|
|
export const createEventQuery = (
|
|
cameraID: string,
|
|
options?: Partial<EventQuery>,
|
|
): EventQuery => ({
|
|
source: QuerySource.Camera,
|
|
type: QueryType.Event,
|
|
cameraIDs: new Set([cameraID]),
|
|
...options,
|
|
});
|
|
|
|
export const createReviewQuery = (
|
|
cameraID: string,
|
|
options?: Partial<ReviewQuery>,
|
|
): ReviewQuery => ({
|
|
source: QuerySource.Camera,
|
|
type: QueryType.Review,
|
|
cameraIDs: new Set([cameraID]),
|
|
...options,
|
|
});
|
|
|
|
export const createRecordingQuery = (
|
|
cameraID: string,
|
|
options?: Partial<RecordingQuery>,
|
|
): RecordingQuery => ({
|
|
source: QuerySource.Camera,
|
|
type: QueryType.Recording,
|
|
cameraIDs: new Set([cameraID]),
|
|
...options,
|
|
});
|
|
|
|
export const createFolderQuery = (folderId: string): FolderQuery => ({
|
|
source: QuerySource.Folder,
|
|
folder: { id: folderId, type: 'ha', title: folderId },
|
|
path: [{ ha: { id: 'Root' } }],
|
|
});
|
|
|
|
export const isEventQuery = (node: {
|
|
source: QuerySource;
|
|
type?: QueryType;
|
|
}): node is EventQuery =>
|
|
node.source === QuerySource.Camera && node.type === QueryType.Event;
|
|
|
|
export const isRecordingQuery = (node: {
|
|
source: QuerySource;
|
|
type?: QueryType;
|
|
}): node is RecordingQuery =>
|
|
node.source === QuerySource.Camera && node.type === QueryType.Recording;
|
|
|
|
export const isReviewQuery = (node: {
|
|
source: QuerySource;
|
|
type?: QueryType;
|
|
}): node is ReviewQuery =>
|
|
node.source === QuerySource.Camera && node.type === QueryType.Review;
|
|
|
|
export const isFolderQuery = (node: { source: QuerySource }): node is FolderQuery =>
|
|
node.source === QuerySource.Folder;
|