Compare commits

...
15 Commits
Author SHA1 Message Date
Aidan Timson 5685ec73a6 Add card skeleton guidance to the components skill 2026-11-23 10:05:43 +00:00
Aidan Timson 68238fcc0b Add a card skeletons gallery page 2026-11-23 10:05:43 +00:00
Aidan Timson cc923acaab Show card and badge skeletons while their code loads 2026-11-23 10:05:43 +00:00
Aidan Timson 1d76e0b241 Remember how tall skeleton content was between loads 2026-11-23 10:05:43 +00:00
Aidan Timson fa6bcf39ed Fade in editors, onboarding and tile text after their skeletons 2026-11-23 10:05:43 +00:00
Aidan Timson a630038932 Use the shared skeleton and fade in the backup summary 2026-11-23 10:05:43 +00:00
Aidan Timson 418d83e728 Fade in logs after their skeletons 2026-11-23 10:05:42 +00:00
Aidan Timson 74cc4a0904 Fade in data tables and device cells after their skeletons 2026-11-23 10:05:42 +00:00
Aidan Timson c87c6aa737 Add a shared fade for content that replaces a skeleton 2026-11-23 10:05:42 +00:00
Aidan Timson 921e3258c7 Name the skeleton overlay before translations load 2026-11-23 10:05:42 +00:00
Aidan Timson c1bec10ec4 Add skeleton overlay guidance to the components skill 2026-11-23 10:05:42 +00:00
Aidan Timson e3a1cec8ea Add a skeleton overlay that reads its shape from the content 2026-11-23 10:05:41 +00:00
Aidan Timson b50fbc985c Slant the skeleton wave from the top corner of the content 2026-11-23 10:05:08 +00:00
Aidan Timson 3eb346abab Run the skeleton wave across the content in one continuous loop 2026-11-23 09:20:18 +00:00
Aidan Timson 26c6ee9afd Make one shared soft wave the default skeleton effect 2026-11-23 09:20:11 +00:00
27 changed files with 2524 additions and 352 deletions

No files matched your search

+24 -1
View File
@@ -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,26 @@ 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.
- `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 has to say when it's loading.
- 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`.
- 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;
}
}
+549
View File
@@ -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],
};
};
+5 -1
View File
@@ -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 {
@@ -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;
}
}
+9 -3
View File
@@ -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;
}
`,
];
}
+189 -7
View File
@@ -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;
}
}
`,
];
+128
View File
@@ -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);
+99
View File
@@ -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)}`;
};
+11 -9
View File
@@ -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>
`;
}
@@ -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 -1
View File
@@ -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>
`;
+31 -42
View File
@@ -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")}:
+29 -1
View File
@@ -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);
+46 -43
View File
@@ -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>
`;
+39 -4
View File
@@ -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);
}
}
}
+45 -4
View File
@@ -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);
}
}
}
@@ -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;
}
`,
];
+22 -13
View File
@@ -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`