mirror of
https://github.com/home-assistant/frontend.git
synced 2026-11-23 13:18:54 +00:00
Compare commits
23
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cfff997772 | ||
|
|
3c0c71ad87 | ||
|
|
d5bd510be0 | ||
|
|
0b3fe09897 | ||
|
|
12aee79264 | ||
|
|
4a195b8c26 | ||
|
|
fb4ccedd9a | ||
|
|
3121faf81b | ||
|
|
5685ec73a6 | ||
|
|
68238fcc0b | ||
|
|
cc923acaab | ||
|
|
1d76e0b241 | ||
|
|
fa6bcf39ed | ||
|
|
a630038932 | ||
|
|
418d83e728 | ||
|
|
74cc4a0904 | ||
|
|
c87c6aa737 | ||
|
|
921e3258c7 | ||
|
|
c1bec10ec4 | ||
|
|
e3a1cec8ea | ||
|
|
b50fbc985c | ||
|
|
3eb346abab | ||
|
|
26c6ee9afd |
No files matched your search
@@ -96,14 +96,17 @@ html`
|
||||
Pick the indicator by what is loading, following the [Loading pattern](https://contributors.home-assistant.io/design/patterns/loading/):
|
||||
|
||||
- Use a skeleton from `src/components/skeleton/` (`ha-skeleton`, `ha-skeleton-text`, `ha-skeleton-icon`) when content loads into a layout you already know, such as table rows, tile text, or a log. It holds the layout, so nothing jumps when the content arrives.
|
||||
- Use `ha-skeleton-overlay` when the content renders before its data arrives, such as a card or badge, or when content reloads over what's already shown. See below.
|
||||
- Use `ha-spinner` only when a whole area loads and its shape is unknown.
|
||||
- Use `ha-button` with `loading`, or `ha-progress-button`, for an action started from a button. Don't put a separate spinner next to it.
|
||||
|
||||
Every skeleton uses the same soft wave (`ha-skeleton`'s default `effect="sheen"`). It's one slanted wave across all the skeletons on the page, from the top corner of the content on the side text starts from to the opposite bottom corner, which each skeleton shows its slice of, on one shared clock. It flows from one skeleton into the next, starts its next sweep as soon as it leaves the content, and a skeleton added mid-sweep joins in rather than starting over. Don't change the effect or speed (`--ha-skeleton-duration`) for one component.
|
||||
|
||||
Wrap the indicator in `ha-fade-in` from `src/components/animation/ha-fade-in.ts`:
|
||||
|
||||
- Fade a skeleton in straight away over about 300ms (`.duration=${300}`), as the data table does. It stands in for the content, so a delay would leave an empty gap.
|
||||
- Delay a spinner or progress bar, usually by `.delay=${500}`, so a load that finishes within that time never flashes it. Some slower areas, such as backups and updates, use `${1000}`.
|
||||
- Don't fade in the loaded content itself.
|
||||
- Content that takes a skeleton's place fades in over `--ha-animation-duration-fast`, which reduced motion makes instant. `ha-skeleton-overlay` does this for you. Elsewhere, use `skeletonOr(loading, skeleton, () => content)` from `src/components/skeleton/skeleton-arrival.ts`: it shows the skeleton while loading and fades the content in once when it replaces it, but not where no skeleton showed, such as table rows made as the table scrolls. Put text in an element of its own inside the content, as only elements fade. For content that fills in where it already is, such as a log, call `fadeInArrival(element)` once when its skeleton goes. Don't add any other fade to loaded content.
|
||||
|
||||
Give a skeleton group the `progressbar` role and a translated label, as `ha-spinner` has, rather than visible "Loading" text. A loading state always ends in the content, an empty state, or an error.
|
||||
|
||||
@@ -121,6 +124,27 @@ html`
|
||||
`;
|
||||
```
|
||||
|
||||
### Skeleton overlay
|
||||
|
||||
`ha-skeleton-overlay` reads a skeleton from the content it wraps, so it can't drift from it: each text line, icon, image, control and drawing gets its own piece, and the real parts are hidden underneath until loading ends.
|
||||
|
||||
```ts
|
||||
html`
|
||||
<ha-skeleton-overlay .loading=${this._loading}>
|
||||
<my-content></my-content>
|
||||
</ha-skeleton-overlay>
|
||||
`;
|
||||
```
|
||||
|
||||
- Turn it on with `loading`, or fire `skeleton-loading` (`{ loading: true }`, later `{ loading: false }`) from inside the content. The event stops at the nearest overlay, so content doesn't need to know what wraps it. In a Lit component, add a `SkeletonLoadingController` from `src/components/skeleton/skeleton-loading-controller.ts` with a function that says whether it's loading, and it fires the events for you.
|
||||
- `hui-card` and `hui-badge` already wrap every card and badge in an overlay, and show a plain wave while the card's code loads. A card that fetches data only needs a `SkeletonLoadingController`, as `hui-calendar-card` and the history and statistics charts do. Energy cards pass `loading` to `EnergyCollectionController` instead, for when they fetch more after the collection's data arrives.
|
||||
- Give the overlay a `skeleton-key` and it remembers how tall the content was once loaded, then holds that height next time. `hui-card` sets one from the card's config. For other content, make one with `skeletonKey()` from `src/components/skeleton/skeleton-sizes.ts`.
|
||||
- For the first visit, render placeholders as big as the content will be, so it doesn't jump when the data arrives. Set `loading` on `ha-chart-base` to have the chart read as one block and its legend as one line, or as its items when the legend has them already. Before a chart exists, use `chartPlaceholderStyles` from `src/components/chart/chart-placeholder.ts`. Lists of a known length, such as the to-do list from its entity's state, draw that many hidden rows. Energy cards whose layout follows the energy preferences, such as the sources table and the devices detail graph, can draw it from `EnergyCollectionController.placeholderData` until their data comes.
|
||||
- Mark parts that shouldn't be read with `data-skeleton`: `none` leaves an element out and showing, `keep` leaves it showing but reads what's inside, and `text`, `round` or `block` force one piece of that kind. Skeletons the content draws itself are left alone.
|
||||
- Put your own skeleton in the `skeleton` slot to replace the reading altogether.
|
||||
- Call `refresh()` when the content changes without changing size.
|
||||
- It gives the skeleton the `progressbar` role and the translated label itself.
|
||||
|
||||
## Shortcuts And Tooltips
|
||||
|
||||
Use `ShortcutManager` from `src/common/keyboard/shortcuts.ts` for keyboard shortcuts. It blocks shortcuts in input fields, can prevent shortcuts during text selection, and supports character and KeyCode shortcuts for non-latin keyboards. See `src/state/quick-bar-mixin.ts` for global shortcut examples.
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
title: Card skeletons
|
||||
subtitle: How a dashboard looks while its cards and badges load
|
||||
---
|
||||
|
||||
Each card and badge sits in an `ha-skeleton-overlay`, which reads a skeleton from what the card or badge draws: every name, state and value gets its own text skeleton, and icons, images, controls and drawings get their own pieces. When loading ends, each part fades in. Turn off **Loading** to see the real cards, or use **Simulate loading** to watch them arrive one by one.
|
||||
@@ -0,0 +1,440 @@
|
||||
import type { PropertyValues, TemplateResult } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
import { mockIcons } from "../../../../demo/src/stubs/icons";
|
||||
import type { HASSDomTargetEvent } from "../../../../src/common/dom/fire_event";
|
||||
import { fireEvent } from "../../../../src/common/dom/fire_event";
|
||||
import "../../../../src/components/ha-button";
|
||||
import "../../../../src/components/ha-switch";
|
||||
import type { HaSwitch } from "../../../../src/components/ha-switch";
|
||||
import { LightColorMode } from "../../../../src/data/light";
|
||||
import type { LovelaceBadgeConfig } from "../../../../src/data/lovelace/config/badge";
|
||||
import type { LovelaceCardConfig } from "../../../../src/data/lovelace/config/card";
|
||||
import { provideHass } from "../../../../src/fake_data/provide_hass";
|
||||
import "../../../../src/panels/lovelace/badges/hui-badge";
|
||||
import type { HuiBadge } from "../../../../src/panels/lovelace/badges/hui-badge";
|
||||
import "../../../../src/panels/lovelace/cards/hui-card";
|
||||
import type { HuiCard } from "../../../../src/panels/lovelace/cards/hui-card";
|
||||
import { computeCardGridSize } from "../../../../src/panels/lovelace/common/compute-card-grid-size";
|
||||
import type { HomeAssistant } from "../../../../src/types";
|
||||
import "../../ha-demo-options";
|
||||
|
||||
const ENTITIES = [
|
||||
{
|
||||
entity_id: "light.bed_light",
|
||||
state: "on",
|
||||
attributes: {
|
||||
friendly_name: "Bed light",
|
||||
supported_color_modes: [LightColorMode.BRIGHTNESS],
|
||||
color_mode: LightColorMode.BRIGHTNESS,
|
||||
brightness: 180,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "light.kitchen_lights",
|
||||
state: "on",
|
||||
attributes: { friendly_name: "Kitchen lights" },
|
||||
},
|
||||
{
|
||||
entity_id: "switch.tv_outlet",
|
||||
state: "off",
|
||||
attributes: { friendly_name: "TV outlet", device_class: "outlet" },
|
||||
},
|
||||
{
|
||||
entity_id: "media_player.living_room",
|
||||
state: "playing",
|
||||
attributes: { friendly_name: "Living room speaker" },
|
||||
},
|
||||
{
|
||||
entity_id: "climate.thermostat",
|
||||
state: "heat",
|
||||
attributes: {
|
||||
friendly_name: "Thermostat",
|
||||
current_temperature: 21,
|
||||
temperature: 22,
|
||||
hvac_modes: ["heat", "off"],
|
||||
hvac_action: "heating",
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "lock.front_door",
|
||||
state: "locked",
|
||||
attributes: { friendly_name: "Front door" },
|
||||
},
|
||||
{
|
||||
entity_id: "person.paulus",
|
||||
state: "home",
|
||||
attributes: {
|
||||
friendly_name: "Paulus",
|
||||
entity_picture: "/images/paulus.jpg",
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "sensor.living_room_temperature",
|
||||
state: "21.4",
|
||||
attributes: {
|
||||
friendly_name: "Living room temperature",
|
||||
device_class: "temperature",
|
||||
unit_of_measurement: "°C",
|
||||
state_class: "measurement",
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "sensor.living_room_humidity",
|
||||
state: "54",
|
||||
attributes: {
|
||||
friendly_name: "Living room humidity",
|
||||
device_class: "humidity",
|
||||
unit_of_measurement: "%",
|
||||
state_class: "measurement",
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "binary_sensor.back_door",
|
||||
state: "off",
|
||||
attributes: { friendly_name: "Back door", device_class: "door" },
|
||||
},
|
||||
{
|
||||
entity_id: "camera.garden",
|
||||
state: "idle",
|
||||
attributes: { friendly_name: "Garden" },
|
||||
},
|
||||
];
|
||||
|
||||
/* The badges row at the top of a sections view */
|
||||
const BADGES: LovelaceBadgeConfig[] = [
|
||||
{ type: "entity", entity: "person.paulus", show_entity_picture: true },
|
||||
{ type: "entity", entity: "sensor.living_room_temperature" },
|
||||
{ type: "entity", entity: "light.kitchen_lights", show_name: true },
|
||||
{ type: "entity", entity: "lock.front_door", color: "green" },
|
||||
{
|
||||
type: "entity",
|
||||
entity: "binary_sensor.back_door",
|
||||
show_name: true,
|
||||
show_state: false,
|
||||
},
|
||||
];
|
||||
|
||||
const SECTIONS: LovelaceCardConfig[][] = [
|
||||
[
|
||||
{
|
||||
type: "heading",
|
||||
heading: "Living room",
|
||||
badges: [
|
||||
{ type: "entity", entity: "sensor.living_room_temperature" },
|
||||
{ type: "entity", entity: "sensor.living_room_humidity" },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "tile",
|
||||
entity: "light.bed_light",
|
||||
features: [{ type: "light-brightness" }],
|
||||
},
|
||||
{ type: "tile", entity: "switch.tv_outlet" },
|
||||
{ type: "tile", entity: "media_player.living_room" },
|
||||
{ type: "tile", entity: "climate.thermostat", vertical: true },
|
||||
{ type: "tile", entity: "lock.front_door", vertical: true },
|
||||
{ type: "entity", entity: "sensor.living_room_temperature" },
|
||||
{ type: "entity", entity: "sensor.living_room_humidity" },
|
||||
],
|
||||
[
|
||||
{ type: "heading", heading: "Cameras" },
|
||||
{ type: "picture-entity", entity: "camera.garden" },
|
||||
{
|
||||
type: "picture-glance",
|
||||
title: "Kitchen",
|
||||
image: "/images/kitchen.png",
|
||||
entities: [
|
||||
"light.kitchen_lights",
|
||||
"switch.tv_outlet",
|
||||
"binary_sensor.back_door",
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "picture-entity",
|
||||
image: "/images/bed.png",
|
||||
entity: "light.bed_light",
|
||||
},
|
||||
],
|
||||
[
|
||||
{ type: "heading", heading: "Overview" },
|
||||
{ type: "tile", entity: "person.paulus" },
|
||||
{ type: "tile", entity: "binary_sensor.back_door" },
|
||||
{
|
||||
type: "entities",
|
||||
title: "Climate",
|
||||
entities: [
|
||||
"climate.thermostat",
|
||||
"sensor.living_room_temperature",
|
||||
"sensor.living_room_humidity",
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "glance",
|
||||
title: "Doors and lights",
|
||||
entities: [
|
||||
"lock.front_door",
|
||||
"binary_sensor.back_door",
|
||||
"light.kitchen_lights",
|
||||
],
|
||||
},
|
||||
{ type: "gauge", entity: "sensor.living_room_humidity" },
|
||||
],
|
||||
];
|
||||
|
||||
interface DemoSlot {
|
||||
key: string;
|
||||
card: HuiCard;
|
||||
}
|
||||
|
||||
interface BadgeSlot {
|
||||
key: string;
|
||||
badge: HuiBadge;
|
||||
}
|
||||
|
||||
@customElement("demo-lovelace-card-skeletons")
|
||||
class DemoCardSkeletons extends LitElement {
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
@state() private _loaded = new Set<string>();
|
||||
|
||||
@state() private _simulating = false;
|
||||
|
||||
private _sections: DemoSlot[][] = [];
|
||||
|
||||
private _badges: BadgeSlot[] = [];
|
||||
|
||||
private _timers: number[] = [];
|
||||
|
||||
/* Whether each card or badge was last told it's loading */
|
||||
private _loadingShown = new WeakMap<Element, boolean>();
|
||||
|
||||
protected firstUpdated(changedProperties: PropertyValues<this>) {
|
||||
super.firstUpdated(changedProperties);
|
||||
const hass = provideHass(this);
|
||||
hass.updateTranslations(null, "en");
|
||||
hass.updateTranslations("lovelace", "en");
|
||||
hass.addEntities(ENTITIES);
|
||||
mockIcons(hass);
|
||||
// Camera snapshots come from a signed path; point it at a gallery image.
|
||||
hass.mockWS("auth/sign_path", () => ({
|
||||
path: "/images/office.jpg?authSig=gallery",
|
||||
}));
|
||||
}
|
||||
|
||||
public disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
this._clearTimers();
|
||||
}
|
||||
|
||||
protected willUpdate(changedProperties: PropertyValues<this>) {
|
||||
if (!changedProperties.has("hass") || !this.hass) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._sections.length === 0) {
|
||||
this._sections = SECTIONS.map((cards, sectionIndex) =>
|
||||
cards.map((config, cardIndex) => {
|
||||
const card = document.createElement("hui-card");
|
||||
card.layout = "grid";
|
||||
card.config = config;
|
||||
|
||||
return { key: `${sectionIndex}-${cardIndex}`, card };
|
||||
})
|
||||
);
|
||||
this._badges = BADGES.map((config, index) => {
|
||||
const badge = document.createElement("hui-badge");
|
||||
badge.config = config;
|
||||
|
||||
return { key: `badge-${index}`, badge };
|
||||
});
|
||||
}
|
||||
|
||||
this._elements().forEach(({ element }) => {
|
||||
element.hass = this.hass;
|
||||
});
|
||||
}
|
||||
|
||||
/* Every card and badge, as one list to measure and reveal */
|
||||
private _elements() {
|
||||
return [
|
||||
...this._badges.map(({ key, badge }) => ({ key, element: badge })),
|
||||
...this._sections.flat().map(({ key, card }) => ({ key, element: card })),
|
||||
];
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this.hass) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
return html`
|
||||
<ha-demo-options>
|
||||
<ha-switch
|
||||
.checked=${this._loaded.size === 0}
|
||||
.disabled=${this._simulating}
|
||||
@change=${this._loadingToggled}
|
||||
></ha-switch>
|
||||
<span>Loading</span>
|
||||
<ha-button
|
||||
size="s"
|
||||
appearance="filled"
|
||||
.disabled=${this._simulating}
|
||||
@click=${this._simulate}
|
||||
>
|
||||
Simulate loading
|
||||
</ha-button>
|
||||
</ha-demo-options>
|
||||
<div class="badges">${this._badges.map(({ badge }) => badge)}</div>
|
||||
<div class="view">
|
||||
${this._sections.map(
|
||||
(slots) => html`
|
||||
<div class="section">
|
||||
${slots.map((slot) => this._renderSlot(slot))}
|
||||
</div>
|
||||
`
|
||||
)}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private _renderSlot({ card }: DemoSlot): TemplateResult {
|
||||
const { rows, columns } = computeCardGridSize(card.getGridOptions());
|
||||
const fitRows = rows !== "auto";
|
||||
const fullWidth = columns === "full";
|
||||
|
||||
return html`
|
||||
<div
|
||||
class="card ${classMap({
|
||||
"fit-rows": fitRows,
|
||||
"full-width": fullWidth,
|
||||
})}"
|
||||
style=${styleMap({
|
||||
"--column-size": fullWidth ? undefined : columns,
|
||||
"--row-size": fitRows ? rows : undefined,
|
||||
})}
|
||||
>
|
||||
${card}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
protected updated(changedProperties: PropertyValues<this>) {
|
||||
super.updated(changedProperties);
|
||||
// A card or badge makes its content when it first updates
|
||||
this._elements().forEach(async ({ key, element }) => {
|
||||
await element.updateComplete;
|
||||
this._setLoading(element, !this._loaded.has(key));
|
||||
});
|
||||
}
|
||||
|
||||
/* Each card and badge already sits in its own skeleton overlay. Say it's
|
||||
loading from inside, as a card waiting on its data does. */
|
||||
private _setLoading(wrapper: HuiCard | HuiBadge, loading: boolean) {
|
||||
const content = wrapper.querySelector(":scope > ha-skeleton-overlay > *");
|
||||
|
||||
if (
|
||||
!(content instanceof HTMLElement) ||
|
||||
this._loadingShown.get(content) === loading
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._loadingShown.set(content, loading);
|
||||
fireEvent(content, "skeleton-loading", { loading });
|
||||
}
|
||||
|
||||
private _keys(): string[] {
|
||||
return this._elements().map(({ key }) => key);
|
||||
}
|
||||
|
||||
private _loadingToggled(ev: HASSDomTargetEvent<HaSwitch>) {
|
||||
this._clearTimers();
|
||||
this._loaded = ev.target.checked ? new Set() : new Set(this._keys());
|
||||
}
|
||||
|
||||
private _simulate() {
|
||||
this._clearTimers();
|
||||
this._loaded = new Set();
|
||||
this._simulating = true;
|
||||
const keys = this._keys();
|
||||
keys.forEach((key) => {
|
||||
const delay = 600 + Math.random() * 2400;
|
||||
this._timers.push(
|
||||
window.setTimeout(() => {
|
||||
this._loaded = new Set(this._loaded).add(key);
|
||||
|
||||
if (this._loaded.size === keys.length) {
|
||||
this._simulating = false;
|
||||
}
|
||||
}, delay)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
private _clearTimers() {
|
||||
this._timers.forEach((timer) => clearTimeout(timer));
|
||||
this._timers = [];
|
||||
this._simulating = false;
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
ha-demo-options {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--ha-space-2);
|
||||
}
|
||||
ha-demo-options ha-button {
|
||||
margin-inline-start: var(--ha-space-4);
|
||||
}
|
||||
.view {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
|
||||
gap: var(--ha-space-8);
|
||||
padding: var(--ha-space-4);
|
||||
background-color: var(--primary-background-color);
|
||||
align-items: start;
|
||||
}
|
||||
.section {
|
||||
--row-gap: 8px;
|
||||
--column-gap: 8px;
|
||||
--row-height: 56px;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(12, minmax(0, 1fr));
|
||||
grid-auto-rows: auto;
|
||||
row-gap: var(--row-gap);
|
||||
column-gap: var(--column-gap);
|
||||
}
|
||||
.card {
|
||||
grid-row: span var(--row-size, 1);
|
||||
grid-column: span min(var(--column-size, 12), 12);
|
||||
}
|
||||
.card.fit-rows {
|
||||
height: calc(
|
||||
(var(--row-size, 1) * (var(--row-height) + var(--row-gap))) - var(
|
||||
--row-gap
|
||||
)
|
||||
);
|
||||
}
|
||||
.card.full-width {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
/* As hui-view-badges lays out the badges row */
|
||||
.badges {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
gap: var(--ha-space-2);
|
||||
padding: var(--ha-space-4) var(--ha-space-4) 0;
|
||||
background-color: var(--primary-background-color);
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"demo-lovelace-card-skeletons": DemoCardSkeletons;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,549 @@
|
||||
/**
|
||||
* Read a skeleton from rendered content, such as a dashboard card: where its
|
||||
* text lines, icons, images, controls and drawings are, inside shadow roots
|
||||
* too. The content stays the source of truth for layout, so the skeleton
|
||||
* can't drift from it.
|
||||
*
|
||||
* Any element can say how it's read with a `data-skeleton` attribute:
|
||||
* - `text`, `round` or `block`: one piece of that kind, the size of the element
|
||||
* - `none`: left out and left showing, such as a card's own chrome
|
||||
* - `keep`: left showing, but what's inside it is still read
|
||||
*
|
||||
* Skeletons a component already draws itself (`ha-skeleton` and its
|
||||
* variants) are left out and left showing, as `none`.
|
||||
*/
|
||||
|
||||
export type SkeletonPieceKind = "text" | "round" | "block" | "shape" | "scrim";
|
||||
|
||||
type SkeletonOverride = "text" | "round" | "block" | "none" | "keep";
|
||||
|
||||
const OVERRIDES = new Set<string>(["text", "round", "block", "none", "keep"]);
|
||||
|
||||
const isOverride = (value: string | null): value is SkeletonOverride =>
|
||||
value !== null && OVERRIDES.has(value);
|
||||
|
||||
const skeletonOverride = (element: Element): SkeletonOverride | undefined => {
|
||||
// An overlay only wraps content, so what it wraps is read
|
||||
if (
|
||||
element.localName.startsWith("ha-skeleton") &&
|
||||
element.localName !== "ha-skeleton-overlay"
|
||||
) {
|
||||
return "none";
|
||||
}
|
||||
|
||||
const value = element.getAttribute("data-skeleton");
|
||||
|
||||
return isOverride(value) ? value : undefined;
|
||||
};
|
||||
|
||||
export interface SkeletonPiece {
|
||||
kind: SkeletonPieceKind;
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
radius?: string;
|
||||
/* An SVG mask for a drawing, such as a gauge arc */
|
||||
mask?: string;
|
||||
/* The part sits on a dark overlay, such as a picture card's name bar */
|
||||
onDark?: boolean;
|
||||
/* A see-through bar laid over a picture, kept as it is */
|
||||
background?: string;
|
||||
}
|
||||
|
||||
export interface ExtractedSkeleton {
|
||||
pieces: SkeletonPiece[];
|
||||
/* The elements the pieces stand in for, hidden while loading */
|
||||
parts: (HTMLElement | SVGElement)[];
|
||||
/* Elements holding text: hide only the text colour, as the same element
|
||||
often draws a frame, such as a badge's pill, that has to stay */
|
||||
textParts: HTMLElement[];
|
||||
}
|
||||
|
||||
const ROUND_TAGS = new Set([
|
||||
"ha-tile-icon",
|
||||
"ha-state-icon",
|
||||
"ha-svg-icon",
|
||||
"ha-icon",
|
||||
"state-badge",
|
||||
]);
|
||||
|
||||
const BLOCK_TAGS = new Set(["img", "video", "ha-camera-stream"]);
|
||||
|
||||
/* A canvas to measure fonts with, made on first use */
|
||||
let measuringContext: CanvasRenderingContext2D | null | undefined;
|
||||
|
||||
const fontContext = (style: CSSStyleDeclaration, size: string) => {
|
||||
measuringContext ??= document.createElement("canvas").getContext("2d");
|
||||
|
||||
if (measuringContext) {
|
||||
measuringContext.font = `${style.fontStyle} ${style.fontWeight} ${size} ${style.fontFamily}`;
|
||||
}
|
||||
|
||||
return measuringContext;
|
||||
};
|
||||
|
||||
/**
|
||||
* Where a text bar goes on a line of this font: from the top of the
|
||||
* capitals down to the baseline, measured from the font itself.
|
||||
* `size` is the size as drawn, after any SVG scaling.
|
||||
*/
|
||||
const capitalBand = (style: CSSStyleDeclaration, size: number) => {
|
||||
const context = fontContext(style, `${size}px`);
|
||||
|
||||
if (!context) {
|
||||
return { top: size * 0.2, height: size * 0.7 };
|
||||
}
|
||||
|
||||
const metrics = context.measureText("H");
|
||||
|
||||
return {
|
||||
// The line box holds the font's ascent, so the baseline sits that far down
|
||||
top: metrics.fontBoundingBoxAscent - metrics.actualBoundingBoxAscent,
|
||||
height: metrics.actualBoundingBoxAscent,
|
||||
};
|
||||
};
|
||||
|
||||
/* How wide "…" is in this font, the room cut-off text leaves at its end */
|
||||
const ellipsisWidth = (style: CSSStyleDeclaration) =>
|
||||
fontContext(style, style.fontSize)?.measureText("…").width ??
|
||||
parseFloat(style.fontSize);
|
||||
|
||||
/* The icon as drawn, not its box, which a line of text can crop */
|
||||
const findGlyph = (element: Element, depth = 4): Element | undefined => {
|
||||
if (depth === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
for (const child of [
|
||||
...(element.shadowRoot?.children ?? []),
|
||||
...element.children,
|
||||
]) {
|
||||
if (child instanceof SVGSVGElement) {
|
||||
return child;
|
||||
}
|
||||
|
||||
const found = findGlyph(child, depth - 1);
|
||||
|
||||
if (found) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/* Near-white text or icons, as on a picture card's dark name bar */
|
||||
const isNearWhite = (color: string): boolean => {
|
||||
const channels = color
|
||||
.match(/[\d.]+/g)
|
||||
?.slice(0, 3)
|
||||
.map(Number);
|
||||
|
||||
return channels?.length === 3 && channels.every((channel) => channel >= 200);
|
||||
};
|
||||
|
||||
const isRendered = (style: CSSStyleDeclaration) =>
|
||||
style.display !== "none" && style.visibility !== "hidden";
|
||||
|
||||
const isSeeThrough = (color: string) => {
|
||||
const alpha = Number(color.match(/rgba\(.*,\s*([\d.]+)\)/)?.[1] ?? 1);
|
||||
|
||||
return alpha > 0 && alpha < 1;
|
||||
};
|
||||
|
||||
/* The first element, inside shadow roots too, that rounds its corners */
|
||||
const findRounded = (element: Element, depth = 4): Element | undefined => {
|
||||
if (depth === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const children = [
|
||||
...(element.shadowRoot?.children ?? []),
|
||||
...element.children,
|
||||
];
|
||||
|
||||
for (const child of children) {
|
||||
if (parseFloat(getComputedStyle(child).borderTopLeftRadius) > 0) {
|
||||
return child;
|
||||
}
|
||||
|
||||
const found = findRounded(child, depth - 1);
|
||||
|
||||
if (found) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/* Join the pieces of one line of text, such as "Heat", "·" and "21 °C" */
|
||||
const mergeLines = (pieces: SkeletonPiece[]): SkeletonPiece[] => {
|
||||
const merged: SkeletonPiece[] = [];
|
||||
|
||||
for (const piece of pieces) {
|
||||
const previous = merged[merged.length - 1];
|
||||
|
||||
// Either side, so right-to-left lines join too
|
||||
const gap = previous
|
||||
? Math.max(
|
||||
piece.x - (previous.x + previous.width),
|
||||
previous.x - (piece.x + piece.width)
|
||||
)
|
||||
: Infinity;
|
||||
|
||||
const sameLine =
|
||||
previous?.kind === "text" &&
|
||||
piece.kind === "text" &&
|
||||
Math.abs(previous.y - piece.y) < 2 &&
|
||||
Math.abs(previous.height - piece.height) < 2 &&
|
||||
gap < 12;
|
||||
|
||||
if (sameLine) {
|
||||
const left = Math.min(previous.x, piece.x);
|
||||
|
||||
const right = Math.max(
|
||||
previous.x + previous.width,
|
||||
piece.x + piece.width
|
||||
);
|
||||
|
||||
previous.x = left;
|
||||
previous.width = right - left;
|
||||
continue;
|
||||
}
|
||||
|
||||
merged.push({ ...piece });
|
||||
}
|
||||
|
||||
return merged;
|
||||
};
|
||||
|
||||
const svgMask = (svg: SVGSVGElement, width: number, height: number) => {
|
||||
const clone = svg.cloneNode(true);
|
||||
|
||||
if (!(clone instanceof SVGSVGElement)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const originals = [svg, ...svg.querySelectorAll("*")];
|
||||
const copies = [clone, ...clone.querySelectorAll("*")];
|
||||
let drawnPaths = 0;
|
||||
|
||||
originals.forEach((original, index) => {
|
||||
const copy = copies[index];
|
||||
const style = getComputedStyle(original);
|
||||
|
||||
if (original.localName === "text" || !isRendered(style)) {
|
||||
copy.setAttribute("display", "none");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (original !== svg && original.localName !== "g") {
|
||||
drawnPaths++;
|
||||
}
|
||||
|
||||
copy.removeAttribute("class");
|
||||
copy.removeAttribute("style");
|
||||
copy.setAttribute("fill", style.fill === "none" ? "none" : "#000");
|
||||
copy.setAttribute("stroke", style.stroke === "none" ? "none" : "#000");
|
||||
copy.setAttribute("stroke-width", style.strokeWidth);
|
||||
copy.setAttribute("stroke-linecap", style.strokeLinecap);
|
||||
});
|
||||
|
||||
if (drawnPaths === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
clone.setAttribute("width", String(width));
|
||||
clone.setAttribute("height", String(height));
|
||||
|
||||
const markup = new XMLSerializer().serializeToString(clone);
|
||||
|
||||
return `url("data:image/svg+xml,${encodeURIComponent(markup)}")`;
|
||||
};
|
||||
|
||||
export const extractSkeleton = (
|
||||
root: Element,
|
||||
origin: DOMRect
|
||||
): ExtractedSkeleton => {
|
||||
const pieces: SkeletonPiece[] = [];
|
||||
const parts = new Set<HTMLElement | SVGElement>();
|
||||
const textParts = new Set<HTMLElement>();
|
||||
|
||||
/* The card's own background, the first solid one found */
|
||||
let surface: string | undefined;
|
||||
|
||||
const box = (rect: DOMRect) => ({
|
||||
x: rect.left - origin.left,
|
||||
y: rect.top - origin.top,
|
||||
width: rect.width,
|
||||
height: rect.height,
|
||||
});
|
||||
|
||||
/* Near-white content on a light card must sit on a dark bar */
|
||||
const onDark = (style: CSSStyleDeclaration) =>
|
||||
surface !== undefined && isNearWhite(surface) && isNearWhite(style.color);
|
||||
|
||||
const addText = (element: Element | ShadowRoot) => {
|
||||
const owner = element instanceof ShadowRoot ? element.host : element;
|
||||
|
||||
// Text cut short with an ellipsis reaches past its box, so clip to it
|
||||
const clip = owner.getBoundingClientRect();
|
||||
|
||||
element.childNodes.forEach((node) => {
|
||||
if (!(node instanceof Text) || !node.textContent?.trim()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Slotted text takes its font and colour from the slot it shows in,
|
||||
// so that's where it's measured and hidden
|
||||
const slot = node.assignedSlot;
|
||||
const hideTarget = slot ?? owner;
|
||||
const style = getComputedStyle(hideTarget);
|
||||
const band = capitalBand(style, parseFloat(style.fontSize));
|
||||
|
||||
if (hideTarget instanceof HTMLElement) {
|
||||
textParts.add(hideTarget);
|
||||
}
|
||||
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(node);
|
||||
|
||||
for (const rect of range.getClientRects()) {
|
||||
// Cut-off text ends in "…", on the right or, right to left, on the
|
||||
// left, so stop the bar where that starts
|
||||
const left =
|
||||
rect.left < clip.left - 1
|
||||
? clip.left + ellipsisWidth(style)
|
||||
: rect.left;
|
||||
|
||||
const right =
|
||||
rect.right > clip.right + 1
|
||||
? clip.right - ellipsisWidth(style)
|
||||
: rect.right;
|
||||
|
||||
if (right <= left) {
|
||||
continue;
|
||||
}
|
||||
|
||||
pieces.push({
|
||||
kind: "text",
|
||||
x: left - origin.left,
|
||||
width: right - left,
|
||||
y: rect.top - origin.top + band.top,
|
||||
height: band.height,
|
||||
onDark: onDark(style),
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const walk = (node: Element | ShadowRoot) => {
|
||||
// Text straight inside a shadow root, as state-display renders its state
|
||||
if (node instanceof ShadowRoot) {
|
||||
addText(node);
|
||||
}
|
||||
|
||||
for (const child of node.children) {
|
||||
const style = getComputedStyle(child);
|
||||
|
||||
if (!isRendered(style)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const rect = child.getBoundingClientRect();
|
||||
const tag = child.localName;
|
||||
// Elements such as slots take no space but their content does
|
||||
const hasSize = rect.width > 0 && rect.height > 0;
|
||||
const override = skeletonOverride(child);
|
||||
|
||||
if (override === "none") {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (override === "keep") {
|
||||
if (child.shadowRoot) {
|
||||
walk(child.shadowRoot);
|
||||
}
|
||||
|
||||
walk(child);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (override !== undefined) {
|
||||
if (
|
||||
hasSize &&
|
||||
(child instanceof HTMLElement || child instanceof SVGElement)
|
||||
) {
|
||||
const size = Math.min(rect.width, rect.height);
|
||||
const piece = box(rect);
|
||||
|
||||
pieces.push(
|
||||
override === "round"
|
||||
? {
|
||||
kind: "round",
|
||||
x: piece.x + (piece.width - size) / 2,
|
||||
y: piece.y + (piece.height - size) / 2,
|
||||
width: size,
|
||||
height: size,
|
||||
}
|
||||
: { kind: override, ...piece, radius: style.borderRadius }
|
||||
);
|
||||
parts.add(child);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
surface === undefined &&
|
||||
hasSize &&
|
||||
style.backgroundColor !== "rgba(0, 0, 0, 0)" &&
|
||||
!isSeeThrough(style.backgroundColor)
|
||||
) {
|
||||
surface = style.backgroundColor;
|
||||
}
|
||||
|
||||
if (child instanceof HTMLElement && ROUND_TAGS.has(tag)) {
|
||||
// Use the circle itself, such as the tile icon's 36px background
|
||||
const circle = (
|
||||
findRounded(child) ??
|
||||
findGlyph(child) ??
|
||||
child
|
||||
).getBoundingClientRect();
|
||||
|
||||
const size =
|
||||
Math.min(circle.width, circle.height) ||
|
||||
Math.max(circle.width, circle.height);
|
||||
|
||||
const piece = box(circle);
|
||||
|
||||
if (size > 0) {
|
||||
pieces.push({
|
||||
kind: "round",
|
||||
x: piece.x + (piece.width - size) / 2,
|
||||
y: piece.y + (piece.height - size) / 2,
|
||||
width: size,
|
||||
height: size,
|
||||
onDark: onDark(style),
|
||||
});
|
||||
parts.add(child);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// A see-through bar over a picture stays, so text keeps its contrast
|
||||
if (
|
||||
child instanceof HTMLElement &&
|
||||
hasSize &&
|
||||
style.position === "absolute" &&
|
||||
isSeeThrough(style.backgroundColor)
|
||||
) {
|
||||
pieces.push({
|
||||
kind: "scrim",
|
||||
...box(rect),
|
||||
radius: style.borderRadius,
|
||||
background: style.backgroundColor,
|
||||
});
|
||||
}
|
||||
|
||||
// Pictures drawn as a background, as hui-image does in a fixed ratio
|
||||
if (
|
||||
child instanceof HTMLElement &&
|
||||
hasSize &&
|
||||
style.backgroundImage.startsWith("url(")
|
||||
) {
|
||||
pieces.push({
|
||||
kind: "block",
|
||||
...box(rect),
|
||||
radius: style.borderRadius,
|
||||
});
|
||||
parts.add(child);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (child instanceof HTMLElement && hasSize && BLOCK_TAGS.has(tag)) {
|
||||
pieces.push({
|
||||
kind: "block",
|
||||
...box(rect),
|
||||
radius: style.borderRadius,
|
||||
});
|
||||
parts.add(child);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
child instanceof HTMLElement &&
|
||||
hasSize &&
|
||||
tag.endsWith("-card-feature")
|
||||
) {
|
||||
const control = findRounded(child);
|
||||
|
||||
const radius = control
|
||||
? getComputedStyle(control).borderRadius
|
||||
: style.borderRadius;
|
||||
|
||||
pieces.push({ kind: "block", ...box(rect), radius });
|
||||
parts.add(child);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (child instanceof SVGSVGElement && hasSize) {
|
||||
const piece = box(rect);
|
||||
const mask = svgMask(child, piece.width, piece.height);
|
||||
|
||||
if (mask) {
|
||||
pieces.push({ kind: "shape", ...piece, mask });
|
||||
}
|
||||
|
||||
child.querySelectorAll("text").forEach((text) => {
|
||||
const textRect = text.getBoundingClientRect();
|
||||
|
||||
if (textRect.width === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// SVG text is scaled with its drawing, as the gauge value is
|
||||
const scale = text.getScreenCTM()?.a ?? 1;
|
||||
const textStyle = getComputedStyle(text);
|
||||
|
||||
const band = capitalBand(
|
||||
textStyle,
|
||||
parseFloat(textStyle.fontSize) * scale
|
||||
);
|
||||
|
||||
pieces.push({
|
||||
kind: "text",
|
||||
...box(textRect),
|
||||
y: textRect.top - origin.top + band.top,
|
||||
height: band.height,
|
||||
});
|
||||
});
|
||||
|
||||
parts.add(child);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (child instanceof HTMLElement) {
|
||||
addText(child);
|
||||
}
|
||||
|
||||
if (child.shadowRoot) {
|
||||
walk(child.shadowRoot);
|
||||
}
|
||||
|
||||
walk(child);
|
||||
}
|
||||
};
|
||||
|
||||
walk(root);
|
||||
|
||||
return {
|
||||
pieces: mergeLines(pieces),
|
||||
parts: [...parts],
|
||||
textParts: [...textParts],
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
import { css } from "lit";
|
||||
|
||||
/* The space a chart takes while its data loads, as big as `ha-chart-base`
|
||||
draws one by default: half as tall as it's wide, within the same limits,
|
||||
with a line for its legend under it. Put the placeholder and its legend
|
||||
in a `.placeholder-container` as wide as the chart will be. */
|
||||
export const chartPlaceholderStyles = css`
|
||||
.placeholder-container {
|
||||
container-type: inline-size;
|
||||
}
|
||||
.placeholder {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: min(max(50cqi, 200px), var(--chart-max-height, 350px));
|
||||
}
|
||||
.legend-placeholder {
|
||||
width: 40%;
|
||||
height: 16px;
|
||||
margin: 10px auto;
|
||||
}
|
||||
`;
|
||||
@@ -173,6 +173,11 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
|
||||
@property({ type: String }) public height?: string;
|
||||
|
||||
// While the data loads, the chart is read as one block and its legend as
|
||||
// one line, or as its items when the legend has them already, so a
|
||||
// skeleton drawn over it takes the size it will have
|
||||
@property({ type: Boolean }) public loading = false;
|
||||
|
||||
// Lets cards that key their data on ids have display names announced
|
||||
// instead when the chart is navigated with Chart2Music.
|
||||
@property({ attribute: false })
|
||||
@@ -635,6 +640,7 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
class="chart ${classMap({
|
||||
"touch-scrub": this._isTouchDevice && this._hasZoomableXAxis(),
|
||||
})}"
|
||||
data-skeleton=${ifDefined(this.loading ? "block" : undefined)}
|
||||
role=${ifDefined(sonifiable ? "application" : undefined)}
|
||||
tabindex=${ifDefined(
|
||||
sonifiable ? "0" : this._sonificationFocusHeld ? "-1" : undefined
|
||||
@@ -707,6 +713,18 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
if (!items) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
// A card that knows its legend before its data shows it under the
|
||||
// skeleton, so the skeleton has as many legend rows as it will
|
||||
if (this.loading && !items.length) {
|
||||
return html`<div class="chart-legend">
|
||||
<ul>
|
||||
<li>
|
||||
<span class="legend-placeholder" data-skeleton="text"></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>`;
|
||||
}
|
||||
const datasets = ensureArray(this.data!);
|
||||
// Index datasets by id and name so each legend item is an O(1) lookup
|
||||
// instead of scanning every dataset twice. Charts can have many series.
|
||||
@@ -2424,6 +2442,13 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
.chart-legend.multiple-items li {
|
||||
max-width: 220px;
|
||||
}
|
||||
.chart-legend li:has(.legend-placeholder) {
|
||||
width: 40%;
|
||||
}
|
||||
.legend-placeholder {
|
||||
width: 100%;
|
||||
height: var(--ha-font-size-s);
|
||||
}
|
||||
.chart-legend.multiple-items li:has(.value) {
|
||||
max-width: 300px;
|
||||
}
|
||||
|
||||
@@ -36,6 +36,10 @@ const ROW_HEIGHT = 30;
|
||||
const ROW_HEIGHT_INSIDE_LABELS = 64;
|
||||
const GRID_BOTTOM = 30;
|
||||
|
||||
/* How tall a timeline with this many rows is drawn */
|
||||
export const timelineHeight = (rows: number, tallRows: boolean) =>
|
||||
rows * (tallRows ? ROW_HEIGHT_INSIDE_LABELS : ROW_HEIGHT) + GRID_BOTTOM;
|
||||
|
||||
@customElement("state-history-chart-timeline")
|
||||
export class StateHistoryChartTimeline extends LitElement {
|
||||
@property({ attribute: false }) public data: TimelineEntity[] = [];
|
||||
@@ -94,13 +98,10 @@ export class StateHistoryChartTimeline extends LitElement {
|
||||
return html`
|
||||
<ha-chart-base
|
||||
.options=${this._chartOptions}
|
||||
.height=${`${
|
||||
this.data.length *
|
||||
(this.insideLabels && (this.chunked || this.showNames)
|
||||
? ROW_HEIGHT_INSIDE_LABELS
|
||||
: ROW_HEIGHT) +
|
||||
GRID_BOTTOM
|
||||
}px`}
|
||||
.height=${`${timelineHeight(
|
||||
this.data.length,
|
||||
this.insideLabels && (this.chunked || this.showNames)
|
||||
)}px`}
|
||||
.data=${this._chartData as HaECSeries}
|
||||
small-controls
|
||||
grow-for-zoom-slider
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { RenderItemFunction } from "@lit-labs/virtualizer/virtualize";
|
||||
import type { HassConfig } from "home-assistant-js-websocket";
|
||||
import type { HassConfig, HassEntities } from "home-assistant-js-websocket";
|
||||
import type { PropertyValues } from "lit";
|
||||
import { css, html, LitElement } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import {
|
||||
customElement,
|
||||
eventOptions,
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
queryAll,
|
||||
state,
|
||||
} from "lit/decorators";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
import { isComponentLoaded } from "../../common/config/is_component_loaded";
|
||||
import { consume } from "../../common/decorators/consume";
|
||||
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
|
||||
@@ -20,18 +21,24 @@ import type {
|
||||
HASSDomTargetEvent,
|
||||
} from "../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../common/translations/localize";
|
||||
import { configContext } from "../../data/context";
|
||||
import { configContext, statesContext } from "../../data/context";
|
||||
import type {
|
||||
HistoryResult,
|
||||
LineChartUnit,
|
||||
TimelineEntity,
|
||||
} from "../../data/history";
|
||||
import { expectedHistoryCharts } from "../../data/history";
|
||||
import { loadVirtualizer } from "../../resources/virtualizer";
|
||||
import type { HomeAssistantConfig } from "../../types";
|
||||
import { SkeletonLoadingController } from "../skeleton/skeleton-loading-controller";
|
||||
import { chartPlaceholderStyles } from "./chart-placeholder";
|
||||
import "./state-history-chart-line";
|
||||
import type { StateHistoryChartLine } from "./state-history-chart-line";
|
||||
import "./state-history-chart-timeline";
|
||||
import type { StateHistoryChartTimeline } from "./state-history-chart-timeline";
|
||||
import {
|
||||
timelineHeight,
|
||||
type StateHistoryChartTimeline,
|
||||
} from "./state-history-chart-timeline";
|
||||
|
||||
const CANVAS_TIMELINE_ROWS_CHUNK = 10; // Split up the canvases to avoid hitting the render limit
|
||||
|
||||
@@ -93,6 +100,21 @@ export class StateHistoryCharts extends LitElement {
|
||||
@property({ attribute: "is-loading-data", type: Boolean })
|
||||
public isLoadingData = false;
|
||||
|
||||
/** The entities being loaded, so their charts' space can be held */
|
||||
@property({ attribute: false }) public loadingEntityIds?: string[];
|
||||
|
||||
/** Whether those entities' charts are split by device class */
|
||||
@property({ attribute: "split-device-classes", type: Boolean })
|
||||
public splitDeviceClasses = false;
|
||||
|
||||
protected readonly _skeletonLoading = new SkeletonLoadingController(
|
||||
this,
|
||||
() =>
|
||||
isComponentLoaded(this._hassConfig, "history") &&
|
||||
this.isLoadingData &&
|
||||
!this.historyData
|
||||
);
|
||||
|
||||
@property({ attribute: "logarithmic-scale", type: Boolean })
|
||||
public logarithmicScale = false;
|
||||
|
||||
@@ -129,6 +151,9 @@ export class StateHistoryCharts extends LitElement {
|
||||
})
|
||||
private _hassConfig!: HassConfig;
|
||||
|
||||
@consume({ context: statesContext, subscribe: true })
|
||||
private _states?: HassEntities;
|
||||
|
||||
@queryAll("state-history-chart-line, state-history-chart-timeline")
|
||||
private _chartComponents!: NodeListOf<
|
||||
StateHistoryChartLine | StateHistoryChartTimeline
|
||||
@@ -147,9 +172,7 @@ export class StateHistoryCharts extends LitElement {
|
||||
}
|
||||
|
||||
if (this.isLoadingData && !this.historyData) {
|
||||
return html`<div class="info">
|
||||
${this._localize("ui.components.history_charts.loading_history")}
|
||||
</div>`;
|
||||
return this._renderLoading();
|
||||
}
|
||||
|
||||
if (this._isHistoryEmpty()) {
|
||||
@@ -189,6 +212,59 @@ export class StateHistoryCharts extends LitElement {
|
||||
`;
|
||||
}
|
||||
|
||||
/* Takes the space the charts will, so nothing moves when they arrive */
|
||||
private _renderLoading() {
|
||||
const label = this._localize(
|
||||
"ui.components.history_charts.loading_history"
|
||||
);
|
||||
|
||||
const expected =
|
||||
this.loadingEntityIds && this._states && !this.height && !this.virtualize
|
||||
? expectedHistoryCharts(
|
||||
this.loadingEntityIds,
|
||||
this._states,
|
||||
this._hassConfig.unit_system.temperature,
|
||||
this.splitDeviceClasses
|
||||
)
|
||||
: undefined;
|
||||
|
||||
if (!expected || (!expected.lines && !expected.timelineRows)) {
|
||||
return html`<div class="info" data-skeleton="block">${label}</div>`;
|
||||
}
|
||||
|
||||
// Only the first chart says what's happening, for where no skeleton is
|
||||
// drawn
|
||||
const timeline = expected.timelineRows
|
||||
? html`<div class="entry-container timeline">
|
||||
<div
|
||||
class="info"
|
||||
data-skeleton="block"
|
||||
style=${styleMap({
|
||||
height: `${timelineHeight(
|
||||
expected.timelineRows,
|
||||
this.insideLabels && this.showNames
|
||||
)}px`,
|
||||
})}
|
||||
>
|
||||
${label}
|
||||
</div>
|
||||
</div>`
|
||||
: nothing;
|
||||
|
||||
const lines = Array.from(
|
||||
{ length: expected.lines },
|
||||
(_, index) =>
|
||||
html`<div class="entry-container line placeholder-container">
|
||||
<div class="info placeholder" data-skeleton="block">
|
||||
${index === 0 && !expected.timelineRows ? label : nothing}
|
||||
</div>
|
||||
<div class="legend-placeholder" data-skeleton="text"></div>
|
||||
</div>`
|
||||
);
|
||||
|
||||
return html`${timeline}${lines}`;
|
||||
}
|
||||
|
||||
private _renderHistoryItem: RenderItemFunction<
|
||||
TimelineEntity[] | LineChartUnit
|
||||
> = (item, index) => {
|
||||
@@ -472,6 +548,8 @@ export class StateHistoryCharts extends LitElement {
|
||||
state-history-chart-line {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
${chartPlaceholderStyles}
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
@@ -57,10 +57,12 @@ import type {
|
||||
ZoomSliderMode,
|
||||
} from "./ha-chart-base";
|
||||
import "./ha-chart-base";
|
||||
import { chartPlaceholderStyles } from "./chart-placeholder";
|
||||
import { sideTooltipPosition } from "./chart-tooltip-position";
|
||||
import "./ha-chart-tooltip-marker";
|
||||
import { generateStatisticsChartData } from "./statistics-chart-data";
|
||||
import { createYAxisPrecisionBounds } from "./y-axis-fraction-digits";
|
||||
import { SkeletonLoadingController } from "../skeleton/skeleton-loading-controller";
|
||||
|
||||
export const supportedStatTypeMap: Record<StatisticType, StatisticType> = {
|
||||
mean: "mean",
|
||||
@@ -121,6 +123,14 @@ export class StatisticsChart extends LitElement {
|
||||
@property({ attribute: "is-loading-data", type: Boolean })
|
||||
public isLoadingData = false;
|
||||
|
||||
protected readonly _skeletonLoading = new SkeletonLoadingController(
|
||||
this,
|
||||
() =>
|
||||
isComponentLoaded(this._hassConfig, "history") &&
|
||||
this.isLoadingData &&
|
||||
!this.statisticsData
|
||||
);
|
||||
|
||||
@property({ attribute: "click-for-more-info", type: Boolean })
|
||||
public clickForMoreInfo = true;
|
||||
|
||||
@@ -242,10 +252,23 @@ export class StatisticsChart extends LitElement {
|
||||
}
|
||||
|
||||
if (this.isLoadingData && !this.statisticsData) {
|
||||
return html`<div class="info">
|
||||
${this._i18n.localize(
|
||||
"ui.components.statistics_charts.loading_statistics"
|
||||
)}
|
||||
const label = this._i18n.localize(
|
||||
"ui.components.statistics_charts.loading_statistics"
|
||||
);
|
||||
|
||||
// A chart given a height holds its space already
|
||||
if (this.height) {
|
||||
return html`<div class="info" data-skeleton="block">${label}</div>`;
|
||||
}
|
||||
|
||||
// Takes the space the chart will, so nothing moves when it arrives
|
||||
return html`<div class="placeholder-container">
|
||||
<div class="info placeholder" data-skeleton="block">${label}</div>
|
||||
${
|
||||
this.hideLegend
|
||||
? nothing
|
||||
: html`<div class="legend-placeholder" data-skeleton="text"></div>`
|
||||
}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
@@ -697,6 +720,7 @@ export class StatisticsChart extends LitElement {
|
||||
line-height: 60px;
|
||||
color: var(--secondary-text-color);
|
||||
}
|
||||
${chartPlaceholderStyles}
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
@@ -45,6 +45,7 @@ import "../ha-checkbox";
|
||||
import type { HaCheckbox } from "../ha-checkbox";
|
||||
import "../skeleton/ha-skeleton-icon";
|
||||
import "../skeleton/ha-skeleton-text";
|
||||
import { skeletonArrivalStyles } from "../skeleton/skeleton-arrival";
|
||||
import "../ha-svg-icon";
|
||||
import "../input/ha-input-search";
|
||||
import { filterData, sortData } from "./sort-filter";
|
||||
@@ -800,9 +801,11 @@ export class HaDataTable extends LitElement {
|
||||
</div>`
|
||||
: nothing
|
||||
}
|
||||
<!-- The list fades in once as it takes the skeleton rows'
|
||||
place; rows made later as it scrolls show at once -->
|
||||
<lit-virtualizer
|
||||
scroller
|
||||
class="mdc-data-table__content scroller ha-scrollbar ${classMap(
|
||||
class="mdc-data-table__content scroller ha-scrollbar arriving ${classMap(
|
||||
{ grouped: Boolean(this.groupColumn) && !this.autoHeight }
|
||||
)}"
|
||||
tabindex=${ifDefined(!this.autoHeight ? "0" : undefined)}
|
||||
@@ -1628,6 +1631,7 @@ export class HaDataTable extends LitElement {
|
||||
static get styles(): CSSResultGroup {
|
||||
return [
|
||||
haStyleScrollbar,
|
||||
skeletonArrivalStyles,
|
||||
css`
|
||||
/* default mdc styles, colors changed, without checkbox styles */
|
||||
:host {
|
||||
|
||||
@@ -73,6 +73,7 @@ import { UNAVAILABLE, UNKNOWN } from "../../data/entity/entity";
|
||||
import type { EntityRegistryEntry } from "../../data/entity/entity_registry";
|
||||
import { ensureMapTilesToken } from "../../data/map_tiles";
|
||||
import "../ha-tooltip";
|
||||
import { SkeletonLoadingController } from "../skeleton/skeleton-loading-controller";
|
||||
import type {
|
||||
HomeAssistantConfig,
|
||||
HomeAssistantConnection,
|
||||
@@ -715,6 +716,12 @@ export class HaMap extends ReactiveElement {
|
||||
|
||||
private _drawnFallback?: number;
|
||||
|
||||
// Until the first frame, which the map fades in with
|
||||
protected readonly _skeletonLoading = new SkeletonLoadingController(
|
||||
this,
|
||||
() => this.isConnected && !this._mapDrawn
|
||||
);
|
||||
|
||||
private _markDrawn(attempt: number): void {
|
||||
if (attempt !== this._setupAttempt || this._mapDrawn) {
|
||||
return;
|
||||
@@ -722,6 +729,7 @@ export class HaMap extends ReactiveElement {
|
||||
clearTimeout(this._drawnFallback);
|
||||
this._mapDrawn = true;
|
||||
this._updateMapAppearance();
|
||||
this.requestUpdate();
|
||||
}
|
||||
|
||||
private _loading = false;
|
||||
|
||||
@@ -0,0 +1,543 @@
|
||||
import type { ContextType } from "@lit/context";
|
||||
import type { CSSResultGroup, PropertyValues } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
import { consume } from "../../common/decorators/consume";
|
||||
import type {
|
||||
ExtractedSkeleton,
|
||||
SkeletonPiece,
|
||||
} from "../../common/dom/extract-skeleton";
|
||||
import { extractSkeleton } from "../../common/dom/extract-skeleton";
|
||||
import type { HASSDomEvent } from "../../common/dom/fire_event";
|
||||
import { internationalizationContext } from "../../data/context";
|
||||
import type { HaSkeleton } from "./ha-skeleton";
|
||||
import "./ha-skeleton";
|
||||
import {
|
||||
rememberedSkeletonHeight,
|
||||
rememberSkeletonHeight,
|
||||
} from "./skeleton-sizes";
|
||||
|
||||
/* How long after loading the content can still settle into its size */
|
||||
const SETTLE_TIME = 2000;
|
||||
|
||||
export interface SkeletonLoadingDetail {
|
||||
loading: boolean;
|
||||
}
|
||||
|
||||
interface ArrivingParts {
|
||||
/* The whole content, when it was hidden rather than its parts */
|
||||
content: Element[];
|
||||
opacityParts: (HTMLElement | SVGElement)[];
|
||||
colorParts: HTMLElement[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a skeleton of its content while that content loads, read from the
|
||||
* content itself: each line of text, icon, image, control and drawing gets
|
||||
* its own piece. When loading ends, the pieces go and each part fades in.
|
||||
*
|
||||
* Loading is on while `loading` is set, or while anything inside has fired
|
||||
* a `skeleton-loading` event with `{ loading: true }` and not yet
|
||||
* `{ loading: false }`. The event stops at the nearest overlay, so content
|
||||
* doesn't need to know what wraps it.
|
||||
*
|
||||
* To take over:
|
||||
* - put your own skeleton in the `skeleton` slot, and it's used instead of
|
||||
* reading one
|
||||
* - set `data-skeleton` on any element inside, as described in
|
||||
* `extract-skeleton`, to change how that part is read or leave it out
|
||||
* - call `refresh()` when the content changes without changing size
|
||||
*
|
||||
* With a `skeleton-key`, it remembers how big the content was once loaded,
|
||||
* and next time holds that size while it loads, stretching the content to
|
||||
* fill it. Give each piece of content its own key, such as one made with
|
||||
* `skeletonKey()` from its config.
|
||||
*
|
||||
* With nothing to read yet, such as before the content's code has loaded,
|
||||
* it fills itself with one plain wave. The skeleton follows the host's
|
||||
* corner radius.
|
||||
*
|
||||
* @slot - The content.
|
||||
* @slot skeleton - A skeleton of your own, used instead of reading one.
|
||||
*/
|
||||
@customElement("ha-skeleton-overlay")
|
||||
export class HaSkeletonOverlay extends LitElement {
|
||||
@property({ type: Boolean }) public loading = false;
|
||||
|
||||
@property() public effect: HaSkeleton["effect"] = "sheen";
|
||||
|
||||
/** Remember the loaded size under this key, and hold it next time */
|
||||
@property({ attribute: "skeleton-key" }) public skeletonKey?: string;
|
||||
|
||||
@state()
|
||||
@consume({ context: internationalizationContext, subscribe: true })
|
||||
private _i18n?: ContextType<typeof internationalizationContext>;
|
||||
|
||||
/* What's inside that has said it's loading */
|
||||
@state() private _loadingSources = new Set<EventTarget>();
|
||||
|
||||
@state() private _pieces?: SkeletonPiece[];
|
||||
|
||||
@state() private _customSkeleton = false;
|
||||
|
||||
@state() private _onScreen = true;
|
||||
|
||||
@query("slot:not([name])") private _contentSlot?: HTMLSlotElement;
|
||||
|
||||
/* Inline values the parts had before they were hidden */
|
||||
private _hiddenOpacity = new Map<HTMLElement | SVGElement, string>();
|
||||
|
||||
private _hiddenColor = new Map<HTMLElement, string>();
|
||||
|
||||
private _wasLoading = false;
|
||||
|
||||
/* What to fade in once loading has ended */
|
||||
private _arriving?: ArrivingParts;
|
||||
|
||||
private _measureFrame?: number;
|
||||
|
||||
/* Whether the remembered size was looked at for this load */
|
||||
private _reserveChecked = false;
|
||||
|
||||
private _settleObserver?: ResizeObserver;
|
||||
|
||||
private _settleTimeout?: number;
|
||||
|
||||
private _resizeObserver = new ResizeObserver(() => this._scheduleMeasure());
|
||||
|
||||
private _intersectionObserver = new IntersectionObserver((entries) => {
|
||||
this._onScreen = entries[entries.length - 1].isIntersecting;
|
||||
});
|
||||
|
||||
public connectedCallback() {
|
||||
super.connectedCallback();
|
||||
|
||||
if (this._wasLoading) {
|
||||
this._observe();
|
||||
}
|
||||
}
|
||||
|
||||
public disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
this._unobserve();
|
||||
this._stopRemembering();
|
||||
|
||||
if (this._measureFrame !== undefined) {
|
||||
cancelAnimationFrame(this._measureFrame);
|
||||
this._measureFrame = undefined;
|
||||
}
|
||||
|
||||
// Never leave the content hidden while it's away
|
||||
this._showParts();
|
||||
}
|
||||
|
||||
/** Read the skeleton again, after the content changed but not its size */
|
||||
public refresh() {
|
||||
this._scheduleMeasure();
|
||||
}
|
||||
|
||||
private get _isLoading() {
|
||||
return this.loading || this._loadingSources.size > 0;
|
||||
}
|
||||
|
||||
protected willUpdate(changedProperties: PropertyValues<this>) {
|
||||
super.willUpdate(changedProperties);
|
||||
const loading = this._isLoading;
|
||||
|
||||
if (loading && !this._wasLoading) {
|
||||
this._customSkeleton = [...this.children].some(
|
||||
(child) => child.slot === "skeleton"
|
||||
);
|
||||
this._reserveChecked = false;
|
||||
this._stopRemembering();
|
||||
this._observe();
|
||||
}
|
||||
|
||||
if (!loading && this._wasLoading) {
|
||||
this._unobserve();
|
||||
this._endLoading();
|
||||
this._rememberWhenSettled();
|
||||
}
|
||||
|
||||
this._wasLoading = loading;
|
||||
}
|
||||
|
||||
protected updated(changedProperties: PropertyValues<this>) {
|
||||
super.updated(changedProperties);
|
||||
|
||||
if (this._isLoading) {
|
||||
this._scheduleMeasure();
|
||||
}
|
||||
|
||||
if (this._arriving) {
|
||||
this._fadeIn(this._arriving);
|
||||
this._arriving = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
protected render() {
|
||||
const loading = this._isLoading;
|
||||
// Named like ha-spinner, which falls back to English before translations
|
||||
// have loaded
|
||||
const label = this._i18n?.localize("ui.common.loading") || "Loading";
|
||||
|
||||
return html`
|
||||
<slot
|
||||
class=${classMap({
|
||||
// Before the first reading, or under a skeleton of your own
|
||||
hidden:
|
||||
loading && (this._customSkeleton || this._pieces === undefined),
|
||||
})}
|
||||
@slotchange=${this._contentChanged}
|
||||
@skeleton-loading=${this._skeletonLoading}
|
||||
></slot>
|
||||
${
|
||||
loading
|
||||
? html`
|
||||
<div class="skeleton" role="progressbar" aria-label=${label}>
|
||||
<slot
|
||||
name="skeleton"
|
||||
@slotchange=${this._skeletonSlotChanged}
|
||||
></slot>
|
||||
${this._customSkeleton ? nothing : this._renderPieces()}
|
||||
</div>
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
private _renderPieces() {
|
||||
// Nothing still animates off screen
|
||||
const effect = this._onScreen ? this.effect : "none";
|
||||
|
||||
if (!this._pieces?.length) {
|
||||
return html`<ha-skeleton class="fill" .effect=${effect}></ha-skeleton>`;
|
||||
}
|
||||
|
||||
return this._pieces.map((piece) =>
|
||||
piece.kind === "scrim"
|
||||
? html`<div class="piece" style=${pieceStyle(piece)}></div>`
|
||||
: html`<ha-skeleton
|
||||
class=${classMap({
|
||||
piece: true,
|
||||
[piece.kind]: true,
|
||||
"on-dark": Boolean(piece.onDark),
|
||||
})}
|
||||
.effect=${effect}
|
||||
style=${pieceStyle(piece)}
|
||||
></ha-skeleton>`
|
||||
);
|
||||
}
|
||||
|
||||
private _skeletonLoading(ev: HASSDomEvent<SkeletonLoadingDetail>) {
|
||||
// The nearest overlay owns it
|
||||
ev.stopPropagation();
|
||||
const source = ev.composedPath()[0];
|
||||
const sources = new Set(this._loadingSources);
|
||||
|
||||
if (ev.detail.loading) {
|
||||
sources.add(source);
|
||||
} else {
|
||||
sources.delete(source);
|
||||
}
|
||||
|
||||
this._loadingSources = sources;
|
||||
this._scheduleMeasure();
|
||||
}
|
||||
|
||||
/* Sizes and visibility only matter while loading, so an overlay around
|
||||
content that has loaded costs nothing */
|
||||
private _observe() {
|
||||
this._resizeObserver.disconnect();
|
||||
this._resizeObserver.observe(this);
|
||||
this._contentSlot
|
||||
?.assignedElements()
|
||||
.forEach((element) => this._resizeObserver.observe(element));
|
||||
this._intersectionObserver.observe(this);
|
||||
this._scheduleMeasure();
|
||||
}
|
||||
|
||||
private _unobserve() {
|
||||
this._resizeObserver.disconnect();
|
||||
this._intersectionObserver.disconnect();
|
||||
}
|
||||
|
||||
private _contentChanged() {
|
||||
if (!this._isLoading) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._observe();
|
||||
this._pruneSources();
|
||||
}
|
||||
|
||||
/* Content that went away can't finish loading */
|
||||
private _pruneSources() {
|
||||
const sources = [...this._loadingSources].filter(
|
||||
(source) => !(source instanceof Node) || source.isConnected
|
||||
);
|
||||
|
||||
if (sources.length !== this._loadingSources.size) {
|
||||
this._loadingSources = new Set(sources);
|
||||
}
|
||||
}
|
||||
|
||||
private _skeletonSlotChanged(ev: Event) {
|
||||
const slot = ev.target;
|
||||
|
||||
if (!(slot instanceof HTMLSlotElement)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._customSkeleton = slot.assignedNodes({ flatten: true }).length > 0;
|
||||
|
||||
if (this._customSkeleton) {
|
||||
// The whole content is hidden under it instead
|
||||
this._showParts();
|
||||
this._pieces = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private _scheduleMeasure() {
|
||||
if (this._measureFrame !== undefined || !this.isConnected) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._measureFrame = requestAnimationFrame(() => {
|
||||
this._measureFrame = undefined;
|
||||
this._measure();
|
||||
});
|
||||
}
|
||||
|
||||
/* Read the skeleton from the content, and hide the parts it stands in for */
|
||||
private _measure() {
|
||||
// A part that said it was loading may have gone without saying it's done
|
||||
this._pruneSources();
|
||||
|
||||
if (!this._isLoading) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._reserve();
|
||||
|
||||
if (this._customSkeleton) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Read from the content as it really looks, then hide it again before
|
||||
// the next paint, so nothing flickers
|
||||
this._showParts();
|
||||
const skeleton = extractSkeleton(this, this.getBoundingClientRect());
|
||||
this._hideParts(skeleton);
|
||||
|
||||
if (JSON.stringify(skeleton.pieces) !== JSON.stringify(this._pieces)) {
|
||||
this._pieces = skeleton.pieces;
|
||||
}
|
||||
}
|
||||
|
||||
/* Hold the height the content had last time it loaded at this width */
|
||||
private _reserve() {
|
||||
if (this._reserveChecked || !this.skeletonKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
const width = this.getBoundingClientRect().width;
|
||||
|
||||
// Not laid out yet
|
||||
if (!width) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._reserveChecked = true;
|
||||
const height = rememberedSkeletonHeight(this.skeletonKey, width);
|
||||
|
||||
if (height === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.style.setProperty(
|
||||
"--ha-skeleton-overlay-reserved-height",
|
||||
`${height}px`
|
||||
);
|
||||
this.toggleAttribute("reserved", true);
|
||||
}
|
||||
|
||||
private _release() {
|
||||
this.removeAttribute("reserved");
|
||||
this.style.removeProperty("--ha-skeleton-overlay-reserved-height");
|
||||
}
|
||||
|
||||
/* Remember the size the content settles into once it has loaded */
|
||||
private _rememberWhenSettled() {
|
||||
const key = this.skeletonKey;
|
||||
|
||||
if (!key) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._settleObserver = new ResizeObserver(() => {
|
||||
const { width, height } = this.getBoundingClientRect();
|
||||
|
||||
if (width && height) {
|
||||
rememberSkeletonHeight(key, width, height);
|
||||
}
|
||||
});
|
||||
this._settleObserver.observe(this);
|
||||
this._settleTimeout = window.setTimeout(
|
||||
() => this._stopRemembering(),
|
||||
SETTLE_TIME
|
||||
);
|
||||
}
|
||||
|
||||
private _stopRemembering() {
|
||||
this._settleObserver?.disconnect();
|
||||
this._settleObserver = undefined;
|
||||
clearTimeout(this._settleTimeout);
|
||||
this._settleTimeout = undefined;
|
||||
}
|
||||
|
||||
private _hideParts(skeleton: ExtractedSkeleton) {
|
||||
skeleton.parts.forEach((part) => {
|
||||
this._hiddenOpacity.set(part, part.style.opacity);
|
||||
part.style.opacity = "0";
|
||||
});
|
||||
|
||||
// Text goes through its colour, so a frame drawn by the same element,
|
||||
// such as a badge's pill, stays
|
||||
skeleton.textParts.forEach((part) => {
|
||||
this._hiddenColor.set(part, part.style.color);
|
||||
part.style.color = "transparent";
|
||||
});
|
||||
}
|
||||
|
||||
private _showParts() {
|
||||
this._hiddenOpacity.forEach((opacity, part) => {
|
||||
part.style.opacity = opacity;
|
||||
});
|
||||
this._hiddenColor.forEach((color, part) => {
|
||||
part.style.color = color;
|
||||
});
|
||||
this._hiddenOpacity.clear();
|
||||
this._hiddenColor.clear();
|
||||
}
|
||||
|
||||
/* Show the content again before the next paint, and note what to fade in */
|
||||
private _endLoading() {
|
||||
// Under a skeleton of its own, or with nothing read from it, the whole
|
||||
// content was hidden or not there yet, rather than its parts
|
||||
const wholeContent = this._customSkeleton || !this._pieces?.length;
|
||||
|
||||
this._arriving = {
|
||||
content: wholeContent
|
||||
? (this._contentSlot?.assignedElements() ?? [])
|
||||
: [],
|
||||
opacityParts: [...this._hiddenOpacity.keys()],
|
||||
colorParts: [...this._hiddenColor.keys()],
|
||||
};
|
||||
|
||||
this._showParts();
|
||||
this._release();
|
||||
this._pieces = undefined;
|
||||
}
|
||||
|
||||
/* Fade each arriving part in, instantly with reduced motion */
|
||||
private _fadeIn({ content, opacityParts, colorParts }: ArrivingParts) {
|
||||
const fade: KeyframeAnimationOptions = {
|
||||
duration:
|
||||
parseFloat(
|
||||
getComputedStyle(this).getPropertyValue(
|
||||
"--ha-animation-duration-fast"
|
||||
)
|
||||
) || 150,
|
||||
easing: "ease-out",
|
||||
};
|
||||
|
||||
[...content, ...opacityParts].forEach((part) =>
|
||||
part.animate([{ opacity: 0 }, { opacity: 1 }], fade)
|
||||
);
|
||||
colorParts.forEach((part) => {
|
||||
const color = getComputedStyle(part).color;
|
||||
part.animate([{ color: "transparent" }, { color }], fade);
|
||||
});
|
||||
}
|
||||
|
||||
static readonly styles: CSSResultGroup = css`
|
||||
:host {
|
||||
display: block;
|
||||
position: relative;
|
||||
}
|
||||
/* Holds the size the content had last time, and stretches the content
|
||||
to fill it */
|
||||
:host([reserved]) {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
:host([reserved])::before {
|
||||
content: "";
|
||||
grid-area: 1 / 1;
|
||||
height: var(--ha-skeleton-overlay-reserved-height);
|
||||
}
|
||||
:host([reserved]) ::slotted(*) {
|
||||
grid-area: 1 / 1;
|
||||
}
|
||||
slot.hidden::slotted(*) {
|
||||
opacity: 0;
|
||||
}
|
||||
.skeleton {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
overflow: hidden;
|
||||
border-radius: inherit;
|
||||
pointer-events: none;
|
||||
}
|
||||
/* Rounded by the layer it fills, which follows the host */
|
||||
.fill {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
--ha-skeleton-border-radius: 0;
|
||||
}
|
||||
.piece {
|
||||
position: absolute;
|
||||
min-height: 0;
|
||||
}
|
||||
.piece.round {
|
||||
--ha-skeleton-border-radius: var(--ha-border-radius-circle);
|
||||
}
|
||||
.piece.shape {
|
||||
--ha-skeleton-border-radius: 0;
|
||||
mask-size: 100% 100%;
|
||||
-webkit-mask-size: 100% 100%;
|
||||
}
|
||||
/* Text and icons on a dark bar over a picture */
|
||||
.piece.on-dark {
|
||||
--ha-skeleton-color: rgba(255, 255, 255, 0.3);
|
||||
--ha-skeleton-sheen-color: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
const pieceStyle = (piece: SkeletonPiece) =>
|
||||
styleMap({
|
||||
left: `${piece.x}px`,
|
||||
top: `${piece.y}px`,
|
||||
width: `${piece.width}px`,
|
||||
height: `${piece.height}px`,
|
||||
"--ha-skeleton-border-radius": piece.radius,
|
||||
"border-radius": piece.kind === "scrim" ? piece.radius : undefined,
|
||||
"background-color": piece.background,
|
||||
"mask-image": piece.mask,
|
||||
"-webkit-mask-image": piece.mask,
|
||||
});
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-skeleton-overlay": HaSkeletonOverlay;
|
||||
}
|
||||
|
||||
interface HASSDomEvents {
|
||||
"skeleton-loading": SkeletonLoadingDetail;
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,9 @@ import { HaSkeleton } from "./ha-skeleton";
|
||||
|
||||
/**
|
||||
* Placeholder for a line of text, matching the tile secondary text skeleton.
|
||||
* Its height follows the surrounding font size. Set `width` in CSS to fit the
|
||||
* expected text.
|
||||
* It takes the height of the surrounding line, so swapping it for the text
|
||||
* doesn't move anything, and draws a thinner bar in the middle of it. Set
|
||||
* `width` in CSS to fit the expected text.
|
||||
*
|
||||
* @cssprop --ha-skeleton-text-width - The width of the placeholder. Defaults to `140px`.
|
||||
*/
|
||||
@@ -19,11 +20,16 @@ export class HaSkeletonText extends HaSkeleton {
|
||||
:host {
|
||||
display: inline-flex;
|
||||
vertical-align: middle;
|
||||
align-items: center;
|
||||
width: var(--ha-skeleton-text-width, 140px);
|
||||
max-width: 100%;
|
||||
height: 1em;
|
||||
height: 1.2em;
|
||||
height: 1lh;
|
||||
min-height: 0;
|
||||
}
|
||||
.indicator {
|
||||
height: 0.75em;
|
||||
}
|
||||
`,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -1,19 +1,152 @@
|
||||
import WaSkeleton from "@home-assistant/webawesome/dist/components/skeleton/skeleton";
|
||||
import type { CSSResultGroup } from "lit";
|
||||
import { css } from "lit";
|
||||
import { customElement } from "lit/decorators";
|
||||
import type { CSSResultGroup, PropertyValues } from "lit";
|
||||
import { css, html } from "lit";
|
||||
import { customElement, query } from "lit/decorators";
|
||||
|
||||
/* How far the wave leans from upright, so it starts at the top corner of the
|
||||
content and finishes at the opposite bottom corner */
|
||||
const WAVE_SLANT_DEG = 20;
|
||||
|
||||
const WAVE_SLANT = Math.tan((WAVE_SLANT_DEG * Math.PI) / 180);
|
||||
|
||||
/**
|
||||
* Placeholder shown while content loads. Sized by its container unless a
|
||||
* more specific variant such as `ha-skeleton-text` or `ha-skeleton-icon` is used.
|
||||
*
|
||||
* A soft wave sweeps across it by default. It's one slanted wave across all
|
||||
* the skeletons on the page, from the top corner of the content on the side
|
||||
* text starts from to the opposite bottom corner: each skeleton shows its
|
||||
* own slice of it, and all of them run in step, so the wave flows from one
|
||||
* skeleton into the next, and a skeleton added later joins mid-sweep instead
|
||||
* of starting over. Each sweep starts as the last one leaves the content.
|
||||
*
|
||||
* @cssprop --ha-skeleton-color - The fill color. Defaults to `var(--ha-color-fill-neutral-normal-resting)`.
|
||||
* @cssprop --ha-skeleton-sheen-color - The sheen color when `effect="sheen"`. Defaults to `var(--ha-color-fill-neutral-loud-resting)`.
|
||||
* @cssprop --ha-skeleton-sheen-color - The sheen color when `effect="sheen"`. Defaults to `var(--ha-color-fill-neutral-normal-hover)`.
|
||||
* @cssprop --ha-skeleton-border-radius - The corner radius. Defaults to `var(--ha-border-radius-sm)`.
|
||||
* @cssprop --ha-skeleton-duration - How long one sweep across the skeletons takes when `effect="sheen"`. Defaults to `3s`.
|
||||
*/
|
||||
@customElement("ha-skeleton")
|
||||
export class HaSkeleton extends WaSkeleton {
|
||||
override effect: WaSkeleton["effect"] = "pulse";
|
||||
override effect: WaSkeleton["effect"] = "sheen";
|
||||
|
||||
/* Every skeleton showing the wave, which share one track */
|
||||
private static _waving = new Set<HaSkeleton>();
|
||||
|
||||
private static _trackFrame?: number;
|
||||
|
||||
@query(".wave") private _wave?: HTMLDivElement;
|
||||
|
||||
private _resizeObserver?: ResizeObserver;
|
||||
|
||||
/**
|
||||
* Lay the one track the wave runs along over the content: the box around
|
||||
* all the skeletons, so no time goes on empty space around them. The wave
|
||||
* leans, so it enters at the box's top corner and has to travel further,
|
||||
* by the box's height times the slant, to clear the opposite bottom
|
||||
* corner. It's measured again whenever a skeleton comes, goes or changes
|
||||
* size, and at the end of each sweep, so it follows the layout as it moves.
|
||||
*/
|
||||
private static _scheduleTrack() {
|
||||
if (HaSkeleton._trackFrame !== undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
HaSkeleton._trackFrame = requestAnimationFrame(() => {
|
||||
HaSkeleton._trackFrame = undefined;
|
||||
|
||||
// Read every skeleton before writing any, so layout runs once
|
||||
const boxes = [...HaSkeleton._waving].flatMap((skeleton) => {
|
||||
const rect = skeleton.getBoundingClientRect();
|
||||
const rtl = getComputedStyle(skeleton).direction === "rtl";
|
||||
|
||||
return rect.width > 0 ? [{ skeleton, rect, rtl }] : [];
|
||||
});
|
||||
|
||||
if (boxes.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const left = Math.min(...boxes.map(({ rect }) => rect.left));
|
||||
const right = Math.max(...boxes.map(({ rect }) => rect.right));
|
||||
const top = Math.min(...boxes.map(({ rect }) => rect.top));
|
||||
const bottom = Math.max(...boxes.map(({ rect }) => rect.bottom));
|
||||
const trackLength = right - left + (bottom - top) * WAVE_SLANT;
|
||||
|
||||
boxes.forEach(({ skeleton, rect, rtl }) => {
|
||||
// Right to left, the wave is drawn mirrored, so it's placed from the
|
||||
// right edge instead
|
||||
const start = rtl ? rect.right - right : left - rect.left;
|
||||
|
||||
// Lower down, the slanted wave arrives later
|
||||
skeleton._placeWave(start - (rect.top - top) * WAVE_SLANT, trackLength);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public connectedCallback() {
|
||||
super.connectedCallback();
|
||||
this._resizeObserver ??= new ResizeObserver(() =>
|
||||
HaSkeleton._scheduleTrack()
|
||||
);
|
||||
this._resizeObserver.observe(this);
|
||||
|
||||
if (this.effect === "sheen") {
|
||||
HaSkeleton._waving.add(this);
|
||||
HaSkeleton._scheduleTrack();
|
||||
}
|
||||
}
|
||||
|
||||
public disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
this._resizeObserver?.disconnect();
|
||||
HaSkeleton._waving.delete(this);
|
||||
HaSkeleton._scheduleTrack();
|
||||
}
|
||||
|
||||
public override render() {
|
||||
return html`
|
||||
<div part="indicator" class="indicator">
|
||||
<div
|
||||
class="wave"
|
||||
@animationiteration=${HaSkeleton._scheduleTrack}
|
||||
></div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
protected updated(changedProperties: PropertyValues<this>) {
|
||||
super.updated(changedProperties);
|
||||
|
||||
if (changedProperties.has("effect")) {
|
||||
if (this.effect === "sheen") {
|
||||
HaSkeleton._waving.add(this);
|
||||
} else {
|
||||
HaSkeleton._waving.delete(this);
|
||||
}
|
||||
|
||||
HaSkeleton._scheduleTrack();
|
||||
}
|
||||
}
|
||||
|
||||
/* Put this skeleton's slice of the wave in its place on the track */
|
||||
private _placeWave(trackStart: number, trackLength: number) {
|
||||
const wave = this._wave;
|
||||
|
||||
if (!wave) {
|
||||
return;
|
||||
}
|
||||
|
||||
wave.style.left = `${trackStart}px`;
|
||||
wave.style.setProperty("--ha-skeleton-track-width", `${trackLength}px`);
|
||||
wave.style.setProperty("--ha-skeleton-slant", `${-WAVE_SLANT_DEG}deg`);
|
||||
|
||||
// All waves count from the same moment, so they stay in step
|
||||
wave.getAnimations().forEach((animation) => {
|
||||
if (animation.startTime !== 0) {
|
||||
animation.startTime = 0;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static get styles(): CSSResultGroup {
|
||||
return [
|
||||
@@ -26,13 +159,59 @@ export class HaSkeleton extends WaSkeleton {
|
||||
);
|
||||
--sheen-color: var(
|
||||
--ha-skeleton-sheen-color,
|
||||
var(--ha-color-fill-neutral-loud-resting)
|
||||
var(--ha-color-fill-neutral-normal-hover)
|
||||
);
|
||||
--wa-border-radius-pill: var(
|
||||
--ha-skeleton-border-radius,
|
||||
var(--ha-border-radius-sm)
|
||||
);
|
||||
}
|
||||
.wave {
|
||||
display: none;
|
||||
}
|
||||
:host([effect="sheen"]) .indicator {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
background: var(--color);
|
||||
animation: none;
|
||||
}
|
||||
/* Right to left, the wave is drawn mirrored, so it starts from the
|
||||
top right corner */
|
||||
:host([effect="sheen"]:dir(rtl)) .indicator {
|
||||
transform: scaleX(-1);
|
||||
}
|
||||
/* The wave crosses the track over all the skeletons, placed from its
|
||||
start and leaning back from its top edge, and moves with transform
|
||||
so it stays cheap */
|
||||
:host([effect="sheen"]) .wave {
|
||||
display: block;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
width: 400px;
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
transparent,
|
||||
var(--sheen-color),
|
||||
transparent
|
||||
);
|
||||
transform-origin: top left;
|
||||
transform: translateX(-100%) skewX(var(--ha-skeleton-slant, 0deg));
|
||||
/* An even pace with no hold, so the next sweep enters as soon as
|
||||
the last one leaves */
|
||||
animation: ha-skeleton-sheen var(--ha-skeleton-duration, 3s) linear
|
||||
infinite;
|
||||
}
|
||||
@keyframes ha-skeleton-sheen {
|
||||
from {
|
||||
transform: translateX(-100%) skewX(var(--ha-skeleton-slant, 0deg));
|
||||
}
|
||||
to {
|
||||
transform: translateX(var(--ha-skeleton-track-width, 100vw))
|
||||
skewX(var(--ha-skeleton-slant, 0deg));
|
||||
}
|
||||
}
|
||||
@media (forced-colors: active) {
|
||||
:host {
|
||||
--color: GrayText;
|
||||
@@ -40,9 +219,12 @@ export class HaSkeleton extends WaSkeleton {
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
:host([effect="pulse"]) .indicator,
|
||||
:host([effect="sheen"]) .indicator {
|
||||
:host([effect="sheen"]) .wave {
|
||||
animation: none;
|
||||
}
|
||||
:host([effect="sheen"]) .wave {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import type { nothing, TemplateResult } from "lit";
|
||||
import { css, html } from "lit";
|
||||
import type {
|
||||
ChildPart,
|
||||
DirectiveParameters,
|
||||
DirectiveResult,
|
||||
PartInfo,
|
||||
} from "lit/directive";
|
||||
import { Directive, directive, PartType } from "lit/directive";
|
||||
|
||||
/* What a skeleton or its content can be rendered as */
|
||||
type SkeletonOrValue =
|
||||
| TemplateResult
|
||||
| DirectiveResult
|
||||
| string
|
||||
| number
|
||||
| typeof nothing
|
||||
| null
|
||||
| undefined;
|
||||
|
||||
/**
|
||||
* Content that takes a skeleton's place fades in, so it doesn't pop in. It
|
||||
* runs at the same pace as `ha-skeleton-overlay`, `--ha-animation-duration-fast`,
|
||||
* which reduced motion makes instant.
|
||||
*/
|
||||
|
||||
const ARRIVAL_KEYFRAMES: Keyframe[] = [{ opacity: 0 }, { opacity: 1 }];
|
||||
|
||||
/**
|
||||
* Fade in an element that takes a skeleton's place but was already on the
|
||||
* page, such as a log that fills in while its skeleton shows.
|
||||
*/
|
||||
export const fadeInArrival = (element: Element) => {
|
||||
const duration =
|
||||
parseFloat(
|
||||
getComputedStyle(element).getPropertyValue("--ha-animation-duration-fast")
|
||||
) || 150;
|
||||
|
||||
element.animate(ARRIVAL_KEYFRAMES, { duration, easing: "ease-out" });
|
||||
};
|
||||
|
||||
/**
|
||||
* For a whole block that replaces a skeleton: put the `arriving` class on it,
|
||||
* and it fades in once, when it first appears. Where it can appear again
|
||||
* without a skeleton before it, use `skeletonOr` instead.
|
||||
*/
|
||||
export const skeletonArrivalStyles = css`
|
||||
.arriving {
|
||||
animation: ha-skeleton-arrival var(--ha-animation-duration-fast, 150ms)
|
||||
ease-out;
|
||||
}
|
||||
@keyframes ha-skeleton-arrival {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
class SkeletonOrDirective extends Directive {
|
||||
/* What this spot showed last time */
|
||||
private _showedSkeleton = false;
|
||||
|
||||
/* Text needs an element to fade, so it's wrapped once it has arrived */
|
||||
private _wrapText = false;
|
||||
|
||||
constructor(partInfo: PartInfo) {
|
||||
super(partInfo);
|
||||
|
||||
if (partInfo.type !== PartType.CHILD) {
|
||||
throw new Error("skeletonOr can only be used in content bindings");
|
||||
}
|
||||
}
|
||||
|
||||
public render(
|
||||
loading: boolean,
|
||||
skeleton: SkeletonOrValue,
|
||||
content: () => SkeletonOrValue
|
||||
): SkeletonOrValue {
|
||||
if (loading) {
|
||||
return skeleton;
|
||||
}
|
||||
|
||||
const value = content();
|
||||
|
||||
return this._wrapText &&
|
||||
(typeof value === "string" || typeof value === "number")
|
||||
? html`<span>${value}</span>`
|
||||
: value;
|
||||
}
|
||||
|
||||
public update(
|
||||
part: ChildPart,
|
||||
[loading, skeleton, content]: DirectiveParameters<this>
|
||||
) {
|
||||
const arriving = !loading && this._showedSkeleton;
|
||||
this._showedSkeleton = loading;
|
||||
|
||||
if (arriving) {
|
||||
this._wrapText = true;
|
||||
|
||||
// Fade in what was rendered, once it's on the page
|
||||
requestAnimationFrame(() => {
|
||||
let node = part.startNode?.nextSibling;
|
||||
|
||||
while (node && node !== part.endNode) {
|
||||
if (node instanceof Element) {
|
||||
fadeInArrival(node);
|
||||
}
|
||||
|
||||
node = node.nextSibling;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return this.render(loading, skeleton, content);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows `skeleton` while `loading`, then `content`. When this spot switches
|
||||
* from the skeleton to the content, the content fades in. A spot that never
|
||||
* showed a skeleton, such as a table row made as the table scrolls, shows its
|
||||
* content at once.
|
||||
*
|
||||
* Content that's only text is wrapped so it can fade. In a template, put text
|
||||
* in an element of its own, as only elements fade.
|
||||
*/
|
||||
export const skeletonOr = directive(SkeletonOrDirective);
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { ReactiveController, ReactiveControllerHost } from "lit";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
|
||||
/**
|
||||
* Tells the nearest `ha-skeleton-overlay` around a component when it starts
|
||||
* and stops loading, through `skeleton-loading` events. The component
|
||||
* doesn't need to know whether anything wraps it: without an overlay, the
|
||||
* events go nowhere.
|
||||
*
|
||||
* `isLoading` is read after every update of the host.
|
||||
*/
|
||||
export class SkeletonLoadingController implements ReactiveController {
|
||||
private _host: ReactiveControllerHost & HTMLElement;
|
||||
|
||||
private _isLoading: () => boolean;
|
||||
|
||||
private _loading = false;
|
||||
|
||||
constructor(
|
||||
host: ReactiveControllerHost & HTMLElement,
|
||||
isLoading: () => boolean
|
||||
) {
|
||||
this._host = host;
|
||||
this._isLoading = isLoading;
|
||||
host.addController(this);
|
||||
}
|
||||
|
||||
public hostConnected() {
|
||||
// A new overlay may be around it now
|
||||
if (this._loading) {
|
||||
fireEvent(this._host, "skeleton-loading", { loading: true });
|
||||
}
|
||||
}
|
||||
|
||||
public hostUpdated() {
|
||||
const loading = this._isLoading();
|
||||
|
||||
if (loading !== this._loading) {
|
||||
this._loading = loading;
|
||||
fireEvent(this._host, "skeleton-loading", { loading });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
/* How tall content was once loaded last time, so its skeleton can hold the
|
||||
same space while it loads again. Content wraps differently at other
|
||||
widths, so each width is remembered on its own. */
|
||||
|
||||
const STORAGE_KEY = "skeletonHeights";
|
||||
|
||||
/* Widths this close together share a height */
|
||||
const WIDTH_STEP = 16;
|
||||
|
||||
/* The most recently loaded ones are kept, the oldest dropped: about 20 bytes
|
||||
each */
|
||||
const MAX_HEIGHTS = 500;
|
||||
|
||||
let heights: Map<string, number> | undefined;
|
||||
|
||||
let saveTimeout: number | undefined;
|
||||
|
||||
const readHeights = (): Map<string, number> => {
|
||||
const read = new Map<string, number>();
|
||||
|
||||
try {
|
||||
const stored: unknown = JSON.parse(
|
||||
window.localStorage.getItem(STORAGE_KEY) ?? "{}"
|
||||
);
|
||||
|
||||
if (stored instanceof Object && !Array.isArray(stored)) {
|
||||
Object.entries(stored).forEach(([key, height]) => {
|
||||
if (Number.isFinite(height)) {
|
||||
read.set(key, Number(height));
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// Unreadable heights are only lost hints
|
||||
}
|
||||
|
||||
return read;
|
||||
};
|
||||
|
||||
const loadHeights = (): Map<string, number> => {
|
||||
heights ??= readHeights();
|
||||
|
||||
return heights;
|
||||
};
|
||||
|
||||
const saveHeights = () => {
|
||||
saveTimeout = undefined;
|
||||
|
||||
try {
|
||||
window.localStorage.setItem(
|
||||
STORAGE_KEY,
|
||||
JSON.stringify(Object.fromEntries(loadHeights()))
|
||||
);
|
||||
} catch {
|
||||
// Private mode or full storage: the skeleton just won't hold the space
|
||||
}
|
||||
};
|
||||
|
||||
const widthKey = (key: string, width: number) =>
|
||||
`${key}@${Math.round(width / WIDTH_STEP)}`;
|
||||
|
||||
export const rememberedSkeletonHeight = (
|
||||
key: string,
|
||||
width: number
|
||||
): number | undefined => loadHeights().get(widthKey(key, width));
|
||||
|
||||
export const rememberSkeletonHeight = (
|
||||
key: string,
|
||||
width: number,
|
||||
height: number
|
||||
) => {
|
||||
const stored = loadHeights();
|
||||
const entryKey = widthKey(key, width);
|
||||
|
||||
// Moved to the end, as the most recently loaded
|
||||
stored.delete(entryKey);
|
||||
stored.set(entryKey, Math.round(height));
|
||||
|
||||
while (stored.size > MAX_HEIGHTS) {
|
||||
const [oldest] = stored.keys();
|
||||
stored.delete(oldest);
|
||||
}
|
||||
|
||||
// A view loads many at once, so they're saved together
|
||||
if (saveTimeout === undefined) {
|
||||
saveTimeout = window.setTimeout(saveHeights, 1000);
|
||||
}
|
||||
};
|
||||
|
||||
/* A short, stable key for a longer text, such as a card's config as JSON */
|
||||
export const skeletonKey = (text: string): string => {
|
||||
let hash = 5381;
|
||||
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
hash = (hash * 33 + text.charCodeAt(i)) % 2147483647;
|
||||
}
|
||||
|
||||
return `${hash.toString(36)}${text.length.toString(36)}`;
|
||||
};
|
||||
@@ -1,6 +1,7 @@
|
||||
import "../skeleton/ha-skeleton-text";
|
||||
import { css, html, LitElement } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import { skeletonOr } from "../skeleton/skeleton-arrival";
|
||||
|
||||
/**
|
||||
* Home Assistant tile info component
|
||||
@@ -46,15 +47,16 @@ export class HaTileInfo extends LitElement {
|
||||
<slot name="primary" class="primary">
|
||||
<span part="primary">${this.primary}</span>
|
||||
</slot>
|
||||
${
|
||||
this.secondaryLoading
|
||||
? html`<div class="secondary">
|
||||
<ha-skeleton-text></ha-skeleton-text>
|
||||
</div>`
|
||||
: html`<slot name="secondary" class="secondary">
|
||||
<span>${this.secondary}</span>
|
||||
</slot>`
|
||||
}
|
||||
${skeletonOr(
|
||||
this.secondaryLoading,
|
||||
html`<div class="secondary">
|
||||
<ha-skeleton-text></ha-skeleton-text>
|
||||
</div>`,
|
||||
() =>
|
||||
html`<slot name="secondary" class="secondary">
|
||||
<span>${this.secondary}</span>
|
||||
</slot>`
|
||||
)}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
consumeContext,
|
||||
ContextController,
|
||||
} from "../common/decorators/consume";
|
||||
import { SkeletonLoadingController } from "../components/skeleton/skeleton-loading-controller";
|
||||
import {
|
||||
apiContext,
|
||||
configContext,
|
||||
@@ -19,7 +20,7 @@ import {
|
||||
uiContext,
|
||||
} from "./context";
|
||||
import type { EnergyCollection, EnergyData } from "./energy";
|
||||
import { getEnergyDataCollection } from "./energy";
|
||||
import { getEnergyDataCollection, hasCombinableEnergySources } from "./energy";
|
||||
import type { FrontendLocaleData } from "./translation";
|
||||
import type { HomeAssistant } from "../types";
|
||||
|
||||
@@ -28,6 +29,9 @@ export interface EnergyCollectionControllerOptions {
|
||||
config: () => { collection_key?: string } | undefined;
|
||||
beforeSubscribe?: (collection: EnergyCollection) => void;
|
||||
onData: (data: EnergyData) => void;
|
||||
/** Whether the host still loads once the data came, such as while it
|
||||
fetches more for it. The host shows a skeleton until it's done. */
|
||||
loading?: () => boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -87,18 +91,73 @@ export class EnergyCollectionController extends ContextController {
|
||||
|
||||
private _collection?: EnergyCollection;
|
||||
|
||||
/* Whether data has come since subscribing, so the host can show a
|
||||
skeleton until it does */
|
||||
private _hasData = false;
|
||||
|
||||
private _placeholderData?: EnergyData;
|
||||
|
||||
constructor(
|
||||
host: ReactiveControllerHost & HTMLElement,
|
||||
options: EnergyCollectionControllerOptions
|
||||
) {
|
||||
super(host);
|
||||
this._options = options;
|
||||
new SkeletonLoadingController(
|
||||
host,
|
||||
() =>
|
||||
this._unsub !== undefined &&
|
||||
(!this._hasData || this._options.loading?.() === true)
|
||||
);
|
||||
}
|
||||
|
||||
get collection(): EnergyCollection | undefined {
|
||||
return this._collection;
|
||||
}
|
||||
|
||||
/**
|
||||
* The data the host is about to get, without its statistics, once the
|
||||
* collection knows the energy preferences. A host can draw its real layout
|
||||
* from it under its skeleton, so the skeleton has the size of what comes.
|
||||
* The energy dashboard builds its cards from the preferences, so they are
|
||||
* known there before the first card renders.
|
||||
*/
|
||||
get placeholderData(): EnergyData | undefined {
|
||||
const collection = this._collection;
|
||||
const prefs = collection?.prefs;
|
||||
|
||||
if (!collection || !prefs || this._hasData) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// The same object each time, so hosts don't redraw for nothing
|
||||
const cached = this._placeholderData;
|
||||
|
||||
if (
|
||||
cached?.prefs === prefs &&
|
||||
cached.start === collection.start &&
|
||||
cached.end === collection.end
|
||||
) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
this._placeholderData = {
|
||||
start: collection.start,
|
||||
end: collection.end,
|
||||
prefs,
|
||||
combineSources: hasCombinableEnergySources(prefs)
|
||||
? collection.combineSources
|
||||
: undefined,
|
||||
info: { cost_sensors: {}, solar_forecast_domains: [] },
|
||||
stats: {},
|
||||
statsMetadata: {},
|
||||
waterUnit: "",
|
||||
gasUnit: "",
|
||||
};
|
||||
|
||||
return this._placeholderData;
|
||||
}
|
||||
|
||||
hostConnected(): void {
|
||||
this._connected = true;
|
||||
this._subscribe();
|
||||
@@ -142,6 +201,7 @@ export class EnergyCollectionController extends ContextController {
|
||||
}
|
||||
this._unsubscribe();
|
||||
this._key = key;
|
||||
this._hasData = false;
|
||||
this._collection = getEnergyDataCollection(this._connection, {
|
||||
callWS: this._callWS,
|
||||
entities: this._entities,
|
||||
@@ -152,7 +212,18 @@ export class EnergyCollectionController extends ContextController {
|
||||
key,
|
||||
});
|
||||
this._options.beforeSubscribe?.(this._collection);
|
||||
this._unsub = this._collection.subscribe(this._options.onData);
|
||||
|
||||
this._unsub = this._collection.subscribe((data) => {
|
||||
this._hasData = true;
|
||||
this._options.onData(data);
|
||||
// So the skeleton goes even if the host keeps nothing new
|
||||
this.host.requestUpdate();
|
||||
});
|
||||
|
||||
// So the host shows a skeleton until the data comes
|
||||
if (!this._hasData) {
|
||||
this.host.requestUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
private _unsubscribe(): void {
|
||||
|
||||
+3
-2
@@ -632,7 +632,8 @@ export interface EnergyData {
|
||||
info: EnergyInfo;
|
||||
stats: Statistics;
|
||||
statsMetadata: Record<string, StatisticsMetaData>;
|
||||
statsCompare: Statistics;
|
||||
// Only while comparing with an earlier period
|
||||
statsCompare?: Statistics;
|
||||
co2SignalEntity?: string;
|
||||
fossilEnergyConsumption?: FossilEnergyConsumption;
|
||||
fossilEnergyConsumptionCompare?: FossilEnergyConsumption;
|
||||
@@ -1974,7 +1975,7 @@ const getSummedDataPartial = (
|
||||
const totalStats: Record<number, number> = {};
|
||||
let sum = 0;
|
||||
subStatIds!.forEach((id) => {
|
||||
const stats = compare ? data.statsCompare[id] : data.stats[id];
|
||||
const stats = compare ? data.statsCompare?.[id] : data.stats[id];
|
||||
if (!stats) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type {
|
||||
HassConfig,
|
||||
HassEntities,
|
||||
HassEntity,
|
||||
HassEntityAttributeBase,
|
||||
MessageBase,
|
||||
@@ -744,6 +745,52 @@ export const isTimelineEntity = (
|
||||
!isNumericEntity(domain, currentState, undefined) &&
|
||||
!LINE_CHART_DOMAINS.includes(domain);
|
||||
|
||||
export interface ExpectedHistoryCharts {
|
||||
lines: number;
|
||||
timelineRows: number;
|
||||
}
|
||||
|
||||
/* How many line charts and timeline rows `computeHistory` will draw these
|
||||
entities' history in, guessed from their current states, so their space
|
||||
can be held while it loads */
|
||||
export const expectedHistoryCharts = (
|
||||
entityIds: string[],
|
||||
states: HassEntities,
|
||||
temperatureUnit: string,
|
||||
splitDeviceClasses = false
|
||||
): ExpectedHistoryCharts => {
|
||||
const lineGroups = new Set<string | undefined>();
|
||||
|
||||
let timelineRows = 0;
|
||||
|
||||
entityIds.forEach((entityId) => {
|
||||
const domain = computeDomain(entityId);
|
||||
|
||||
const stateObj: HassEntity | undefined = states[entityId];
|
||||
|
||||
if (isTimelineEntity(domain, stateObj)) {
|
||||
timelineRows++;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const unit = isNumericEntity(domain, stateObj, undefined)
|
||||
? stateObj?.attributes.unit_of_measurement || BLANK_UNIT
|
||||
: ({
|
||||
climate: temperatureUnit,
|
||||
humidifier: "%",
|
||||
water_heater: temperatureUnit,
|
||||
}[domain] ?? domain);
|
||||
|
||||
const deviceClass =
|
||||
SPECIAL_DOMAIN_CLASSES[domain] || stateObj?.attributes.device_class;
|
||||
|
||||
lineGroups.add(computeGroupKey(unit, deviceClass, splitDeviceClasses));
|
||||
});
|
||||
|
||||
return { lines: lineGroups.size, timelineRows };
|
||||
};
|
||||
|
||||
export const mergeHistoryResults = (
|
||||
historyResult: HistoryResult,
|
||||
ltsResult?: HistoryResult,
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import "../../../../components/skeleton/ha-skeleton";
|
||||
import "../../../../components/skeleton/ha-skeleton-text";
|
||||
import type { HassConfig } from "home-assistant-js-websocket";
|
||||
import type { PropertyValues } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import {
|
||||
fadeInArrival,
|
||||
skeletonOr,
|
||||
} from "../../../../components/skeleton/skeleton-arrival";
|
||||
import { consume } from "../../../../common/decorators/consume";
|
||||
import { isComponentLoaded } from "../../../../common/config/is_component_loaded";
|
||||
import { relativeTime } from "../../../../common/datetime/relative_time";
|
||||
@@ -65,6 +70,8 @@ export class HaMoreInfoUpdateBackup extends LitElement {
|
||||
|
||||
@state() private _entitySources?: EntitySources;
|
||||
|
||||
@query("ha-row-item") private _rowItem?: HTMLElement;
|
||||
|
||||
@consume({ context: apiContext, subscribe: true })
|
||||
private _api!: HomeAssistantApi;
|
||||
|
||||
@@ -91,6 +98,19 @@ export class HaMoreInfoUpdateBackup extends LitElement {
|
||||
this._setupBackup();
|
||||
}
|
||||
|
||||
protected updated(changedProps: PropertyValues) {
|
||||
super.updated(changedProps);
|
||||
|
||||
// The row's text takes its skeleton's place
|
||||
if (
|
||||
changedProps.get("_backupConfigLoading") === true &&
|
||||
!this._backupConfigLoading &&
|
||||
this._rowItem
|
||||
) {
|
||||
fadeInArrival(this._rowItem);
|
||||
}
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (
|
||||
!this.stateObj ||
|
||||
@@ -119,19 +139,20 @@ export class HaMoreInfoUpdateBackup extends LitElement {
|
||||
></ha-fade-in>`
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
this._createBackupLoading
|
||||
? html`<ha-fade-in class="skeleton-end" slot="end" .delay=${500}
|
||||
><ha-skeleton></ha-skeleton
|
||||
></ha-fade-in>`
|
||||
: html`<ha-switch
|
||||
slot="end"
|
||||
.accessibleLabel=${createBackupTexts?.title ?? ""}
|
||||
.checked=${this._createBackup}
|
||||
@change=${this._createBackupChanged}
|
||||
.disabled=${this.disabled || updateIsInstalling(this.stateObj)}
|
||||
></ha-switch>`
|
||||
}
|
||||
${skeletonOr(
|
||||
this._createBackupLoading,
|
||||
html`<ha-fade-in class="skeleton-end" slot="end" .delay=${500}
|
||||
><ha-skeleton></ha-skeleton
|
||||
></ha-fade-in>`,
|
||||
() =>
|
||||
html`<ha-switch
|
||||
slot="end"
|
||||
.accessibleLabel=${createBackupTexts?.title ?? ""}
|
||||
.checked=${this._createBackup}
|
||||
@change=${this._createBackupChanged}
|
||||
.disabled=${this.disabled || updateIsInstalling(this.stateObj!)}
|
||||
></ha-switch>`
|
||||
)}
|
||||
</ha-row-item>
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { consume } from "../common/decorators/consume";
|
||||
import "../components/ha-card";
|
||||
import "../components/ha-ripple";
|
||||
import "../components/ha-svg-icon";
|
||||
import { skeletonOr } from "../components/skeleton/skeleton-arrival";
|
||||
import { translationsReadyContext } from "../mixins/lit-localize-lite-mixin";
|
||||
import { renderSkeleton, skeletonStyles } from "./render-skeleton";
|
||||
|
||||
@@ -29,7 +30,11 @@ class OnboardingWelcomeLink extends LitElement {
|
||||
@keydown=${this._handleKeyDown}
|
||||
>
|
||||
<ha-svg-icon .path=${this.iconPath}></ha-svg-icon>
|
||||
${this._translationsReady === false ? renderSkeleton("label") : this.label}
|
||||
${skeletonOr(
|
||||
this._translationsReady === false,
|
||||
renderSkeleton("label"),
|
||||
() => this.label
|
||||
)}
|
||||
<ha-ripple></ha-ripple>
|
||||
</ha-card>
|
||||
`;
|
||||
|
||||
@@ -10,6 +10,7 @@ import "../components/ha-button";
|
||||
import "../components/ha-icon-next";
|
||||
import "../components/item/ha-list-item-button";
|
||||
import "../components/list/ha-list-base";
|
||||
import { skeletonOr } from "../components/skeleton/skeleton-arrival";
|
||||
import { translationsReadyContext } from "../mixins/lit-localize-lite-mixin";
|
||||
import { renderSkeleton, skeletonStyles } from "./render-skeleton";
|
||||
import { onBoardingStyles } from "./styles";
|
||||
@@ -28,37 +29,29 @@ class OnboardingWelcome extends LitElement {
|
||||
const ready = this._translationsReady;
|
||||
return html`
|
||||
<h1>
|
||||
${
|
||||
ready
|
||||
? this._localize("ui.panel.page-onboarding.welcome.header")
|
||||
: renderSkeleton("title")
|
||||
}
|
||||
${skeletonOr(!ready, renderSkeleton("title"), () =>
|
||||
this._localize("ui.panel.page-onboarding.welcome.header")
|
||||
)}
|
||||
</h1>
|
||||
<p>
|
||||
${
|
||||
ready
|
||||
? this._localize("ui.panel.page-onboarding.intro")
|
||||
: renderSkeleton("line")
|
||||
}
|
||||
${skeletonOr(!ready, renderSkeleton("line"), () =>
|
||||
this._localize("ui.panel.page-onboarding.intro")
|
||||
)}
|
||||
</p>
|
||||
|
||||
<ha-button @click=${this._start} class="start" .disabled=${!ready}>
|
||||
${
|
||||
ready
|
||||
? this._localize("ui.panel.page-onboarding.welcome.start")
|
||||
: renderSkeleton("button")
|
||||
}
|
||||
${skeletonOr(!ready, renderSkeleton("button"), () =>
|
||||
this._localize("ui.panel.page-onboarding.welcome.start")
|
||||
)}
|
||||
</ha-button>
|
||||
|
||||
<div class="divider">
|
||||
<wa-divider></wa-divider>
|
||||
<div>
|
||||
<span>
|
||||
${
|
||||
ready
|
||||
? this._localize("ui.panel.page-onboarding.welcome.or_restore")
|
||||
: renderSkeleton("chip")
|
||||
}
|
||||
${skeletonOr(!ready, renderSkeleton("chip"), () =>
|
||||
this._localize("ui.panel.page-onboarding.welcome.or_restore")
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -69,22 +62,16 @@ class OnboardingWelcome extends LitElement {
|
||||
.disabled=${!ready}
|
||||
>
|
||||
<div slot="headline">
|
||||
${
|
||||
ready
|
||||
? this._localize(
|
||||
"ui.panel.page-onboarding.restore.upload_backup"
|
||||
)
|
||||
: renderSkeleton("headline")
|
||||
}
|
||||
${skeletonOr(!ready, renderSkeleton("headline"), () =>
|
||||
this._localize("ui.panel.page-onboarding.restore.upload_backup")
|
||||
)}
|
||||
</div>
|
||||
<div slot="supporting-text">
|
||||
${
|
||||
ready
|
||||
? this._localize(
|
||||
"ui.panel.page-onboarding.restore.options.upload_description"
|
||||
)
|
||||
: renderSkeleton("line")
|
||||
}
|
||||
${skeletonOr(!ready, renderSkeleton("line"), () =>
|
||||
this._localize(
|
||||
"ui.panel.page-onboarding.restore.options.upload_description"
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
<ha-icon-next slot="end"></ha-icon-next>
|
||||
</ha-list-item-button>
|
||||
@@ -93,16 +80,18 @@ class OnboardingWelcome extends LitElement {
|
||||
.disabled=${!ready}
|
||||
>
|
||||
<div slot="headline">
|
||||
${ready ? "Home Assistant Link" : renderSkeleton("headline")}
|
||||
${skeletonOr(
|
||||
!ready,
|
||||
renderSkeleton("headline"),
|
||||
() => "Home Assistant Link"
|
||||
)}
|
||||
</div>
|
||||
<div slot="supporting-text">
|
||||
${
|
||||
ready
|
||||
? this._localize(
|
||||
"ui.panel.page-onboarding.restore.ha-cloud.description"
|
||||
)
|
||||
: renderSkeleton("line")
|
||||
}
|
||||
${skeletonOr(!ready, renderSkeleton("line"), () =>
|
||||
this._localize(
|
||||
"ui.panel.page-onboarding.restore.ha-cloud.description"
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
<ha-icon-next slot="end"></ha-icon-next>
|
||||
</ha-list-item-button>
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
state,
|
||||
} from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import { ifDefined } from "lit/directives/if-defined";
|
||||
import { repeat } from "lit/directives/repeat";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../../../../common/decorators/consume";
|
||||
@@ -27,6 +28,7 @@ import "../../../../components/item/ha-list-item-button";
|
||||
import "../../../../components/list/ha-list-base";
|
||||
import "../../../../components/skeleton/ha-skeleton";
|
||||
import "../../../../components/skeleton/ha-skeleton-text";
|
||||
import { skeletonOr } from "../../../../components/skeleton/skeleton-arrival";
|
||||
import type { ConfigEntry } from "../../../../data/config_entries";
|
||||
import {
|
||||
configEntriesContext,
|
||||
@@ -135,39 +137,39 @@ export class HaAutomationAddItems extends LitElement {
|
||||
})}
|
||||
@scroll=${this._onItemsScroll}
|
||||
>
|
||||
${
|
||||
this.loadingLabel
|
||||
? html`<ha-fade-in .duration=${300} easing="ease-in">
|
||||
<div
|
||||
class="skeletons"
|
||||
role="progressbar"
|
||||
aria-label=${this.loadingLabel}
|
||||
>
|
||||
<ha-skeleton-text></ha-skeleton-text>
|
||||
<ha-skeleton></ha-skeleton>
|
||||
<ha-skeleton></ha-skeleton>
|
||||
<ha-skeleton></ha-skeleton>
|
||||
</div>
|
||||
</ha-fade-in>`
|
||||
: !this.items && !this.error
|
||||
${skeletonOr(
|
||||
Boolean(this.loadingLabel),
|
||||
html`<ha-fade-in .duration=${300} easing="ease-in">
|
||||
<div
|
||||
class="skeletons"
|
||||
role="progressbar"
|
||||
aria-label=${ifDefined(this.loadingLabel)}
|
||||
>
|
||||
<ha-skeleton-text></ha-skeleton-text>
|
||||
<ha-skeleton></ha-skeleton>
|
||||
<ha-skeleton></ha-skeleton>
|
||||
<ha-skeleton></ha-skeleton>
|
||||
</div>
|
||||
</ha-fade-in>`,
|
||||
() =>
|
||||
!this.items && !this.error
|
||||
? this.selectLabel
|
||||
: this.error
|
||||
? html`${this.error}
|
||||
? html`<span>${this.error}</span>
|
||||
<div>${this._renderCurrentTarget()}</div>`
|
||||
: this.items && !this.items.length
|
||||
? html`${this.emptyLabel}
|
||||
${
|
||||
this.target
|
||||
? html`<div>${this._renderCurrentTarget()}</div>`
|
||||
: nothing
|
||||
}`
|
||||
? html`<span>${this.emptyLabel}</span> ${
|
||||
this.target
|
||||
? html`<div>${this._renderCurrentTarget()}</div>`
|
||||
: nothing
|
||||
}`
|
||||
: repeat(
|
||||
this.items,
|
||||
(_, index) => `item-group-${index}`,
|
||||
(itemGroup) =>
|
||||
this._renderItemList(itemGroup.title, itemGroup.items)
|
||||
)
|
||||
}
|
||||
)}
|
||||
</div>
|
||||
<slot></slot>`;
|
||||
}
|
||||
|
||||
@@ -16,6 +16,8 @@ import "../../../../../components/ha-icon-button";
|
||||
import "../../../../../components/ha-svg-icon";
|
||||
import "../../../../../components/item/ha-list-item-base";
|
||||
import "../../../../../components/list/ha-list-base";
|
||||
import "../../../../../components/skeleton/ha-skeleton-text";
|
||||
import { skeletonOr } from "../../../../../components/skeleton/skeleton-arrival";
|
||||
import type { BackupConfig, BackupContent } from "../../../../../data/backup";
|
||||
import {
|
||||
BACKUP_OVERDUE_MARGIN_HOURS,
|
||||
@@ -67,9 +69,11 @@ class HaBackupOverviewBackups extends LitElement {
|
||||
<ha-list-base>
|
||||
<ha-list-item-base wrap-headline>
|
||||
<ha-svg-icon slot="start" .path=${mdiBackupRestore}></ha-svg-icon>
|
||||
<span slot="headline" class=${headline === null ? "skeleton" : ""}
|
||||
>${headline}</span
|
||||
>
|
||||
${skeletonOr(
|
||||
headline === null,
|
||||
html`<ha-skeleton-text slot="headline"></ha-skeleton-text>`,
|
||||
() => html`<span slot="headline">${headline}</span>`
|
||||
)}
|
||||
</ha-list-item-base>
|
||||
${
|
||||
description || description === null
|
||||
@@ -79,12 +83,13 @@ class HaBackupOverviewBackups extends LitElement {
|
||||
slot="start"
|
||||
.path=${mdiCalendar}
|
||||
></ha-svg-icon>
|
||||
<span
|
||||
slot="headline"
|
||||
class=${description === null ? "skeleton" : ""}
|
||||
>${description}</span
|
||||
>
|
||||
|
||||
${skeletonOr(
|
||||
description === null,
|
||||
html`<ha-skeleton-text
|
||||
slot="headline"
|
||||
></ha-skeleton-text>`,
|
||||
() => html`<span slot="headline">${description}</span>`
|
||||
)}
|
||||
${
|
||||
lastCompletedDate
|
||||
? html`
|
||||
@@ -370,34 +375,8 @@ class HaBackupOverviewBackups extends LitElement {
|
||||
ha-list-item-base::part(start) {
|
||||
color: var(--ha-color-text-secondary);
|
||||
}
|
||||
span.skeleton {
|
||||
position: relative;
|
||||
display: block;
|
||||
width: 160px;
|
||||
animation-fill-mode: forwards;
|
||||
animation-iteration-count: infinite;
|
||||
animation-name: loading;
|
||||
animation-timing-function: linear;
|
||||
animation-duration: 1.2s;
|
||||
border-radius: var(--ha-border-radius-sm);
|
||||
height: 16px;
|
||||
margin: 2px 0;
|
||||
background: linear-gradient(
|
||||
to right,
|
||||
var(--card-background-color) 8%,
|
||||
var(--secondary-background-color) 18%,
|
||||
var(--card-background-color) 33%
|
||||
)
|
||||
0% 0% / 936px 104px;
|
||||
}
|
||||
|
||||
@keyframes loading {
|
||||
0% {
|
||||
background-position: -468px 0;
|
||||
}
|
||||
100% {
|
||||
background-position: 468px 0;
|
||||
}
|
||||
ha-skeleton-text {
|
||||
--ha-skeleton-text-width: 160px;
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
@@ -59,6 +59,7 @@ import "../../../components/ha-filter-states";
|
||||
import "../../../components/ha-icon-button";
|
||||
import "../../../components/skeleton/ha-skeleton-icon";
|
||||
import "../../../components/skeleton/ha-skeleton-text";
|
||||
import { skeletonOr } from "../../../components/skeleton/skeleton-arrival";
|
||||
import { createAreaRegistryEntry } from "../../../data/area/area_registry";
|
||||
import type { ConfigEntry, SubEntry } from "../../../data/config_entries";
|
||||
import { getSubEntries, sortConfigEntries } from "../../../data/config_entries";
|
||||
@@ -547,23 +548,26 @@ export class HaConfigDeviceDashboard extends LitElement {
|
||||
moveable: false,
|
||||
showNarrow: true,
|
||||
template: (device) =>
|
||||
!this.entries
|
||||
? html`<ha-skeleton-icon></ha-skeleton-icon>`
|
||||
: device.domains.length
|
||||
? html`<img
|
||||
alt=""
|
||||
crossorigin="anonymous"
|
||||
referrerpolicy="no-referrer"
|
||||
src=${brandsUrl(
|
||||
{
|
||||
domain: device.domains[0],
|
||||
type: "icon",
|
||||
darkOptimized: this.hass.themes?.darkMode,
|
||||
},
|
||||
this.hass.auth.data.hassUrl
|
||||
)}
|
||||
/>`
|
||||
: "",
|
||||
skeletonOr(
|
||||
!this.entries,
|
||||
html`<ha-skeleton-icon></ha-skeleton-icon>`,
|
||||
() =>
|
||||
device.domains.length
|
||||
? html`<img
|
||||
alt=""
|
||||
crossorigin="anonymous"
|
||||
referrerpolicy="no-referrer"
|
||||
src=${brandsUrl(
|
||||
{
|
||||
domain: device.domains[0],
|
||||
type: "icon",
|
||||
darkOptimized: this.hass.themes?.darkMode,
|
||||
},
|
||||
this.hass.auth.data.hassUrl
|
||||
)}
|
||||
/>`
|
||||
: ""
|
||||
),
|
||||
},
|
||||
name: {
|
||||
title: localize("ui.panel.config.devices.data_table.device"),
|
||||
@@ -585,17 +589,20 @@ export class HaConfigDeviceDashboard extends LitElement {
|
||||
</div>`
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
device.label_entries.length
|
||||
? html`
|
||||
<ha-data-table-labels
|
||||
.labels=${device.label_entries}
|
||||
></ha-data-table-labels>
|
||||
`
|
||||
: device.labels.length && !this._labels
|
||||
? html`<ha-skeleton-text></ha-skeleton-text>`
|
||||
${skeletonOr(
|
||||
!device.label_entries.length &&
|
||||
device.labels.length > 0 &&
|
||||
!this._labels,
|
||||
html`<ha-skeleton-text></ha-skeleton-text>`,
|
||||
() =>
|
||||
device.label_entries.length
|
||||
? html`
|
||||
<ha-data-table-labels
|
||||
.labels=${device.label_entries}
|
||||
></ha-data-table-labels>
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
)}
|
||||
`,
|
||||
},
|
||||
area: getAreaTableColumn(localize),
|
||||
@@ -608,9 +615,11 @@ export class HaConfigDeviceDashboard extends LitElement {
|
||||
urlName: "integration",
|
||||
minWidth: "120px",
|
||||
template: (device) =>
|
||||
!this.entries
|
||||
? html`<ha-skeleton-text></ha-skeleton-text>`
|
||||
: device.integration,
|
||||
skeletonOr(
|
||||
!this.entries,
|
||||
html`<ha-skeleton-text></ha-skeleton-text>`,
|
||||
() => device.integration
|
||||
),
|
||||
},
|
||||
device_family_name: {
|
||||
title: localize("ui.panel.config.devices.data_table.parent_device"),
|
||||
@@ -664,38 +673,46 @@ export class HaConfigDeviceDashboard extends LitElement {
|
||||
maxWidth: "101px",
|
||||
minWidth: "101px",
|
||||
valueColumn: "battery_level",
|
||||
template: (device) => {
|
||||
if (!this.entities) {
|
||||
return html`<ha-skeleton-text></ha-skeleton-text>`;
|
||||
}
|
||||
const batteryEntityPair = device.battery_entity;
|
||||
const battery =
|
||||
batteryEntityPair && batteryEntityPair[0]
|
||||
? this.hass.states[batteryEntityPair[0]]
|
||||
: undefined;
|
||||
const batteryDomain = battery
|
||||
? computeStateDomain(battery)
|
||||
: undefined;
|
||||
const batteryCharging =
|
||||
batteryEntityPair && batteryEntityPair[1]
|
||||
? this.hass.states[batteryEntityPair[1]]
|
||||
: undefined;
|
||||
template: (device) =>
|
||||
skeletonOr(
|
||||
!this.entities,
|
||||
html`<ha-skeleton-text></ha-skeleton-text>`,
|
||||
() => {
|
||||
const batteryEntityPair = device.battery_entity;
|
||||
|
||||
return battery &&
|
||||
(batteryDomain === "binary_sensor" || !isNaN(battery.state as any))
|
||||
? html`
|
||||
${
|
||||
batteryDomain === "sensor"
|
||||
? this.hass.formatEntityState(battery)
|
||||
: nothing
|
||||
}
|
||||
<ha-battery-icon
|
||||
.batteryStateObj=${battery}
|
||||
.batteryChargingStateObj=${batteryCharging}
|
||||
></ha-battery-icon>
|
||||
`
|
||||
: "—";
|
||||
},
|
||||
const battery =
|
||||
batteryEntityPair && batteryEntityPair[0]
|
||||
? this.hass.states[batteryEntityPair[0]]
|
||||
: undefined;
|
||||
|
||||
const batteryDomain = battery
|
||||
? computeStateDomain(battery)
|
||||
: undefined;
|
||||
|
||||
const batteryCharging =
|
||||
batteryEntityPair && batteryEntityPair[1]
|
||||
? this.hass.states[batteryEntityPair[1]]
|
||||
: undefined;
|
||||
|
||||
return battery &&
|
||||
(batteryDomain === "binary_sensor" ||
|
||||
!isNaN(Number(battery.state)))
|
||||
? html`
|
||||
${
|
||||
batteryDomain === "sensor"
|
||||
? html`<span
|
||||
>${this.hass.formatEntityState(battery)}</span
|
||||
>`
|
||||
: nothing
|
||||
}
|
||||
<ha-battery-icon
|
||||
.batteryStateObj=${battery}
|
||||
.batteryChargingStateObj=${batteryCharging}
|
||||
></ha-battery-icon>
|
||||
`
|
||||
: "—";
|
||||
}
|
||||
),
|
||||
},
|
||||
created_at: getCreatedAtTableColumn(localize, this.hass),
|
||||
modified_at: getModifiedAtTableColumn(localize, this.hass),
|
||||
@@ -880,15 +897,15 @@ export class HaConfigDeviceDashboard extends LitElement {
|
||||
${this.hass.localize(
|
||||
"ui.panel.config.devices.filtering_by_config_entry"
|
||||
)}
|
||||
${
|
||||
!this.entries
|
||||
? html`<ha-skeleton-text></ha-skeleton-text>`
|
||||
: this.entries.find(
|
||||
(entry) =>
|
||||
entry.entry_id ===
|
||||
this._filters.config_entry!.value![0]
|
||||
)?.title || this._filters.config_entry.value[0]
|
||||
}${
|
||||
${skeletonOr(
|
||||
!this.entries,
|
||||
html`<ha-skeleton-text></ha-skeleton-text>`,
|
||||
() =>
|
||||
this.entries?.find(
|
||||
(entry) =>
|
||||
entry.entry_id === this._filters.config_entry!.value![0]
|
||||
)?.title || this._filters.config_entry!.value![0]
|
||||
)}${
|
||||
this._filters.config_entry.value.length === 1 &&
|
||||
Array.isArray(this._filters.sub_entry?.value) &&
|
||||
this._filters.sub_entry.value.length
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
ERR_CONNECTION_LOST,
|
||||
type UnsubscribeFunc,
|
||||
} from "home-assistant-js-websocket";
|
||||
import type { CSSResultGroup } from "lit";
|
||||
import type { CSSResultGroup, PropertyValues } from "lit";
|
||||
import { mdiCircle, mdiWrap, mdiWrapDisabled } from "@mdi/js";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, query, state } from "lit/decorators";
|
||||
@@ -20,6 +20,10 @@ import "../../../components/ha-svg-icon";
|
||||
import "../../../components/input/ha-input-search";
|
||||
import type { HaInputSearch } from "../../../components/input/ha-input-search";
|
||||
import "../../../components/skeleton/ha-skeleton-log";
|
||||
import {
|
||||
fadeInArrival,
|
||||
skeletonOr,
|
||||
} from "../../../components/skeleton/skeleton-arrival";
|
||||
import {
|
||||
connectionContext,
|
||||
internationalizationContext,
|
||||
@@ -65,6 +69,29 @@ class DialogLiveLog extends DialogMixin<LiveLogDialogParams>(LitElement) {
|
||||
|
||||
private _resubscribeOnReady = false;
|
||||
|
||||
// Whether the skeleton showed last render, so the log fades in once its
|
||||
// first lines take the skeleton's place
|
||||
private _showedSkeleton = false;
|
||||
|
||||
private _linesArriving = false;
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues<this>) {
|
||||
super.willUpdate(changedProps);
|
||||
const showSkeleton = !this._lineCount && this._loading;
|
||||
this._linesArriving =
|
||||
this._showedSkeleton && !showSkeleton && this._lineCount > 0;
|
||||
this._showedSkeleton = showSkeleton;
|
||||
}
|
||||
|
||||
protected updated(changedProps: PropertyValues<this>) {
|
||||
super.updated(changedProps);
|
||||
|
||||
if (this._linesArriving && this._logViewer) {
|
||||
this._linesArriving = false;
|
||||
fadeInArrival(this._logViewer);
|
||||
}
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
super.connectedCallback();
|
||||
const connection = this._connection.connection;
|
||||
@@ -217,18 +244,21 @@ class DialogLiveLog extends DialogMixin<LiveLogDialogParams>(LitElement) {
|
||||
${
|
||||
this._lineCount
|
||||
? nothing
|
||||
: this._loading
|
||||
? html`<ha-skeleton-log
|
||||
: skeletonOr(
|
||||
this._loading,
|
||||
html`<ha-skeleton-log
|
||||
.label=${this._i18n.localize(
|
||||
"ui.panel.config.logs.loading_log"
|
||||
)}
|
||||
></ha-skeleton-log>`
|
||||
: html`<div class="waiting">
|
||||
${this._i18n.localize(
|
||||
"ui.panel.config.integrations.config_entry.live_log.waiting",
|
||||
{ integration: this.params.name }
|
||||
)}
|
||||
</div>`
|
||||
></ha-skeleton-log>`,
|
||||
() =>
|
||||
html`<div class="waiting">
|
||||
${this._i18n.localize(
|
||||
"ui.panel.config.integrations.config_entry.live_log.waiting",
|
||||
{ integration: this.params!.name }
|
||||
)}
|
||||
</div>`
|
||||
)
|
||||
}
|
||||
</ha-log-viewer>
|
||||
${
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { CSSResultGroup, PropertyValues } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, query, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { skeletonOr } from "../../../components/skeleton/skeleton-arrival";
|
||||
import { consume } from "../../../common/decorators/consume";
|
||||
import { isComponentLoaded } from "../../../common/config/is_component_loaded";
|
||||
import { fireEvent } from "../../../common/dom/fire_event";
|
||||
@@ -190,62 +191,58 @@ class DialogSystemLogDetail extends LitElement {
|
||||
.label=${this._i18n.localize("ui.panel.config.logs.copy")}
|
||||
.path=${mdiContentCopy}
|
||||
></ha-icon-button>
|
||||
${
|
||||
integration &&
|
||||
this._manifest === undefined &&
|
||||
reportTarget !== "frontend"
|
||||
? html`<ha-alert
|
||||
alert-type=${this.isCustomIntegration ? "warning" : "info"}
|
||||
>
|
||||
<ha-skeleton-text></ha-skeleton-text>
|
||||
</ha-alert>`
|
||||
: html`<ha-alert
|
||||
alert-type=${this.isCustomIntegration ? "warning" : "info"}
|
||||
>
|
||||
<p>
|
||||
${this._i18n.localize(
|
||||
`ui.panel.config.logs.detail.report_issue.${reportMessage}.introduction`,
|
||||
{
|
||||
integration:
|
||||
this._manifest?.name ??
|
||||
(integration
|
||||
? domainToName(this._i18n.localize, integration)
|
||||
: new URL(reportUrl).hostname),
|
||||
}
|
||||
)}
|
||||
</p>
|
||||
<p>
|
||||
${this._i18n.localize(
|
||||
`ui.panel.config.logs.detail.report_issue.${reportMessage}.report`,
|
||||
{
|
||||
report_link: html`<a
|
||||
href=${reportUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>${this._i18n.localize(`ui.panel.config.logs.detail.report_issue.${reportTarget}.link_text`)}</a
|
||||
>`,
|
||||
}
|
||||
)}
|
||||
</p>
|
||||
${
|
||||
reportMessage !== "custom"
|
||||
? html`<p>
|
||||
${this._i18n.localize(
|
||||
`ui.panel.config.logs.detail.report_issue.${reportMessage}.guidance`,
|
||||
{
|
||||
guide_link: html`<a
|
||||
href=${`${DOCUMENTATION_URL}/help/reporting_issues/`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>${this._i18n.localize("ui.panel.config.logs.detail.report_issue.guide_link_text")}</a
|
||||
>`,
|
||||
}
|
||||
)}
|
||||
</p>`
|
||||
: nothing
|
||||
}
|
||||
</ha-alert>`
|
||||
}
|
||||
<ha-alert alert-type=${this.isCustomIntegration ? "warning" : "info"}>
|
||||
${skeletonOr(
|
||||
Boolean(integration) &&
|
||||
this._manifest === undefined &&
|
||||
reportTarget !== "frontend",
|
||||
html`<ha-skeleton-text></ha-skeleton-text>`,
|
||||
() => html`
|
||||
<p>
|
||||
${this._i18n.localize(
|
||||
`ui.panel.config.logs.detail.report_issue.${reportMessage}.introduction`,
|
||||
{
|
||||
integration:
|
||||
this._manifest?.name ??
|
||||
(integration
|
||||
? domainToName(this._i18n.localize, integration)
|
||||
: new URL(reportUrl).hostname),
|
||||
}
|
||||
)}
|
||||
</p>
|
||||
<p>
|
||||
${this._i18n.localize(
|
||||
`ui.panel.config.logs.detail.report_issue.${reportMessage}.report`,
|
||||
{
|
||||
report_link: html`<a
|
||||
href=${reportUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>${this._i18n.localize(`ui.panel.config.logs.detail.report_issue.${reportTarget}.link_text`)}</a
|
||||
>`,
|
||||
}
|
||||
)}
|
||||
</p>
|
||||
${
|
||||
reportMessage !== "custom"
|
||||
? html`<p>
|
||||
${this._i18n.localize(
|
||||
`ui.panel.config.logs.detail.report_issue.${reportMessage}.guidance`,
|
||||
{
|
||||
guide_link: html`<a
|
||||
href=${`${DOCUMENTATION_URL}/help/reporting_issues/`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>${this._i18n.localize("ui.panel.config.logs.detail.report_issue.guide_link_text")}</a
|
||||
>`,
|
||||
}
|
||||
)}
|
||||
</p>`
|
||||
: nothing
|
||||
}
|
||||
`
|
||||
)}
|
||||
</ha-alert>
|
||||
<div class="contents">
|
||||
<p>
|
||||
${this._i18n.localize("ui.panel.config.logs.detail.logger")}:
|
||||
|
||||
@@ -37,6 +37,10 @@ import "../../../components/ha-dropdown-item";
|
||||
import "../../../components/ha-icon-button";
|
||||
import "../../../components/ha-svg-icon";
|
||||
import "../../../components/skeleton/ha-skeleton-log";
|
||||
import {
|
||||
fadeInArrival,
|
||||
skeletonArrivalStyles,
|
||||
} from "../../../components/skeleton/skeleton-arrival";
|
||||
|
||||
import { getSignedPath } from "../../../data/auth";
|
||||
|
||||
@@ -159,6 +163,12 @@ class ErrorLogCard extends LitElement {
|
||||
|
||||
@state() private _loadingPrevState?: "loading" | "end" | "loaded";
|
||||
|
||||
// Whether the skeleton showed last render, so the log fades in once it
|
||||
// takes the skeleton's place
|
||||
private _showedSkeleton = false;
|
||||
|
||||
private _logArriving = false;
|
||||
|
||||
@state() private _noSearchResults = false;
|
||||
|
||||
@state() private _numberOfLines?: number;
|
||||
@@ -359,7 +369,7 @@ class ErrorLogCard extends LitElement {
|
||||
.label=${localize("ui.panel.config.logs.loading_log")}
|
||||
></ha-skeleton-log>`
|
||||
: this._loadingState === "empty"
|
||||
? html`<div>
|
||||
? html`<div class="arriving">
|
||||
${
|
||||
integrationLog
|
||||
? localize(
|
||||
@@ -451,6 +461,18 @@ class ErrorLogCard extends LitElement {
|
||||
this._boot = 0;
|
||||
this._loadLogs();
|
||||
}
|
||||
|
||||
// As render decides: lines kept while reconnecting show instead
|
||||
const showSkeleton =
|
||||
this._loadingState === "loading" &&
|
||||
!(
|
||||
this._ansiToHtmlElement?.hasLines &&
|
||||
!(this.filter && this._noSearchResults)
|
||||
);
|
||||
|
||||
this._logArriving =
|
||||
this._showedSkeleton && !showSkeleton && this._loadingState === "loaded";
|
||||
this._showedSkeleton = showSkeleton;
|
||||
}
|
||||
|
||||
protected firstUpdated(changedProps: PropertyValues<this>) {
|
||||
@@ -465,6 +487,11 @@ class ErrorLogCard extends LitElement {
|
||||
protected updated(changedProps: PropertyValues) {
|
||||
super.updated(changedProps);
|
||||
|
||||
if (this._logArriving && this._ansiToHtmlElement) {
|
||||
this._logArriving = false;
|
||||
fadeInArrival(this._ansiToHtmlElement);
|
||||
}
|
||||
|
||||
if (this._newLogsIndicator && this._scrolledToBottomController.value) {
|
||||
this._newLogsIndicator = false;
|
||||
}
|
||||
@@ -1041,6 +1068,7 @@ class ErrorLogCard extends LitElement {
|
||||
|
||||
static styles: CSSResultGroup = css`
|
||||
${haStyleScrollbar}
|
||||
${skeletonArrivalStyles}
|
||||
|
||||
:host {
|
||||
direction: var(--direction);
|
||||
|
||||
@@ -18,6 +18,7 @@ import "../../../components/ha-icon-button";
|
||||
import "../../../components/item/ha-list-item-button";
|
||||
import "../../../components/list/ha-list-base";
|
||||
import "../../../components/skeleton/ha-skeleton-text";
|
||||
import { skeletonOr } from "../../../components/skeleton/skeleton-arrival";
|
||||
import { getSignedPath } from "../../../data/auth";
|
||||
import {
|
||||
getCoreLogFileDownloadUnavailableReason,
|
||||
@@ -182,37 +183,38 @@ export class SystemLogCard extends LitElement {
|
||||
</ha-alert>`
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
this._items === undefined
|
||||
? html`<ha-fade-in .duration=${300} easing="ease-in">
|
||||
<div
|
||||
class="skeleton"
|
||||
role="progressbar"
|
||||
aria-label=${this.hass.localize(
|
||||
"ui.panel.config.logs.loading_log"
|
||||
)}
|
||||
>
|
||||
${SKELETON_ROW_WIDTHS.map(
|
||||
([primary, secondary]) => html`
|
||||
<div class="skeleton-row">
|
||||
<ha-skeleton-text
|
||||
class="primary"
|
||||
style=${styleMap({
|
||||
"--ha-skeleton-text-width": `${primary}%`,
|
||||
})}
|
||||
></ha-skeleton-text>
|
||||
<ha-skeleton-text
|
||||
class="secondary"
|
||||
style=${styleMap({
|
||||
"--ha-skeleton-text-width": `${secondary}%`,
|
||||
})}
|
||||
></ha-skeleton-text>
|
||||
</div>
|
||||
`
|
||||
)}
|
||||
</div>
|
||||
</ha-fade-in>`
|
||||
: this._items.length === 0
|
||||
${skeletonOr(
|
||||
this._items === undefined,
|
||||
html`<ha-fade-in .duration=${300} easing="ease-in">
|
||||
<div
|
||||
class="skeleton"
|
||||
role="progressbar"
|
||||
aria-label=${this.hass.localize(
|
||||
"ui.panel.config.logs.loading_log"
|
||||
)}
|
||||
>
|
||||
${SKELETON_ROW_WIDTHS.map(
|
||||
([primary, secondary]) => html`
|
||||
<div class="skeleton-row">
|
||||
<ha-skeleton-text
|
||||
class="primary"
|
||||
style=${styleMap({
|
||||
"--ha-skeleton-text-width": `${primary}%`,
|
||||
})}
|
||||
></ha-skeleton-text>
|
||||
<ha-skeleton-text
|
||||
class="secondary"
|
||||
style=${styleMap({
|
||||
"--ha-skeleton-text-width": `${secondary}%`,
|
||||
})}
|
||||
></ha-skeleton-text>
|
||||
</div>
|
||||
`
|
||||
)}
|
||||
</div>
|
||||
</ha-fade-in>`,
|
||||
() =>
|
||||
this._items!.length === 0
|
||||
? html`
|
||||
<div class="card-content empty-content">
|
||||
${this.hass.localize("ui.panel.config.logs.no_issues")}
|
||||
@@ -289,18 +291,19 @@ export class SystemLogCard extends LitElement {
|
||||
`
|
||||
)}</ha-list-base
|
||||
>`
|
||||
}
|
||||
${
|
||||
this._items === undefined
|
||||
? nothing
|
||||
: html`<div class="card-actions">
|
||||
<ha-call-service-button domain="system_log" service="clear"
|
||||
>${this.hass.localize(
|
||||
"ui.panel.config.logs.clear"
|
||||
)}</ha-call-service-button
|
||||
>
|
||||
</div>`
|
||||
}
|
||||
)}
|
||||
${skeletonOr(
|
||||
this._items === undefined,
|
||||
nothing,
|
||||
() =>
|
||||
html`<div class="card-actions">
|
||||
<ha-call-service-button domain="system_log" service="clear"
|
||||
>${this.hass.localize(
|
||||
"ui.panel.config.logs.clear"
|
||||
)}</ha-call-service-button
|
||||
>
|
||||
</div>`
|
||||
)}
|
||||
</ha-card>
|
||||
</div>
|
||||
`;
|
||||
|
||||
@@ -7,6 +7,7 @@ import { isComponentLoaded } from "../../common/config/is_component_loaded";
|
||||
import { computeStateDomain } from "../../common/entity/compute_state_domain";
|
||||
import { throttle } from "../../common/util/throttle";
|
||||
import "../../components/ha-spinner";
|
||||
import { SkeletonLoadingController } from "../../components/skeleton/skeleton-loading-controller";
|
||||
import type { LogbookEntry, LogbookStreamMessage } from "../../data/logbook";
|
||||
import { subscribeLogbook } from "../../data/logbook";
|
||||
import type { TraceContexts } from "../../data/trace";
|
||||
@@ -85,6 +86,14 @@ export class HaLogbook extends LitElement {
|
||||
@property({ type: Number, attribute: "max-entries" })
|
||||
public maxEntries?: number;
|
||||
|
||||
/**
|
||||
* While loading, draw a date line and this many entry rows for a skeleton
|
||||
* overlay to read, instead of a spinner. Only for a logbook inside an
|
||||
* overlay, such as a card's.
|
||||
*/
|
||||
@property({ type: Number, attribute: "placeholder-rows" })
|
||||
public placeholderRows = 0;
|
||||
|
||||
@state() private _logbookEntries?: LogbookEntry[];
|
||||
|
||||
@state() private _traceContexts: TraceContexts = {};
|
||||
@@ -97,6 +106,15 @@ export class HaLogbook extends LitElement {
|
||||
|
||||
@state() private _error?: string;
|
||||
|
||||
protected readonly _skeletonLoading = new SkeletonLoadingController(
|
||||
this,
|
||||
() =>
|
||||
this.hass !== undefined &&
|
||||
isComponentLoaded(this.hass.config, "logbook") &&
|
||||
!this._error &&
|
||||
this._logbookEntries === undefined
|
||||
);
|
||||
|
||||
private _unsubLogbook?: Promise<UnsubscribeFunc>;
|
||||
|
||||
private _liveUpdatesEnabled = true;
|
||||
@@ -132,8 +150,27 @@ export class HaLogbook extends LitElement {
|
||||
const entries = this._shownEntries();
|
||||
|
||||
if (entries === undefined) {
|
||||
if (this.placeholderRows > 0) {
|
||||
// Shaped like the list that replaces it: a date, then entries
|
||||
return html`
|
||||
<div class="placeholder">
|
||||
<div class="placeholder-date" data-skeleton="text"></div>
|
||||
${Array.from(
|
||||
{ length: this.placeholderRows },
|
||||
() => html`
|
||||
<div class="placeholder-entry">
|
||||
<span class="placeholder-dot" data-skeleton="round"></span>
|
||||
<span class="placeholder-message" data-skeleton="text"></span>
|
||||
<span class="placeholder-time" data-skeleton="text"></span>
|
||||
</div>
|
||||
`
|
||||
)}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
return html`
|
||||
<div class="progress-wrapper">
|
||||
<div class="progress-wrapper" data-skeleton="block">
|
||||
<ha-spinner></ha-spinner>
|
||||
</div>
|
||||
`;
|
||||
@@ -587,6 +624,46 @@ export class HaLogbook extends LitElement {
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
align-items: center;
|
||||
/* Inset like the entries, for the skeleton a card draws over it */
|
||||
margin: 0 var(--ha-space-4);
|
||||
}
|
||||
|
||||
/* Sized like the renderer's date heading and list entries */
|
||||
.placeholder {
|
||||
padding: var(--ha-space-2)
|
||||
var(--logbook-horizontal-padding, var(--ha-space-4)) 0;
|
||||
}
|
||||
|
||||
.placeholder-date {
|
||||
width: 40%;
|
||||
height: calc(var(--ha-font-size-m) * var(--ha-line-height-normal));
|
||||
margin-bottom: var(--ha-space-2);
|
||||
}
|
||||
|
||||
.placeholder-entry {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--ha-space-3);
|
||||
height: 40px;
|
||||
}
|
||||
|
||||
.placeholder-dot {
|
||||
flex: none;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
}
|
||||
|
||||
.placeholder-message {
|
||||
flex: 1;
|
||||
max-width: 50%;
|
||||
height: var(--ha-font-size-m);
|
||||
}
|
||||
|
||||
.placeholder-time {
|
||||
flex: none;
|
||||
width: 72px;
|
||||
height: var(--ha-font-size-s);
|
||||
margin-inline-start: auto;
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
@@ -3,12 +3,16 @@ import { ReactiveElement } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import { fireEvent } from "../../../common/dom/fire_event";
|
||||
import "../../../components/ha-svg-icon";
|
||||
import "../../../components/skeleton/ha-skeleton-overlay";
|
||||
import type { LovelaceBadgeConfig } from "../../../data/lovelace/config/badge";
|
||||
import type { HomeAssistant } from "../../../types";
|
||||
import { ConditionalListenerMixin } from "../../../mixins/conditional-listener-mixin";
|
||||
import { getConfigEntityId } from "../common/get-config-entity-id";
|
||||
import { createBadgeElement } from "../create-element/create-badge-element";
|
||||
import { createErrorBadgeConfig } from "../create-element/create-element-base";
|
||||
import {
|
||||
createErrorBadgeConfig,
|
||||
lovelaceElementPending,
|
||||
} from "../create-element/create-element-base";
|
||||
import type { LovelaceBadge } from "../types";
|
||||
|
||||
declare global {
|
||||
@@ -39,6 +43,15 @@ export class HuiBadge extends ConditionalListenerMixin<LovelaceBadgeConfig>(
|
||||
|
||||
private _element?: LovelaceBadge;
|
||||
|
||||
/* Holds the badge, and draws its skeleton while its code loads */
|
||||
private _overlay = document.createElement("ha-skeleton-overlay");
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this._overlay.style.borderRadius =
|
||||
"var(--ha-badge-border-radius, var(--ha-border-radius-pill))";
|
||||
}
|
||||
|
||||
protected createRenderRoot() {
|
||||
return this;
|
||||
}
|
||||
@@ -96,6 +109,28 @@ export class HuiBadge extends ConditionalListenerMixin<LovelaceBadgeConfig>(
|
||||
while (this.lastChild) {
|
||||
this.removeChild(this.lastChild);
|
||||
}
|
||||
|
||||
this._overlay.replaceChildren();
|
||||
this.appendChild(this._overlay);
|
||||
|
||||
// A badge whose code is still loading has nothing to show yet, so it
|
||||
// holds a badge's size for the wave until it does
|
||||
const element = this._element;
|
||||
const pending = lovelaceElementPending(element, config.type);
|
||||
this._overlay.loading = pending !== undefined;
|
||||
this._overlay.style.minHeight = pending ? "var(--ha-badge-size, 36px)" : "";
|
||||
this._overlay.style.minWidth = pending
|
||||
? "calc(var(--ha-badge-size, 36px) * 3)"
|
||||
: "";
|
||||
|
||||
pending?.then(() => {
|
||||
if (this._element === element) {
|
||||
this._overlay.loading = false;
|
||||
this._overlay.style.minHeight = "";
|
||||
this._overlay.style.minWidth = "";
|
||||
}
|
||||
});
|
||||
|
||||
this._updateVisibility();
|
||||
}
|
||||
|
||||
@@ -181,12 +216,12 @@ export class HuiBadge extends ConditionalListenerMixin<LovelaceBadgeConfig>(
|
||||
|
||||
if (this._element.connectedWhileHidden === true) {
|
||||
if (!this._element.parentElement) {
|
||||
this.appendChild(this._element);
|
||||
this._overlay.appendChild(this._element);
|
||||
}
|
||||
} else if (!visible && this._element.parentElement) {
|
||||
this.removeChild(this._element);
|
||||
this._overlay.removeChild(this._element);
|
||||
} else if (visible && !this._element.parentElement) {
|
||||
this.appendChild(this._element);
|
||||
this._overlay.appendChild(this._element);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
import { transform } from "../../../common/decorators/transform";
|
||||
import { computeDomain } from "../../../common/entity/compute_domain";
|
||||
import type { LocalizeFunc } from "../../../common/translations/localize";
|
||||
import { SkeletonLoadingController } from "../../../components/skeleton/skeleton-loading-controller";
|
||||
import { apiContext, connectionContext } from "../../../data/context";
|
||||
import { UNAVAILABLE } from "../../../data/entity/entity";
|
||||
import {
|
||||
@@ -97,6 +98,12 @@ class HuiLightColorFavoritesCardFeature
|
||||
|
||||
private _unsubEntityRegistry?: UnsubscribeFunc;
|
||||
|
||||
// The favourites are read from the entity's settings
|
||||
protected readonly _skeletonLoading = new SkeletonLoadingController(
|
||||
this,
|
||||
() => this._unsubEntityRegistry !== undefined && this._entry === undefined
|
||||
);
|
||||
|
||||
private _resizeController = new ResizeController(this, {
|
||||
callback: (entries) => {
|
||||
const width = entries[0]?.contentRect.width;
|
||||
@@ -131,10 +138,8 @@ class HuiLightColorFavoritesCardFeature
|
||||
this._unsubEntityRegistry = subscribeEntityRegistry(
|
||||
this._connection,
|
||||
(entries) => {
|
||||
const entry = entries.find((e) => e.entity_id === id);
|
||||
if (entry) {
|
||||
this._entry = entry;
|
||||
}
|
||||
// Without an entry, there are no favourites to wait for
|
||||
this._entry = entries.find((e) => e.entity_id === id) ?? null;
|
||||
}
|
||||
);
|
||||
} catch (_e) {
|
||||
@@ -147,12 +152,7 @@ class HuiLightColorFavoritesCardFeature
|
||||
return this._resizeController.value ?? 0;
|
||||
}
|
||||
|
||||
protected updated(changedProps: PropertyValues): void {
|
||||
if (changedProps.has("context") || changedProps.has("_connection")) {
|
||||
this._unsubscribeEntityRegistry();
|
||||
this._subscribeEntityEntry();
|
||||
}
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues): void {
|
||||
if (changedProps.has("_entry")) {
|
||||
if (this._entry?.options?.light?.favorite_colors) {
|
||||
this._favoriteColors = this._entry.options.light.favorite_colors;
|
||||
@@ -164,6 +164,13 @@ class HuiLightColorFavoritesCardFeature
|
||||
}
|
||||
}
|
||||
|
||||
protected updated(changedProps: PropertyValues): void {
|
||||
if (changedProps.has("context") || changedProps.has("_connection")) {
|
||||
this._unsubscribeEntityRegistry();
|
||||
this._subscribeEntityEntry();
|
||||
}
|
||||
}
|
||||
|
||||
static getStubConfig(): LightColorFavoritesCardFeatureConfig {
|
||||
return {
|
||||
type: "light-color-favorites",
|
||||
|
||||
@@ -23,6 +23,7 @@ import type {
|
||||
LocalizeKeys,
|
||||
} from "../../../common/translations/localize";
|
||||
import "../../../components/ha-control-select";
|
||||
import { SkeletonLoadingController } from "../../../components/skeleton/skeleton-loading-controller";
|
||||
import { apiContext, connectionContext } from "../../../data/context";
|
||||
import { UNAVAILABLE } from "../../../data/entity/entity";
|
||||
import type { ExtEntityRegistryEntry } from "../../../data/entity/entity_registry";
|
||||
@@ -137,6 +138,12 @@ export abstract class HuiNumericFavoriteCardFeatureBase<
|
||||
|
||||
private _subscribedConnection?: HomeAssistant["connection"];
|
||||
|
||||
// The favourites are read from the entity's settings
|
||||
protected readonly _skeletonLoading = new SkeletonLoadingController(
|
||||
this,
|
||||
() => this._subscribedEntityId !== undefined && this._entry === undefined
|
||||
);
|
||||
|
||||
private _resizeController = new ResizeController<number | undefined>(this, {
|
||||
callback: (entries: { contentRect?: { width: number } }[]) => {
|
||||
const width = entries[0]?.contentRect?.width;
|
||||
|
||||
@@ -17,6 +17,7 @@ import { transform } from "../../../common/decorators/transform";
|
||||
import type { LocalizeFunc } from "../../../common/translations/localize";
|
||||
import type { FrontendLocaleData } from "../../../data/translation";
|
||||
import "../../../components/ha-spinner";
|
||||
import { SkeletonLoadingController } from "../../../components/skeleton/skeleton-loading-controller";
|
||||
import {
|
||||
configContext,
|
||||
connectionContext,
|
||||
@@ -123,6 +124,16 @@ class HuiPrecipitationForecastCardFeature
|
||||
|
||||
@state() private _error?: string;
|
||||
|
||||
// Only while there's a forecast to wait for
|
||||
protected readonly _skeletonLoading = new SkeletonLoadingController(
|
||||
this,
|
||||
() =>
|
||||
!this._forecast &&
|
||||
!this._error &&
|
||||
supportsForecast(this._stateObj) &&
|
||||
this._resolvedForecastType() !== undefined
|
||||
);
|
||||
|
||||
private _subscribed?: Promise<UnsubscribeFunc | undefined>;
|
||||
|
||||
private _subscribedType?: ForecastResolution;
|
||||
@@ -240,7 +251,7 @@ class HuiPrecipitationForecastCardFeature
|
||||
}
|
||||
if (!this._forecast) {
|
||||
return html`
|
||||
<div class="container loading">
|
||||
<div class="container loading" data-skeleton="block">
|
||||
<ha-spinner size="small"></ha-spinner>
|
||||
</div>
|
||||
`;
|
||||
|
||||
@@ -18,6 +18,7 @@ import { transform } from "../../../common/decorators/transform";
|
||||
import type { LocalizeFunc } from "../../../common/translations/localize";
|
||||
import type { FrontendLocaleData } from "../../../data/translation";
|
||||
import "../../../components/ha-spinner";
|
||||
import { SkeletonLoadingController } from "../../../components/skeleton/skeleton-loading-controller";
|
||||
import {
|
||||
configContext,
|
||||
connectionContext,
|
||||
@@ -118,6 +119,16 @@ class HuiTemperatureForecastCardFeature
|
||||
|
||||
@state() private _error?: string;
|
||||
|
||||
// Only while there's a forecast to wait for
|
||||
protected readonly _skeletonLoading = new SkeletonLoadingController(
|
||||
this,
|
||||
() =>
|
||||
!this._forecast &&
|
||||
!this._error &&
|
||||
supportsForecast(this._stateObj) &&
|
||||
this._resolvedForecastType() !== undefined
|
||||
);
|
||||
|
||||
private _subscribed?: Promise<UnsubscribeFunc | undefined>;
|
||||
|
||||
private _subscribedType?: ForecastResolution;
|
||||
@@ -226,7 +237,7 @@ class HuiTemperatureForecastCardFeature
|
||||
}
|
||||
if (!this._forecast) {
|
||||
return html`
|
||||
<div class="container loading">
|
||||
<div class="container loading" data-skeleton="block">
|
||||
<ha-spinner size="small"></ha-spinner>
|
||||
</div>
|
||||
`;
|
||||
|
||||
@@ -21,6 +21,7 @@ import type { HaControlButton } from "../../../components/ha-control-button";
|
||||
import "../../../components/ha-control-button-group";
|
||||
import "../../../components/ha-control-select-menu";
|
||||
import "../../../components/ha-svg-icon";
|
||||
import { SkeletonLoadingController } from "../../../components/skeleton/skeleton-loading-controller";
|
||||
import {
|
||||
apiContext,
|
||||
connectionContext,
|
||||
@@ -101,6 +102,12 @@ class HuiTimerPresetsCardFeature
|
||||
|
||||
private _unsubEntityRegistry?: UnsubscribeFunc;
|
||||
|
||||
// The presets are read from the entity's settings
|
||||
protected readonly _skeletonLoading = new SkeletonLoadingController(
|
||||
this,
|
||||
() => this._unsubEntityRegistry !== undefined && this._entry === undefined
|
||||
);
|
||||
|
||||
public connectedCallback() {
|
||||
super.connectedCallback();
|
||||
this._subscribeEntityEntry();
|
||||
@@ -134,12 +141,7 @@ class HuiTimerPresetsCardFeature
|
||||
}
|
||||
}
|
||||
|
||||
protected updated(changedProps: PropertyValues): void {
|
||||
if (changedProps.has("context") || changedProps.has("_connection")) {
|
||||
this._unsubscribeEntityRegistry();
|
||||
this._subscribeEntityEntry();
|
||||
}
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues): void {
|
||||
if (changedProps.has("_entry")) {
|
||||
this._presets = normalizeTimerPresets(
|
||||
this._entry?.options?.timer?.presets
|
||||
@@ -147,6 +149,13 @@ class HuiTimerPresetsCardFeature
|
||||
}
|
||||
}
|
||||
|
||||
protected updated(changedProps: PropertyValues): void {
|
||||
if (changedProps.has("context") || changedProps.has("_connection")) {
|
||||
this._unsubscribeEntityRegistry();
|
||||
this._subscribeEntityEntry();
|
||||
}
|
||||
}
|
||||
|
||||
public static async getConfigElement(): Promise<LovelaceCardFeatureEditor> {
|
||||
await import("../editor/config-elements/hui-timer-presets-card-feature-editor");
|
||||
return document.createElement("hui-timer-presets-card-feature-editor");
|
||||
@@ -178,6 +187,11 @@ class HuiTimerPresetsCardFeature
|
||||
|
||||
const presets = this._presets;
|
||||
|
||||
// Keep the row while the presets load, so the card keeps its height
|
||||
if (this._entry === undefined && this._unsubEntityRegistry) {
|
||||
return html`<ha-control-button-group></ha-control-button-group>`;
|
||||
}
|
||||
|
||||
if (!presets.length) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ import { transform } from "../../../common/decorators/transform";
|
||||
import { computeDomain } from "../../../common/entity/compute_domain";
|
||||
import { isNumericFromAttributes } from "../../../common/number/format_number";
|
||||
import type { LocalizeFunc } from "../../../common/translations/localize";
|
||||
import { SkeletonLoadingController } from "../../../components/skeleton/skeleton-loading-controller";
|
||||
import {
|
||||
configContext,
|
||||
connectionContext,
|
||||
@@ -103,6 +104,24 @@ class HuiHistoryChartCardFeature
|
||||
|
||||
@state() private _error?: { code: string; message: string };
|
||||
|
||||
protected readonly _skeletonLoading = new SkeletonLoadingController(
|
||||
this,
|
||||
() => {
|
||||
const stateObj = this._stateObj;
|
||||
const hassConfig = this._hassConfig;
|
||||
|
||||
// Only while there's history to wait for
|
||||
return (
|
||||
this._loading &&
|
||||
!this._error &&
|
||||
stateObj !== undefined &&
|
||||
supportsTrendGraphCardFeatureFromState(stateObj) &&
|
||||
hassConfig !== undefined &&
|
||||
isComponentLoaded(hassConfig, "history")
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
private _subscribed?: Promise<UnsubscribeFunc | undefined>;
|
||||
|
||||
private _interval?: number;
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { html } from "lit";
|
||||
import "../../../../../components/ha-gauge";
|
||||
import type { FrontendLocaleData } from "../../../../../data/translation";
|
||||
|
||||
/**
|
||||
* Holds the place of an energy gauge card's gauge and name while its data
|
||||
* loads. The gauge is hidden, as it has no value yet, but a skeleton drawn
|
||||
* over the card still takes its shape.
|
||||
*/
|
||||
export const renderEnergyGaugeLoading = (
|
||||
locale: FrontendLocaleData,
|
||||
loadingText: string
|
||||
) => html`
|
||||
<ha-gauge
|
||||
style="opacity: 0"
|
||||
aria-hidden="true"
|
||||
.value=${0}
|
||||
label="%"
|
||||
.locale=${locale}
|
||||
></ha-gauge>
|
||||
<div class="name">${loadingText}</div>
|
||||
`;
|
||||
@@ -13,6 +13,7 @@ import "../../../../components/ha-svg-icon";
|
||||
import "../../../../components/ha-tooltip";
|
||||
import {
|
||||
configContext,
|
||||
entitiesContext,
|
||||
internationalizationContext,
|
||||
} from "../../../../data/context";
|
||||
import type { EnergyData } from "../../../../data/energy";
|
||||
@@ -30,6 +31,7 @@ import { createEntityNotFoundWarning } from "../../components/hui-warning";
|
||||
import type { LovelaceCard } from "../../types";
|
||||
import { severityMap } from "../hui-gauge-card";
|
||||
import type { EnergyCarbonGaugeCardConfig } from "../types";
|
||||
import { renderEnergyGaugeLoading } from "./common/gauge-loading";
|
||||
|
||||
const FORMAT_OPTIONS = {
|
||||
maximumFractionDigits: 0,
|
||||
@@ -71,6 +73,10 @@ class HuiEnergyCarbonGaugeCard extends LitElement implements LovelaceCard {
|
||||
})
|
||||
private _hassConfig!: HassConfig;
|
||||
|
||||
@state()
|
||||
@consume({ context: entitiesContext, subscribe: true })
|
||||
private _entities?: HomeAssistant["entities"];
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
new EnergyCollectionController(this, {
|
||||
@@ -98,7 +104,23 @@ class HuiEnergyCarbonGaugeCard extends LitElement implements LovelaceCard {
|
||||
}
|
||||
|
||||
if (!this._data) {
|
||||
return html`${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}`;
|
||||
// Without a CO2 Signal sensor the card shows nothing, so it doesn't
|
||||
// stand in for anything while the data loads
|
||||
if (
|
||||
this._entities &&
|
||||
!Object.values(this._entities).some(
|
||||
(entity) => entity.platform === "co2signal"
|
||||
)
|
||||
) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
return html`<ha-card>
|
||||
${renderEnergyGaugeLoading(
|
||||
this._i18n.locale,
|
||||
this._i18n.localize("ui.panel.lovelace.cards.energy.loading")
|
||||
)}
|
||||
</ha-card>`;
|
||||
}
|
||||
|
||||
if (!this._data.co2SignalEntity) {
|
||||
|
||||
@@ -122,15 +122,12 @@ export class HuiEnergyDevicesDetailGraphCard
|
||||
@consume({ context: uiContext, subscribe: true })
|
||||
private _ui!: HomeAssistantUI;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
new EnergyCollectionController(this, {
|
||||
config: () => this._config,
|
||||
onData: (data) => {
|
||||
this._data = data;
|
||||
},
|
||||
});
|
||||
}
|
||||
private _energy = new EnergyCollectionController(this, {
|
||||
config: () => this._config,
|
||||
onData: (data) => {
|
||||
this._data = data;
|
||||
},
|
||||
});
|
||||
|
||||
public getCardSize(): Promise<number> | number {
|
||||
return 3;
|
||||
@@ -184,6 +181,7 @@ export class HuiEnergyDevicesDetailGraphCard
|
||||
this._legendData
|
||||
)}
|
||||
.expandLegend=${this._config.expand_legend}
|
||||
?loading=${!this._data}
|
||||
click-label-for-more-info
|
||||
@dataset-hidden=${this._datasetHidden}
|
||||
@dataset-unhidden=${this._datasetUnhidden}
|
||||
@@ -311,10 +309,13 @@ export class HuiEnergyDevicesDetailGraphCard
|
||||
);
|
||||
|
||||
private _processStatistics() {
|
||||
if (!this._data) {
|
||||
// Until the data comes, the legend lists the configured devices so the
|
||||
// skeleton has as many legend rows as the chart will
|
||||
const energyData = this._data ?? this._energy.placeholderData;
|
||||
|
||||
if (!energyData) {
|
||||
return;
|
||||
}
|
||||
const energyData = this._data;
|
||||
|
||||
const {
|
||||
chartData,
|
||||
|
||||
@@ -205,6 +205,7 @@ export class HuiEnergyDevicesGraphCard
|
||||
.sonificationLabelFormatter=${this._sonificationLabel}
|
||||
.extraComponents=${[PieChart]}
|
||||
.expandLegend=${this._config.expand_legend}
|
||||
?loading=${!this._data}
|
||||
click-label-for-more-info
|
||||
@chart-click=${this._handleChartClick}
|
||||
@dataset-hidden=${this._datasetHidden}
|
||||
|
||||
@@ -212,7 +212,13 @@ class HuiEnergyDistrubutionCard extends LitElement implements LovelaceCard {
|
||||
}
|
||||
|
||||
if (!this._data) {
|
||||
return html`${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}`;
|
||||
return html`<ha-card .header=${this._config.title}>
|
||||
<div class="card-content">
|
||||
<div class="loading" data-skeleton="block">
|
||||
${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}
|
||||
</div>
|
||||
</div>
|
||||
</ha-card>`;
|
||||
}
|
||||
|
||||
const prefs = this._data.prefs;
|
||||
@@ -969,6 +975,11 @@ class HuiEnergyDistrubutionCard extends LitElement implements LovelaceCard {
|
||||
position: relative;
|
||||
direction: ltr;
|
||||
}
|
||||
/* The usual layout: a row of sources over the grid and home. Others are
|
||||
remembered once seen. */
|
||||
.loading {
|
||||
height: 230px;
|
||||
}
|
||||
.lines {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
|
||||
@@ -242,9 +242,10 @@ export class HuiEnergyGasGraphCard extends LitElement implements LovelaceCard {
|
||||
this._displayPrecision ?? this._yAxisFractionDigits
|
||||
)}
|
||||
chart-type="bar"
|
||||
?loading=${!this._data}
|
||||
></ha-chart-base>
|
||||
${
|
||||
!this._chartData.length
|
||||
this._data && !this._chartData.length
|
||||
? html`<div class="no-data">
|
||||
${
|
||||
isToday(this._start)
|
||||
|
||||
@@ -77,8 +77,30 @@ class HuiEnergyGridBalanceCard extends LitElement implements LovelaceCard {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const title =
|
||||
this._config.title ||
|
||||
this._i18n.localize("ui.panel.lovelace.cards.energy.grid_balance.title");
|
||||
|
||||
if (!this._data) {
|
||||
return html`${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}`;
|
||||
return html`
|
||||
<ha-card>
|
||||
<div class="content">
|
||||
<ha-tile-icon>
|
||||
<ha-svg-icon
|
||||
slot="icon"
|
||||
.path=${mdiTransmissionTower}
|
||||
></ha-svg-icon>
|
||||
</ha-tile-icon>
|
||||
<ha-tile-info>
|
||||
<span slot="primary">${title}</span>
|
||||
<span slot="secondary">
|
||||
${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}
|
||||
</span>
|
||||
</ha-tile-info>
|
||||
</div>
|
||||
<div class="bar loading" data-skeleton="block"></div>
|
||||
</ha-card>
|
||||
`;
|
||||
}
|
||||
|
||||
const { summedData } = getSummedData(this._data);
|
||||
@@ -117,14 +139,7 @@ class HuiEnergyGridBalanceCard extends LitElement implements LovelaceCard {
|
||||
></ha-svg-icon>
|
||||
</ha-tile-icon>
|
||||
<ha-tile-info>
|
||||
<span slot="primary">
|
||||
${
|
||||
this._config.title ||
|
||||
this._i18n.localize(
|
||||
"ui.panel.lovelace.cards.energy.grid_balance.title"
|
||||
)
|
||||
}
|
||||
</span>
|
||||
<span slot="primary">${title}</span>
|
||||
<span slot="secondary" class="equation">
|
||||
<span class="imported" id="eq-imported">
|
||||
${fmtEnergy(imported)}
|
||||
@@ -310,6 +325,10 @@ class HuiEnergyGridBalanceCard extends LitElement implements LovelaceCard {
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.bar.loading {
|
||||
border-radius: var(--ha-border-radius-lg);
|
||||
}
|
||||
|
||||
.bar-half {
|
||||
position: relative;
|
||||
display: flex;
|
||||
|
||||
@@ -21,6 +21,7 @@ import type {
|
||||
} from "../../../../types";
|
||||
import type { LovelaceCard } from "../../types";
|
||||
import type { EnergyGridNeutralityGaugeCardConfig } from "../types";
|
||||
import { renderEnergyGaugeLoading } from "./common/gauge-loading";
|
||||
|
||||
const LEVELS: LevelDefinition[] = [
|
||||
{ level: -1, stroke: "var(--energy-grid-return-color)" },
|
||||
@@ -79,7 +80,12 @@ class HuiEnergyGridGaugeCard extends LitElement implements LovelaceCard {
|
||||
}
|
||||
|
||||
if (!this._data) {
|
||||
return html`${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}`;
|
||||
return html`<ha-card>
|
||||
${renderEnergyGaugeLoading(
|
||||
this._i18n.locale,
|
||||
this._i18n.localize("ui.panel.lovelace.cards.energy.loading")
|
||||
)}
|
||||
</ha-card>`;
|
||||
}
|
||||
const { summedData, compareSummedData: _ } = getSummedData(this._data);
|
||||
|
||||
|
||||
@@ -165,8 +165,26 @@ class HuiEnergySankeyCard
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const vertical =
|
||||
this._config.layout === "vertical" ||
|
||||
(this._config.layout !== "horizontal" && this._isMobileSize);
|
||||
|
||||
const cardClasses = classMap({
|
||||
"is-grid": this.layout === "grid",
|
||||
"is-panel": this.layout === "panel",
|
||||
"is-vertical": vertical,
|
||||
});
|
||||
|
||||
if (!this._data) {
|
||||
return html`${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}`;
|
||||
return html`
|
||||
<ha-card .header=${this._config.title} class=${cardClasses}>
|
||||
<div class="card-content">
|
||||
<div class="loading" data-skeleton="block">
|
||||
${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}
|
||||
</div>
|
||||
</div>
|
||||
</ha-card>
|
||||
`;
|
||||
}
|
||||
|
||||
const prefs = this._data.prefs;
|
||||
@@ -407,19 +425,8 @@ class HuiEnergySankeyCard
|
||||
|
||||
const hasData = nodes.some((node) => node.value > 0);
|
||||
|
||||
const vertical =
|
||||
this._config.layout === "vertical" ||
|
||||
(this._config.layout !== "horizontal" && this._isMobileSize);
|
||||
|
||||
return html`
|
||||
<ha-card
|
||||
.header=${this._config.title}
|
||||
class=${classMap({
|
||||
"is-grid": this.layout === "grid",
|
||||
"is-panel": this.layout === "panel",
|
||||
"is-vertical": vertical,
|
||||
})}
|
||||
>
|
||||
<ha-card .header=${this._config.title} class=${cardClasses}>
|
||||
<div class="card-content">
|
||||
${
|
||||
hasData
|
||||
@@ -726,6 +733,9 @@ class HuiEnergySankeyCard
|
||||
flex: 1;
|
||||
display: flex;
|
||||
}
|
||||
.loading {
|
||||
flex: 1;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ import type {
|
||||
import type { LovelaceCard } from "../../types";
|
||||
import { severityMap } from "../hui-gauge-card";
|
||||
import type { EnergySelfSufficiencyGaugeCardConfig } from "../types";
|
||||
import { renderEnergyGaugeLoading } from "./common/gauge-loading";
|
||||
|
||||
const FORMAT_OPTIONS = {
|
||||
maximumFractionDigits: 0,
|
||||
@@ -82,7 +83,12 @@ class HuiEnergySelfSufficiencyGaugeCard
|
||||
}
|
||||
|
||||
if (!this._data) {
|
||||
return html`${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}`;
|
||||
return html`<ha-card>
|
||||
${renderEnergyGaugeLoading(
|
||||
this._i18n.locale,
|
||||
this._i18n.localize("ui.panel.lovelace.cards.energy.loading")
|
||||
)}
|
||||
</ha-card>`;
|
||||
}
|
||||
|
||||
// The strategy only includes this card if we have a grid.
|
||||
|
||||
@@ -21,6 +21,7 @@ import type {
|
||||
import type { LovelaceCard } from "../../types";
|
||||
import { severityMap } from "../hui-gauge-card";
|
||||
import type { EnergySolarGaugeCardConfig } from "../types";
|
||||
import { renderEnergyGaugeLoading } from "./common/gauge-loading";
|
||||
|
||||
const FORMAT_OPTIONS = {
|
||||
maximumFractionDigits: 0,
|
||||
@@ -78,7 +79,12 @@ class HuiEnergySolarGaugeCard extends LitElement implements LovelaceCard {
|
||||
}
|
||||
|
||||
if (!this._data) {
|
||||
return html`${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}`;
|
||||
return html`<ha-card>
|
||||
${renderEnergyGaugeLoading(
|
||||
this._i18n.locale,
|
||||
this._i18n.localize("ui.panel.lovelace.cards.energy.loading")
|
||||
)}
|
||||
</ha-card>`;
|
||||
}
|
||||
|
||||
const { summedData, compareSummedData: _ } = getSummedData(this._data);
|
||||
|
||||
@@ -120,6 +120,7 @@ export class HuiEnergySolarGraphCard
|
||||
new EnergyCollectionController(this, {
|
||||
config: () => this._config,
|
||||
onData: (data) => this._fetchForecasts(data),
|
||||
loading: () => !this._data,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -184,9 +185,10 @@ export class HuiEnergySolarGraphCard
|
||||
this._yAxisFractionDigits
|
||||
)}
|
||||
chart-type="bar"
|
||||
?loading=${!this._data}
|
||||
></ha-chart-base>
|
||||
${
|
||||
!this._chartData.length
|
||||
this._data && !this._chartData.length
|
||||
? html`<div class="no-data">
|
||||
${
|
||||
isToday(this._start)
|
||||
|
||||
@@ -151,15 +151,12 @@ export class HuiEnergySourcesTableCard
|
||||
})
|
||||
private _gasDisplayPrecisions?: Record<string, number | undefined>;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
new EnergyCollectionController(this, {
|
||||
config: () => this._config,
|
||||
onData: (data) => {
|
||||
this._data = data;
|
||||
},
|
||||
});
|
||||
}
|
||||
private _energy = new EnergyCollectionController(this, {
|
||||
config: () => this._config,
|
||||
onData: (data) => {
|
||||
this._data = data;
|
||||
},
|
||||
});
|
||||
|
||||
public getCardSize(): Promise<number> | number {
|
||||
return 3;
|
||||
@@ -357,8 +354,22 @@ export class HuiEnergySourcesTableCard
|
||||
return nothing;
|
||||
}
|
||||
|
||||
if (!this._data) {
|
||||
return html`${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}`;
|
||||
// Until the data comes, the table has a row for every configured source,
|
||||
// so the skeleton has as many rows as the table will
|
||||
const data = this._data ?? this._energy.placeholderData;
|
||||
const placeholder = !this._data;
|
||||
|
||||
if (!data) {
|
||||
return html`<ha-card>
|
||||
${
|
||||
this._config.title
|
||||
? html`<h1 class="card-header">${this._config.title}</h1>`
|
||||
: ""
|
||||
}
|
||||
<div class="loading" data-skeleton="block">
|
||||
${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}
|
||||
</div>
|
||||
</ha-card>`;
|
||||
}
|
||||
|
||||
let totalGrid = 0;
|
||||
@@ -396,7 +407,7 @@ export class HuiEnergySourcesTableCard
|
||||
water: false,
|
||||
};
|
||||
|
||||
const allTypes = energySourcesByType(this._data.prefs);
|
||||
const allTypes = energySourcesByType(data.prefs);
|
||||
const pickedTypes = this._config?.types;
|
||||
const types = pickedTypes
|
||||
? Object.fromEntries(
|
||||
@@ -452,8 +463,8 @@ export class HuiEnergySourcesTableCard
|
||||
|
||||
const units = {
|
||||
solar: "kWh",
|
||||
gas: this._data.gasUnit,
|
||||
water: this._data.waterUnit,
|
||||
gas: data.gasUnit,
|
||||
water: data.waterUnit,
|
||||
};
|
||||
|
||||
const gasDisplayPrecisions = types.gas
|
||||
@@ -475,7 +486,7 @@ export class HuiEnergySourcesTableCard
|
||||
}
|
||||
: undefined;
|
||||
|
||||
const compare = this._data.statsCompare !== undefined;
|
||||
const compare = data.statsCompare !== undefined;
|
||||
|
||||
const _extractStatData = (
|
||||
statId: string,
|
||||
@@ -487,24 +498,26 @@ export class HuiEnergySourcesTableCard
|
||||
cost: number;
|
||||
costCompare: number;
|
||||
} => {
|
||||
const energy = calculateStatisticSumGrowth(this._data!.stats[statId]);
|
||||
const energy = calculateStatisticSumGrowth(data.stats[statId]);
|
||||
|
||||
const compareEnergy =
|
||||
compare &&
|
||||
calculateStatisticSumGrowth(this._data!.statsCompare[statId]);
|
||||
compare && calculateStatisticSumGrowth(data.statsCompare?.[statId]);
|
||||
|
||||
const cost =
|
||||
(costStatId &&
|
||||
calculateStatisticSumGrowth(this._data!.stats[costStatId])) ||
|
||||
(costStatId && calculateStatisticSumGrowth(data.stats[costStatId])) ||
|
||||
0;
|
||||
|
||||
const costCompare =
|
||||
(compare &&
|
||||
costStatId &&
|
||||
calculateStatisticSumGrowth(this._data!.statsCompare[costStatId])) ||
|
||||
calculateStatisticSumGrowth(data.statsCompare?.[costStatId])) ||
|
||||
0;
|
||||
|
||||
if (energy === null && (!compare || compareEnergy === null)) {
|
||||
if (
|
||||
!placeholder &&
|
||||
energy === null &&
|
||||
(!compare || compareEnergy === null)
|
||||
) {
|
||||
return {
|
||||
hasData: false,
|
||||
energy: energy || 0,
|
||||
@@ -526,11 +539,11 @@ export class HuiEnergySourcesTableCard
|
||||
const _sumStatData = (statIds: string[]) =>
|
||||
statIds.reduce(
|
||||
(sum, statId) => {
|
||||
const data = _extractStatData(statId, null);
|
||||
const statData = _extractStatData(statId, null);
|
||||
return {
|
||||
hasData: sum.hasData || data.hasData,
|
||||
energy: sum.energy + data.energy,
|
||||
energyCompare: sum.energyCompare + data.energyCompare,
|
||||
hasData: sum.hasData || statData.hasData,
|
||||
energy: sum.energy + statData.energy,
|
||||
energyCompare: sum.energyCompare + statData.energyCompare,
|
||||
};
|
||||
},
|
||||
{ hasData: false, energy: 0, energyCompare: 0 }
|
||||
@@ -539,7 +552,7 @@ export class HuiEnergySourcesTableCard
|
||||
const showOnlyTotals = this._config.show_only_totals;
|
||||
const combine =
|
||||
!showOnlyTotals &&
|
||||
(this._config.combine_sources ?? this._data.combineSources ?? false);
|
||||
(this._config.combine_sources ?? data.combineSources ?? false);
|
||||
const combineType = (type: keyof EnergySourceByType) =>
|
||||
combine && (types[type]?.length ?? 0) > 1;
|
||||
|
||||
@@ -609,8 +622,7 @@ export class HuiEnergySourcesTableCard
|
||||
html` ${types[type]?.map((source, idx) => {
|
||||
const cost_stat =
|
||||
type in hasCosts &&
|
||||
(source.stat_cost ||
|
||||
this._data!.info.cost_sensors[source.stat_energy_from]);
|
||||
(source.stat_cost || data.info.cost_sensors[source.stat_energy_from]);
|
||||
|
||||
const { hasData, energy, energyCompare, cost, costCompare } =
|
||||
_extractStatData(source.stat_energy_from, cost_stat || null);
|
||||
@@ -793,7 +805,7 @@ export class HuiEnergySourcesTableCard
|
||||
this._states,
|
||||
this._formatEntityName,
|
||||
source,
|
||||
this._data!.statsMetadata
|
||||
data.statsMetadata
|
||||
);
|
||||
return html` ${this._renderRow(
|
||||
computedStyles,
|
||||
@@ -875,7 +887,7 @@ export class HuiEnergySourcesTableCard
|
||||
|
||||
const cost_stat =
|
||||
source.stat_cost ||
|
||||
this._data!.info.cost_sensors[source.stat_energy_from];
|
||||
data.info.cost_sensors[source.stat_energy_from];
|
||||
const { hasData, energy, energyCompare, cost, costCompare } =
|
||||
_extractStatData(
|
||||
source.stat_energy_from,
|
||||
@@ -941,7 +953,7 @@ export class HuiEnergySourcesTableCard
|
||||
|
||||
const cost_stat =
|
||||
source.stat_compensation ||
|
||||
this._data!.info.cost_sensors[source.stat_energy_to];
|
||||
data.info.cost_sensors[source.stat_energy_to];
|
||||
const { hasData, energy, energyCompare, cost, costCompare } =
|
||||
_extractStatData(source.stat_energy_to, cost_stat || null);
|
||||
|
||||
@@ -1171,6 +1183,12 @@ export class HuiEnergySourcesTableCard
|
||||
.card-header {
|
||||
padding-bottom: 0;
|
||||
}
|
||||
/* Before the energy preferences are known: as tall as the header row
|
||||
and three sources (212px). Others are remembered once seen. */
|
||||
.loading {
|
||||
height: 180px;
|
||||
margin: 16px;
|
||||
}
|
||||
.content {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
@@ -226,8 +226,10 @@ export class HuiEnergyUsageGraphCard
|
||||
)}
|
||||
chart-type="bar"
|
||||
.expandLegend=${this._config.expand_legend}
|
||||
?loading=${!this._data}
|
||||
></ha-chart-base>
|
||||
${
|
||||
this._data &&
|
||||
!this._chartData.some((dataset) => dataset.data!.length)
|
||||
? html`<div class="no-data">
|
||||
${
|
||||
|
||||
@@ -197,9 +197,10 @@ export class HuiEnergyWaterGraphCard
|
||||
this._yAxisFractionDigits
|
||||
)}
|
||||
chart-type="bar"
|
||||
?loading=${!this._data}
|
||||
></ha-chart-base>
|
||||
${
|
||||
!this._chartData.length
|
||||
this._data && !this._chartData.length
|
||||
? html`<div class="no-data">
|
||||
${
|
||||
isToday(this._start)
|
||||
|
||||
@@ -227,8 +227,26 @@ class HuiPowerSankeyCard
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const vertical =
|
||||
this._config.layout === "vertical" ||
|
||||
(this._config.layout !== "horizontal" && this._isMobileSize);
|
||||
|
||||
const cardClasses = classMap({
|
||||
"is-grid": this.layout === "grid",
|
||||
"is-panel": this.layout === "panel",
|
||||
"is-vertical": vertical,
|
||||
});
|
||||
|
||||
if (!this._data) {
|
||||
return html`${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}`;
|
||||
return html`
|
||||
<ha-card .header=${this._config.title} class=${cardClasses}>
|
||||
<div class="card-content">
|
||||
<div class="loading" data-skeleton="block">
|
||||
${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}
|
||||
</div>
|
||||
</div>
|
||||
</ha-card>
|
||||
`;
|
||||
}
|
||||
|
||||
const prefs = this._data.prefs;
|
||||
@@ -450,19 +468,8 @@ class HuiPowerSankeyCard
|
||||
|
||||
const hasData = nodes.some((node) => node.value > 0);
|
||||
|
||||
const vertical =
|
||||
this._config.layout === "vertical" ||
|
||||
(this._config.layout !== "horizontal" && this._isMobileSize);
|
||||
|
||||
return html`
|
||||
<ha-card
|
||||
.header=${this._config.title}
|
||||
class=${classMap({
|
||||
"is-grid": this.layout === "grid",
|
||||
"is-panel": this.layout === "panel",
|
||||
"is-vertical": vertical,
|
||||
})}
|
||||
>
|
||||
<ha-card .header=${this._config.title} class=${cardClasses}>
|
||||
<div class="card-content">
|
||||
${
|
||||
hasData
|
||||
@@ -862,6 +869,9 @@ class HuiPowerSankeyCard
|
||||
flex: 1;
|
||||
display: flex;
|
||||
}
|
||||
.loading {
|
||||
flex: 1;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
@@ -214,8 +214,10 @@ export class HuiPowerSourcesGraphCard
|
||||
this._yAxisFractionDigits
|
||||
)}
|
||||
.expandLegend=${this._config.expand_legend}
|
||||
?loading=${!this._energyData}
|
||||
></ha-chart-base>
|
||||
${
|
||||
this._energyData &&
|
||||
!this._chartData.some((dataset) => dataset.data!.length)
|
||||
? html`<div class="no-data">
|
||||
${
|
||||
|
||||
@@ -7,7 +7,7 @@ import { applyThemesOnElement } from "../../../common/dom/apply_themes_on_elemen
|
||||
import type { HASSDomEvent } from "../../../common/dom/fire_event";
|
||||
import { debounce } from "../../../common/util/debounce";
|
||||
import "../../../components/ha-card";
|
||||
import "../../../components/ha-spinner";
|
||||
import { SkeletonLoadingController } from "../../../components/skeleton/skeleton-loading-controller";
|
||||
import type { Calendar } from "../../../data/calendar";
|
||||
import { getCalendarColors } from "../../../data/calendar";
|
||||
import { CalendarEventsController } from "../../../data/calendar-events-controller";
|
||||
@@ -81,6 +81,11 @@ export class HuiCalendarCard
|
||||
|
||||
private _events = new CalendarEventsController(this);
|
||||
|
||||
protected readonly _skeletonLoading = new SkeletonLoadingController(
|
||||
this,
|
||||
() => !this._entityRegistry || !this._eventsLoaded
|
||||
);
|
||||
|
||||
public setConfig(config: CalendarCardConfig): void {
|
||||
if (!config.entities?.length) {
|
||||
throw new Error("Entities must be specified");
|
||||
@@ -174,7 +179,6 @@ export class HuiCalendarCard
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const loading = !this._entityRegistry || !this._eventsLoaded;
|
||||
const rows = this._config.grid_options
|
||||
? this._config.grid_options.rows
|
||||
: this._config.layout_options?.grid_rows;
|
||||
@@ -198,7 +202,6 @@ export class HuiCalendarCard
|
||||
"is-grid": this.layout === "grid" && !autoHeight,
|
||||
"is-panel": this.layout === "panel",
|
||||
"has-title": !!this._config.title,
|
||||
loading: loading,
|
||||
})}
|
||||
?auto-height=${autoHeight}
|
||||
?add-fab=${this._config.show_add_event}
|
||||
@@ -219,13 +222,6 @@ export class HuiCalendarCard
|
||||
}
|
||||
@view-changed=${this._handleViewChanged}
|
||||
></ha-full-calendar>
|
||||
${
|
||||
loading
|
||||
? html`<div class="loading">
|
||||
<ha-spinner></ha-spinner>
|
||||
</div>`
|
||||
: nothing
|
||||
}
|
||||
</ha-card>
|
||||
`;
|
||||
}
|
||||
@@ -344,10 +340,6 @@ export class HuiCalendarCard
|
||||
height: auto;
|
||||
}
|
||||
|
||||
ha-full-calendar.loading {
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
ha-full-calendar.is-grid,
|
||||
ha-full-calendar.is-panel {
|
||||
--calendar-height: calc(100% - 16px);
|
||||
@@ -364,16 +356,6 @@ export class HuiCalendarCard
|
||||
);
|
||||
height: calc(100% - var(--header-height));
|
||||
}
|
||||
|
||||
.loading {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--card-background-color, var(--ha-card-background));
|
||||
z-index: 1;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ import { ReactiveElement } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import { fireEvent } from "../../../common/dom/fire_event";
|
||||
import "../../../components/ha-svg-icon";
|
||||
import "../../../components/skeleton/ha-skeleton-overlay";
|
||||
import { skeletonKey } from "../../../components/skeleton/skeleton-sizes";
|
||||
import type { LovelaceCardConfig } from "../../../data/lovelace/config/card";
|
||||
import type { HomeAssistant } from "../../../types";
|
||||
import { ConditionalListenerMixin } from "../../../mixins/conditional-listener-mixin";
|
||||
@@ -10,7 +12,10 @@ import { migrateLayoutToGridOptions } from "../common/compute-card-grid-size";
|
||||
import { computeCardSize } from "../common/compute-card-size";
|
||||
import { getConfigEntityId } from "../common/get-config-entity-id";
|
||||
import { tryCreateCardElement } from "../create-element/create-card-element";
|
||||
import { createErrorCardElement } from "../create-element/create-element-base";
|
||||
import {
|
||||
createErrorCardElement,
|
||||
lovelaceElementPending,
|
||||
} from "../create-element/create-element-base";
|
||||
import type { LovelaceCard, LovelaceGridOptions } from "../types";
|
||||
|
||||
declare global {
|
||||
@@ -63,6 +68,16 @@ export class HuiCard extends ConditionalListenerMixin<LovelaceCardConfig>(
|
||||
|
||||
private _element?: LovelaceCard;
|
||||
|
||||
/* Holds the card, and draws its skeleton while its code loads */
|
||||
private _overlay = document.createElement("ha-skeleton-overlay");
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this._overlay.style.height = "100%";
|
||||
this._overlay.style.borderRadius =
|
||||
"var(--ha-card-border-radius, var(--ha-border-radius-lg))";
|
||||
}
|
||||
|
||||
protected createRenderRoot() {
|
||||
return this;
|
||||
}
|
||||
@@ -134,6 +149,9 @@ export class HuiCard extends ConditionalListenerMixin<LovelaceCardConfig>(
|
||||
}
|
||||
this._element.setConfig(config);
|
||||
this._elementConfig = config;
|
||||
this._overlay.skeletonKey = this.preview
|
||||
? undefined
|
||||
: skeletonKey(JSON.stringify(config));
|
||||
fireEvent(this, "card-updated");
|
||||
}
|
||||
|
||||
@@ -183,6 +201,29 @@ export class HuiCard extends ConditionalListenerMixin<LovelaceCardConfig>(
|
||||
while (this.lastChild) {
|
||||
this.removeChild(this.lastChild);
|
||||
}
|
||||
|
||||
this._overlay.replaceChildren();
|
||||
this._overlay.skeletonKey = this.preview
|
||||
? undefined
|
||||
: skeletonKey(JSON.stringify(config));
|
||||
this.appendChild(this._overlay);
|
||||
|
||||
// A card whose code is still loading has nothing to show yet, so it
|
||||
// holds a row's height for the wave until it does
|
||||
const element = this._element;
|
||||
const pending = lovelaceElementPending(element, config.type);
|
||||
this._overlay.loading = pending !== undefined;
|
||||
this._overlay.style.minHeight = pending
|
||||
? "var(--row-height, var(--ha-section-grid-row-height, 56px))"
|
||||
: "";
|
||||
|
||||
pending?.then(() => {
|
||||
if (this._element === element) {
|
||||
this._overlay.loading = false;
|
||||
this._overlay.style.minHeight = "";
|
||||
}
|
||||
});
|
||||
|
||||
this._updateVisibility();
|
||||
}
|
||||
|
||||
@@ -285,12 +326,12 @@ export class HuiCard extends ConditionalListenerMixin<LovelaceCardConfig>(
|
||||
|
||||
if (this._element.connectedWhileHidden === true) {
|
||||
if (!this._element.parentElement) {
|
||||
this.appendChild(this._element);
|
||||
this._overlay.appendChild(this._element);
|
||||
}
|
||||
} else if (!visible && this._element.parentElement) {
|
||||
this.removeChild(this._element);
|
||||
this._overlay.removeChild(this._element);
|
||||
} else if (visible && !this._element.parentElement) {
|
||||
this.appendChild(this._element);
|
||||
this._overlay.appendChild(this._element);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -370,6 +370,8 @@ export class HuiHistoryGraphCard extends LitElement implements LovelaceCard {
|
||||
<state-history-charts
|
||||
.isLoadingData=${!this._history}
|
||||
.historyData=${this._history}
|
||||
.loadingEntityIds=${this._entityIds}
|
||||
?split-device-classes=${this._config.split_device_classes}
|
||||
.names=${this._names}
|
||||
up-to-now
|
||||
.hoursToShow=${this._hoursToShow}
|
||||
|
||||
@@ -32,7 +32,9 @@ export class HuiHorizontalStackCard extends HuiStackCard {
|
||||
height: 100%;
|
||||
}
|
||||
#root {
|
||||
display: flex;
|
||||
display: grid;
|
||||
grid-auto-flow: column;
|
||||
grid-auto-columns: minmax(0, 1fr);
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
gap: var(--horizontal-stack-card-gap, var(--stack-card-gap, 8px));
|
||||
@@ -40,9 +42,13 @@ export class HuiHorizontalStackCard extends HuiStackCard {
|
||||
#root > hui-card {
|
||||
display: contents;
|
||||
}
|
||||
#root > hui-card > * {
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
/* Cards stretch to the tallest one */
|
||||
#root > hui-card > ha-skeleton-overlay {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
#root > hui-card > ha-skeleton-overlay > * {
|
||||
flex: 1;
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
@@ -424,6 +424,7 @@ export class HuiLogbookCard extends LitElement implements LovelaceCard {
|
||||
.entityIds=${this._getEntityIds()}
|
||||
.stateFilter=${this._stateFilter}
|
||||
.nameDetail=${this._getNameDetail()}
|
||||
.placeholderRows=${3}
|
||||
narrow
|
||||
no-icon
|
||||
virtualize
|
||||
|
||||
@@ -453,6 +453,7 @@ class HuiMapCard extends LitElement implements LovelaceCard {
|
||||
.scaleRuler=${this._config.scale_ruler || false}
|
||||
@map-clicked=${this._handleMapClicked}
|
||||
interactive-zones
|
||||
data-skeleton="block"
|
||||
.renderPassive=${this.layout !== PANEL_VIEW_LAYOUT}
|
||||
></ha-map>
|
||||
<div id="buttons">
|
||||
|
||||
@@ -29,6 +29,7 @@ import type { PropertyValues } from "lit";
|
||||
import { LitElement, css, html, nothing } from "lit";
|
||||
import { customElement, query, state } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import { ifDefined } from "lit/directives/if-defined";
|
||||
import { repeat } from "lit/directives/repeat";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { calcDate } from "../../../common/datetime/calc_date";
|
||||
@@ -58,6 +59,7 @@ import "../../../components/list/ha-list-selectable";
|
||||
import type { HaListSelectable } from "../../../components/list/ha-list-selectable";
|
||||
import "../../../components/input/ha-input";
|
||||
import type { HaInput } from "../../../components/input/ha-input";
|
||||
import { SkeletonLoadingController } from "../../../components/skeleton/skeleton-loading-controller";
|
||||
import {
|
||||
apiContext,
|
||||
configContext,
|
||||
@@ -178,6 +180,23 @@ export class HuiTodoListCard extends LitElement implements LovelaceCard {
|
||||
|
||||
@state() private _items?: TodoItem[];
|
||||
|
||||
protected readonly _skeletonLoading = new SkeletonLoadingController(
|
||||
this,
|
||||
() => this._stateObj !== undefined && this._items === undefined
|
||||
);
|
||||
|
||||
/* Stand-ins for the items while they load, as many as the list's state
|
||||
says are still to do. They're drawn hidden, so a skeleton over the card
|
||||
takes the space the items will. */
|
||||
private _placeholderItems = memoizeOne((count: number): TodoItem[] =>
|
||||
Array.from({ length: count }, (_, index) => ({
|
||||
uid: `placeholder-${index}`,
|
||||
// Hidden, only their length counts
|
||||
summary: "x".repeat([14, 9, 18, 11][index % 4]),
|
||||
status: TodoItemStatus.NeedsAction,
|
||||
}))
|
||||
);
|
||||
|
||||
@state() private _reordering = false;
|
||||
|
||||
@query("ha-input", true) private _input!: HaInput;
|
||||
@@ -472,6 +491,16 @@ export class HuiTodoListCard extends LitElement implements LovelaceCard {
|
||||
const unavailable =
|
||||
stateObj.state === UNAVAILABLE || stateObj.state === UNKNOWN;
|
||||
|
||||
// While the items load, as many hidden rows as the list says are to do
|
||||
const toDo = Number(stateObj.state);
|
||||
|
||||
const placeholders =
|
||||
this._items === undefined && Number.isInteger(toDo) && toDo > 0
|
||||
? this._placeholderItems(Math.min(toDo, 50))
|
||||
: undefined;
|
||||
|
||||
const items = this._items ?? placeholders;
|
||||
|
||||
// Discard memoization when we rollover to a new day, so filters can be recalculated
|
||||
const memoTime = this._config.due_date_period
|
||||
? calcDate(
|
||||
@@ -483,20 +512,20 @@ export class HuiTodoListCard extends LitElement implements LovelaceCard {
|
||||
: 0;
|
||||
|
||||
const checkedItems = this._getCheckedItems(
|
||||
this._items,
|
||||
items,
|
||||
this._config.display_order,
|
||||
this._config.due_date_period,
|
||||
memoTime
|
||||
);
|
||||
const uncheckedItems = this._getUncheckedItems(
|
||||
this._items,
|
||||
items,
|
||||
this._config.display_order,
|
||||
this._config.due_date_period,
|
||||
memoTime
|
||||
);
|
||||
|
||||
const itemsWithoutStatus = this._getItemsWithoutStatus(
|
||||
this._items,
|
||||
items,
|
||||
this._config.display_order,
|
||||
this._config.due_date_period,
|
||||
memoTime
|
||||
@@ -504,7 +533,7 @@ export class HuiTodoListCard extends LitElement implements LovelaceCard {
|
||||
|
||||
const reorderableItems = this._reordering
|
||||
? this._getUncheckedAndItemsWithoutStatus(
|
||||
this._items,
|
||||
items,
|
||||
this._config.display_order,
|
||||
this._config.due_date_period,
|
||||
memoTime
|
||||
@@ -548,6 +577,9 @@ export class HuiTodoListCard extends LitElement implements LovelaceCard {
|
||||
: nothing
|
||||
}
|
||||
<ha-sortable
|
||||
class=${classMap({ placeholder: placeholders !== undefined })}
|
||||
?inert=${placeholders !== undefined}
|
||||
aria-hidden=${ifDefined(placeholders ? "true" : undefined)}
|
||||
handle-selector="ha-svg-icon"
|
||||
draggable-selector=".draggable"
|
||||
.disabled=${!this._reordering}
|
||||
@@ -1119,6 +1151,10 @@ export class HuiTodoListCard extends LitElement implements LovelaceCard {
|
||||
--ha-icon-button-size: 32px;
|
||||
}
|
||||
|
||||
ha-sortable.placeholder {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.addRow,
|
||||
.header {
|
||||
display: flex;
|
||||
|
||||
@@ -19,6 +19,7 @@ import { formatNumber } from "../../../common/number/format_number";
|
||||
import { round } from "../../../common/number/round";
|
||||
import "../../../components/ha-card";
|
||||
import "../../../components/ha-svg-icon";
|
||||
import { SkeletonLoadingController } from "../../../components/skeleton/skeleton-loading-controller";
|
||||
import {
|
||||
configContext,
|
||||
connectionContext,
|
||||
@@ -31,6 +32,7 @@ import type { ActionHandlerEvent } from "../../../data/lovelace/action_handler";
|
||||
import type {
|
||||
ForecastAttribute,
|
||||
ForecastEvent,
|
||||
ForecastType,
|
||||
WeatherEntity,
|
||||
} from "../../../data/weather";
|
||||
import {
|
||||
@@ -125,8 +127,15 @@ class HuiWeatherForecastCard extends LitElement implements LovelaceCard {
|
||||
|
||||
@state() private _forecastEvent?: ForecastEvent;
|
||||
|
||||
@state() private _forecastFailed = false;
|
||||
|
||||
@state() private _subscribed?: Promise<() => void>;
|
||||
|
||||
protected readonly _skeletonLoading = new SkeletonLoadingController(
|
||||
this,
|
||||
() => this._isForecastLoading()
|
||||
);
|
||||
|
||||
private _dragScrollController = new DragScrollController(this, {
|
||||
selector: ".forecast",
|
||||
enabled: false,
|
||||
@@ -162,6 +171,45 @@ class HuiWeatherForecastCard extends LitElement implements LovelaceCard {
|
||||
);
|
||||
}
|
||||
|
||||
/* Waiting for the first forecast of the type the card shows */
|
||||
private _isForecastLoading(): boolean {
|
||||
const stateObj = this._stateObj;
|
||||
|
||||
return Boolean(
|
||||
this._config &&
|
||||
this._config.show_forecast !== false &&
|
||||
this._needForecastSubscription() &&
|
||||
stateObj &&
|
||||
stateObj.state !== UNAVAILABLE &&
|
||||
this._forecastEvent?.type !== this._config.forecast_type &&
|
||||
!this._forecastFailed
|
||||
);
|
||||
}
|
||||
|
||||
/* Stand-ins for the forecast while it loads, drawn hidden so a skeleton
|
||||
over the card takes the space the forecast will */
|
||||
private _placeholderForecast(
|
||||
type: ForecastType | undefined,
|
||||
condition: string,
|
||||
count: number
|
||||
): ForecastAttribute[] {
|
||||
const step =
|
||||
type === "hourly"
|
||||
? 60 * 60 * 1000
|
||||
: type === "twice_daily"
|
||||
? 12 * 60 * 60 * 1000
|
||||
: 24 * 60 * 60 * 1000;
|
||||
|
||||
const now = Date.now();
|
||||
|
||||
return Array.from({ length: count }, (_, index) => ({
|
||||
datetime: new Date(now + index * step).toISOString(),
|
||||
condition,
|
||||
temperature: 0,
|
||||
is_daytime: type === "twice_daily" ? index % 2 === 0 : undefined,
|
||||
}));
|
||||
}
|
||||
|
||||
private _unsubscribeForecastEvents() {
|
||||
if (this._subscribed) {
|
||||
this._subscribed.then((unsub) => unsub());
|
||||
@@ -189,8 +237,10 @@ class HuiWeatherForecastCard extends LitElement implements LovelaceCard {
|
||||
this._config!.forecast_type as "daily" | "hourly" | "twice_daily",
|
||||
(event) => {
|
||||
this._forecastEvent = event;
|
||||
this._forecastFailed = false;
|
||||
}
|
||||
).catch((e) => {
|
||||
this._forecastFailed = true;
|
||||
if (e.code === "invalid_entity_id") {
|
||||
setTimeout(() => {
|
||||
this._subscribed = undefined;
|
||||
@@ -312,14 +362,26 @@ class HuiWeatherForecastCard extends LitElement implements LovelaceCard {
|
||||
|
||||
const itemsToShow = this._config?.forecast_slots ?? 5;
|
||||
|
||||
const forecastLoading = this._isForecastLoading();
|
||||
|
||||
const forecast =
|
||||
this._config?.show_forecast !== false && forecastData?.forecast?.length
|
||||
? forecastData.forecast.slice(0, itemsToShow)
|
||||
: undefined;
|
||||
: forecastLoading
|
||||
? this._placeholderForecast(
|
||||
this._config.forecast_type,
|
||||
stateObj.state,
|
||||
itemsToShow
|
||||
)
|
||||
: undefined;
|
||||
const weather = !forecast || this._config?.show_current !== false;
|
||||
|
||||
const hourly = forecastData?.type === "hourly";
|
||||
const dayNight = forecastData?.type === "twice_daily";
|
||||
const forecastType = forecastLoading
|
||||
? this._config.forecast_type
|
||||
: forecastData?.type;
|
||||
|
||||
const hourly = forecastType === "hourly";
|
||||
const dayNight = forecastType === "twice_daily";
|
||||
const compactForecast = this._sizeController.value?.height === "short";
|
||||
// Hourly forecasts skip day names, because 0:00 already marks a new day.
|
||||
const showInlineDayLabel = compactForecast && dayNight;
|
||||
@@ -485,6 +547,8 @@ class HuiWeatherForecastCard extends LitElement implements LovelaceCard {
|
||||
compact: compactForecast,
|
||||
dragging: this._dragScrollController.scrolling,
|
||||
})}
|
||||
style=${ifDefined(forecastLoading ? "opacity: 0" : undefined)}
|
||||
aria-hidden=${ifDefined(forecastLoading ? "true" : undefined)}
|
||||
>
|
||||
${
|
||||
showDayHeader
|
||||
|
||||
@@ -164,8 +164,27 @@ abstract class HuiWaterGasFlowSankeyCard
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const { group_by_area, group_by_floor, layout, title } = this._config;
|
||||
|
||||
const vertical =
|
||||
layout === "vertical" || (layout !== "horizontal" && this._isMobileSize);
|
||||
|
||||
const cardClasses = classMap({
|
||||
"is-grid": this.layout === "grid",
|
||||
"is-panel": this.layout === "panel",
|
||||
"is-vertical": vertical,
|
||||
});
|
||||
|
||||
if (!this._data) {
|
||||
return html`${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}`;
|
||||
return html`
|
||||
<ha-card .header=${title} class=${cardClasses}>
|
||||
<div class="card-content">
|
||||
<div class="loading" data-skeleton="block">
|
||||
${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}
|
||||
</div>
|
||||
</div>
|
||||
</ha-card>
|
||||
`;
|
||||
}
|
||||
|
||||
const resource = this.resource;
|
||||
@@ -335,7 +354,6 @@ abstract class HuiWaterGasFlowSankeyCard
|
||||
});
|
||||
links.push(...deviceLinks);
|
||||
|
||||
const { group_by_area, group_by_floor, layout, title } = this._config;
|
||||
const sankeyLayout = buildSankeyLayout({
|
||||
states: this._states,
|
||||
registries: this._registries,
|
||||
@@ -354,18 +372,8 @@ abstract class HuiWaterGasFlowSankeyCard
|
||||
|
||||
const hasData = nodes.some((node) => node.value > 0);
|
||||
|
||||
const vertical =
|
||||
layout === "vertical" || (layout !== "horizontal" && this._isMobileSize);
|
||||
|
||||
return html`
|
||||
<ha-card
|
||||
.header=${title}
|
||||
class=${classMap({
|
||||
"is-grid": this.layout === "grid",
|
||||
"is-panel": this.layout === "panel",
|
||||
"is-vertical": vertical,
|
||||
})}
|
||||
>
|
||||
<ha-card .header=${title} class=${cardClasses}>
|
||||
<div class="card-content">
|
||||
${
|
||||
hasData
|
||||
@@ -438,6 +446,9 @@ abstract class HuiWaterGasFlowSankeyCard
|
||||
flex: 1;
|
||||
display: flex;
|
||||
}
|
||||
.loading {
|
||||
flex: 1;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
@@ -137,8 +137,26 @@ abstract class HuiWaterGasSankeyCard
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const vertical =
|
||||
this._config.layout === "vertical" ||
|
||||
(this._config.layout !== "horizontal" && this._isMobileSize);
|
||||
|
||||
const cardClasses = classMap({
|
||||
"is-grid": this.layout === "grid",
|
||||
"is-panel": this.layout === "panel",
|
||||
"is-vertical": vertical,
|
||||
});
|
||||
|
||||
if (!this._data) {
|
||||
return html`${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}`;
|
||||
return html`
|
||||
<ha-card .header=${this._config.title} class=${cardClasses}>
|
||||
<div class="card-content">
|
||||
<div class="loading" data-skeleton="block">
|
||||
${this._i18n.localize("ui.panel.lovelace.cards.energy.loading")}
|
||||
</div>
|
||||
</div>
|
||||
</ha-card>
|
||||
`;
|
||||
}
|
||||
|
||||
const data = this._data;
|
||||
@@ -309,19 +327,8 @@ abstract class HuiWaterGasSankeyCard
|
||||
|
||||
const hasData = nodes.some((node) => node.value > 0);
|
||||
|
||||
const vertical =
|
||||
this._config.layout === "vertical" ||
|
||||
(this._config.layout !== "horizontal" && this._isMobileSize);
|
||||
|
||||
return html`
|
||||
<ha-card
|
||||
.header=${this._config.title}
|
||||
class=${classMap({
|
||||
"is-grid": this.layout === "grid",
|
||||
"is-panel": this.layout === "panel",
|
||||
"is-vertical": vertical,
|
||||
})}
|
||||
>
|
||||
<ha-card .header=${this._config.title} class=${cardClasses}>
|
||||
<div class="card-content">
|
||||
${
|
||||
hasData
|
||||
@@ -374,6 +381,9 @@ abstract class HuiWaterGasSankeyCard
|
||||
flex: 1;
|
||||
display: flex;
|
||||
}
|
||||
.loading {
|
||||
flex: 1;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
@@ -208,6 +208,13 @@ export class HuiEnergyPeriodSelector extends LitElement {
|
||||
this._measure();
|
||||
}
|
||||
|
||||
// The collection knows its period before its data comes, so the
|
||||
// selector can show it from the start
|
||||
if (!this._startDate && this._energyCollection.collection) {
|
||||
this._startDate = this._energyCollection.collection.start;
|
||||
this._endDate = this._energyCollection.collection.end || endOfToday();
|
||||
}
|
||||
|
||||
if (changedProps.has("showCombineSources")) {
|
||||
this._applyDefaultCombineSources();
|
||||
}
|
||||
|
||||
@@ -13,7 +13,9 @@ import { computeDomain } from "../../../common/entity/compute_domain";
|
||||
import parseAspectRatio from "../../../common/util/parse-aspect-ratio";
|
||||
import "../../../components/ha-camera-stream";
|
||||
import type { HaCameraStream } from "../../../components/ha-camera-stream";
|
||||
import "../../../components/ha-spinner";
|
||||
import "../../../components/animation/ha-fade-in";
|
||||
import "../../../components/skeleton/ha-skeleton";
|
||||
import { fadeInArrival } from "../../../components/skeleton/skeleton-arrival";
|
||||
import type { CameraEntity } from "../../../data/camera";
|
||||
import { fetchThumbnailUrlWithCache } from "../../../data/camera";
|
||||
import { UNAVAILABLE } from "../../../data/entity/entity";
|
||||
@@ -73,6 +75,8 @@ export class HuiImage extends LitElement {
|
||||
|
||||
@query("#image") private _img?: HTMLImageElement;
|
||||
|
||||
@query(".container") private _container?: HTMLDivElement;
|
||||
|
||||
private _reconnectImg = false;
|
||||
|
||||
@state() private _cameraImageSrc?: string;
|
||||
@@ -261,8 +265,8 @@ export class HuiImage extends LitElement {
|
||||
filter = isOff && imageFallback ? DEFAULT_FILTER : "";
|
||||
}
|
||||
|
||||
// Snapshots load only once the card is on screen; skip the spinner until then.
|
||||
const showSpinner = !this.cameraImage || this._imageVisible;
|
||||
// Snapshots load only once the card is on screen; skip the skeleton until then.
|
||||
const showSkeleton = !this.cameraImage || this._imageVisible;
|
||||
|
||||
return html`
|
||||
<div
|
||||
@@ -334,7 +338,9 @@ export class HuiImage extends LitElement {
|
||||
(imageSrc === undefined ||
|
||||
this._loadState === LoadState.Loading)
|
||||
? html`<div
|
||||
class="progress-container"
|
||||
class="loading"
|
||||
role="progressbar"
|
||||
aria-label=${this.hass.localize("ui.common.loading")}
|
||||
style=${styleMap({
|
||||
height: !useRatio
|
||||
? this._lastImageHeight
|
||||
@@ -344,11 +350,10 @@ export class HuiImage extends LitElement {
|
||||
})}
|
||||
>
|
||||
${
|
||||
showSpinner
|
||||
? html`<ha-spinner
|
||||
class="render-spinner"
|
||||
size="small"
|
||||
></ha-spinner>`
|
||||
showSkeleton
|
||||
? html`<ha-fade-in .duration=${300} easing="ease-in">
|
||||
<ha-skeleton></ha-skeleton>
|
||||
</ha-fade-in>`
|
||||
: nothing
|
||||
}
|
||||
</div>`
|
||||
@@ -406,6 +411,7 @@ export class HuiImage extends LitElement {
|
||||
private async _onImageLoad(
|
||||
ev: HASSDomTargetEvent<HTMLImageElement>
|
||||
): Promise<void> {
|
||||
const arriving = this._loadState === LoadState.Loading;
|
||||
this._loadState = LoadState.Loaded;
|
||||
const imgEl = ev.target;
|
||||
if (this._ratio && this._ratio.w > 0 && this._ratio.h > 0) {
|
||||
@@ -413,6 +419,11 @@ export class HuiImage extends LitElement {
|
||||
}
|
||||
await this.updateComplete;
|
||||
this._lastImageHeight = imgEl.offsetHeight;
|
||||
|
||||
// The picture takes the skeleton's place, so it fades in
|
||||
if (arriving && this._container) {
|
||||
fadeInArrival(this._container);
|
||||
}
|
||||
}
|
||||
|
||||
private async _onVideoLoad(
|
||||
@@ -497,10 +508,8 @@ export class HuiImage extends LitElement {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.progress-container {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
ha-skeleton {
|
||||
--ha-skeleton-border-radius: 0;
|
||||
}
|
||||
|
||||
.ratio {
|
||||
|
||||
@@ -228,6 +228,35 @@ const _lazyCreate = <T extends keyof CreateElementConfigTypes>(
|
||||
const _getCustomTag = (type: string) =>
|
||||
isCustomType(type) ? stripCustomPrefix(type) : undefined;
|
||||
|
||||
/**
|
||||
* For an element made for `type` that is still waiting for its code, a
|
||||
* promise for when it has something to show: once its code has loaded, or
|
||||
* once a custom one gives up and shows its error. Undefined when it already
|
||||
* has.
|
||||
*/
|
||||
export const lovelaceElementPending = (
|
||||
element: HTMLElement,
|
||||
type: string | undefined
|
||||
): Promise<void> | undefined => {
|
||||
const customTag = type ? _getCustomTag(type) : undefined;
|
||||
const tag = customTag ?? element.localName;
|
||||
|
||||
if (customElements.get(tag)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const defined = customElements.whenDefined(tag).then(() => undefined);
|
||||
|
||||
return customTag
|
||||
? Promise.race([
|
||||
defined,
|
||||
new Promise<void>((resolve) => {
|
||||
setTimeout(resolve, TIMEOUT);
|
||||
}),
|
||||
])
|
||||
: defined;
|
||||
};
|
||||
|
||||
export const createLovelaceElement = <T extends keyof CreateElementConfigTypes>(
|
||||
tagSuffix: T,
|
||||
config: CreateElementConfigTypes[T]["config"],
|
||||
|
||||
@@ -10,6 +10,7 @@ import "../../../components/animation/ha-fade-in";
|
||||
import "../../../components/ha-alert";
|
||||
import "../../../components/skeleton/ha-skeleton";
|
||||
import "../../../components/skeleton/ha-skeleton-text";
|
||||
import { skeletonOr } from "../../../components/skeleton/skeleton-arrival";
|
||||
import "../../../components/ha-yaml-editor";
|
||||
import type { HaYamlEditor } from "../../../components/ha-yaml-editor";
|
||||
import type { LovelaceConfig } from "../../../data/lovelace/config/types";
|
||||
@@ -267,15 +268,13 @@ export abstract class HuiElementEditor<
|
||||
class="gui-editor"
|
||||
@edit-sub-element=${this._editSubElement}
|
||||
>
|
||||
${
|
||||
this._loading
|
||||
? this._renderLoading()
|
||||
: cache(
|
||||
this._subElementEditorConfig
|
||||
? this._renderSubElement()
|
||||
: this.renderConfigElement()
|
||||
)
|
||||
}
|
||||
${skeletonOr(this._loading, this._renderLoading(), () =>
|
||||
cache(
|
||||
this._subElementEditorConfig
|
||||
? this._renderSubElement()
|
||||
: this.renderConfigElement()
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
`
|
||||
: html`
|
||||
|
||||
Reference in new issue
Block a user