Compare commits

...
6 Commits
5 changed files with 1177 additions and 11 deletions

No files matched your search

+22 -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.
- Don't add your own fade to loaded content. `ha-skeleton-overlay` fades each part in over `--ha-animation-duration-fast`, which reduced motion makes instant.
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,24 @@ 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.
- 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.
+545
View File
@@ -0,0 +1,545 @@
/**
* 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 => {
if (element.localName.startsWith("ha-skeleton")) {
return "none";
}
const value = element.getAttribute("data-skeleton");
return isOverride(value) ? value : undefined;
};
export interface SkeletonPiece {
kind: SkeletonPieceKind;
x: number;
y: number;
width: number;
height: number;
radius?: string;
/* An SVG mask for a drawing, such as a gauge arc */
mask?: string;
/* The part sits on a dark overlay, such as a picture card's name bar */
onDark?: boolean;
/* A see-through bar laid over a picture, kept as it is */
background?: string;
}
export interface ExtractedSkeleton {
pieces: SkeletonPiece[];
/* The elements the pieces stand in for, hidden while loading */
parts: (HTMLElement | SVGElement)[];
/* Elements holding text: hide only the text colour, as the same element
often draws a frame, such as a badge's pill, that has to stay */
textParts: HTMLElement[];
}
const ROUND_TAGS = new Set([
"ha-tile-icon",
"ha-state-icon",
"ha-svg-icon",
"ha-icon",
"state-badge",
]);
const BLOCK_TAGS = new Set(["img", "video", "ha-camera-stream"]);
/* A canvas to measure fonts with, made on first use */
let measuringContext: CanvasRenderingContext2D | null | undefined;
const fontContext = (style: CSSStyleDeclaration, size: string) => {
measuringContext ??= document.createElement("canvas").getContext("2d");
if (measuringContext) {
measuringContext.font = `${style.fontStyle} ${style.fontWeight} ${size} ${style.fontFamily}`;
}
return measuringContext;
};
/**
* Where a text bar goes on a line of this font: from the top of the
* capitals down to the baseline, measured from the font itself.
* `size` is the size as drawn, after any SVG scaling.
*/
const capitalBand = (style: CSSStyleDeclaration, size: number) => {
const context = fontContext(style, `${size}px`);
if (!context) {
return { top: size * 0.2, height: size * 0.7 };
}
const metrics = context.measureText("H");
return {
// The line box holds the font's ascent, so the baseline sits that far down
top: metrics.fontBoundingBoxAscent - metrics.actualBoundingBoxAscent,
height: metrics.actualBoundingBoxAscent,
};
};
/* How wide "…" is in this font, the room cut-off text leaves at its end */
const ellipsisWidth = (style: CSSStyleDeclaration) =>
fontContext(style, style.fontSize)?.measureText("…").width ??
parseFloat(style.fontSize);
/* The icon as drawn, not its box, which a line of text can crop */
const findGlyph = (element: Element, depth = 4): Element | undefined => {
if (depth === 0) {
return undefined;
}
for (const child of [
...(element.shadowRoot?.children ?? []),
...element.children,
]) {
if (child instanceof SVGSVGElement) {
return child;
}
const found = findGlyph(child, depth - 1);
if (found) {
return found;
}
}
return undefined;
};
/* Near-white text or icons, as on a picture card's dark name bar */
const isNearWhite = (color: string): boolean => {
const channels = color
.match(/[\d.]+/g)
?.slice(0, 3)
.map(Number);
return channels?.length === 3 && channels.every((channel) => channel >= 200);
};
const isRendered = (style: CSSStyleDeclaration) =>
style.display !== "none" && style.visibility !== "hidden";
const isSeeThrough = (color: string) => {
const alpha = Number(color.match(/rgba\(.*,\s*([\d.]+)\)/)?.[1] ?? 1);
return alpha > 0 && alpha < 1;
};
/* The first element, inside shadow roots too, that rounds its corners */
const findRounded = (element: Element, depth = 4): Element | undefined => {
if (depth === 0) {
return undefined;
}
const children = [
...(element.shadowRoot?.children ?? []),
...element.children,
];
for (const child of children) {
if (parseFloat(getComputedStyle(child).borderTopLeftRadius) > 0) {
return child;
}
const found = findRounded(child, depth - 1);
if (found) {
return found;
}
}
return undefined;
};
/* Join the pieces of one line of text, such as "Heat", "·" and "21 °C" */
const mergeLines = (pieces: SkeletonPiece[]): SkeletonPiece[] => {
const merged: SkeletonPiece[] = [];
for (const piece of pieces) {
const previous = merged[merged.length - 1];
// Either side, so right-to-left lines join too
const gap = previous
? Math.max(
piece.x - (previous.x + previous.width),
previous.x - (piece.x + piece.width)
)
: Infinity;
const sameLine =
previous?.kind === "text" &&
piece.kind === "text" &&
Math.abs(previous.y - piece.y) < 2 &&
Math.abs(previous.height - piece.height) < 2 &&
gap < 12;
if (sameLine) {
const left = Math.min(previous.x, piece.x);
const right = Math.max(
previous.x + previous.width,
piece.x + piece.width
);
previous.x = left;
previous.width = right - left;
continue;
}
merged.push({ ...piece });
}
return merged;
};
const svgMask = (svg: SVGSVGElement, width: number, height: number) => {
const clone = svg.cloneNode(true);
if (!(clone instanceof SVGSVGElement)) {
return undefined;
}
const originals = [svg, ...svg.querySelectorAll("*")];
const copies = [clone, ...clone.querySelectorAll("*")];
let drawnPaths = 0;
originals.forEach((original, index) => {
const copy = copies[index];
const style = getComputedStyle(original);
if (original.localName === "text" || !isRendered(style)) {
copy.setAttribute("display", "none");
return;
}
if (original !== svg && original.localName !== "g") {
drawnPaths++;
}
copy.removeAttribute("class");
copy.removeAttribute("style");
copy.setAttribute("fill", style.fill === "none" ? "none" : "#000");
copy.setAttribute("stroke", style.stroke === "none" ? "none" : "#000");
copy.setAttribute("stroke-width", style.strokeWidth);
copy.setAttribute("stroke-linecap", style.strokeLinecap);
});
if (drawnPaths === 0) {
return undefined;
}
clone.setAttribute("width", String(width));
clone.setAttribute("height", String(height));
const markup = new XMLSerializer().serializeToString(clone);
return `url("data:image/svg+xml,${encodeURIComponent(markup)}")`;
};
export const extractSkeleton = (
root: Element,
origin: DOMRect
): ExtractedSkeleton => {
const pieces: SkeletonPiece[] = [];
const parts = new Set<HTMLElement | SVGElement>();
const textParts = new Set<HTMLElement>();
/* The card's own background, the first solid one found */
let surface: string | undefined;
const box = (rect: DOMRect) => ({
x: rect.left - origin.left,
y: rect.top - origin.top,
width: rect.width,
height: rect.height,
});
/* Near-white content on a light card must sit on a dark bar */
const onDark = (style: CSSStyleDeclaration) =>
surface !== undefined && isNearWhite(surface) && isNearWhite(style.color);
const addText = (element: Element | ShadowRoot) => {
const owner = element instanceof ShadowRoot ? element.host : element;
// Text cut short with an ellipsis reaches past its box, so clip to it
const clip = owner.getBoundingClientRect();
element.childNodes.forEach((node) => {
if (!(node instanceof Text) || !node.textContent?.trim()) {
return;
}
// Slotted text takes its font and colour from the slot it shows in,
// so that's where it's measured and hidden
const slot = node.assignedSlot;
const hideTarget = slot ?? owner;
const style = getComputedStyle(hideTarget);
const band = capitalBand(style, parseFloat(style.fontSize));
if (hideTarget instanceof HTMLElement) {
textParts.add(hideTarget);
}
const range = document.createRange();
range.selectNodeContents(node);
for (const rect of range.getClientRects()) {
// Cut-off text ends in "…", on the right or, right to left, on the
// left, so stop the bar where that starts
const left =
rect.left < clip.left - 1
? clip.left + ellipsisWidth(style)
: rect.left;
const right =
rect.right > clip.right + 1
? clip.right - ellipsisWidth(style)
: rect.right;
if (right <= left) {
continue;
}
pieces.push({
kind: "text",
x: left - origin.left,
width: right - left,
y: rect.top - origin.top + band.top,
height: band.height,
onDark: onDark(style),
});
}
});
};
const walk = (node: Element | ShadowRoot) => {
// Text straight inside a shadow root, as state-display renders its state
if (node instanceof ShadowRoot) {
addText(node);
}
for (const child of node.children) {
const style = getComputedStyle(child);
if (!isRendered(style)) {
continue;
}
const rect = child.getBoundingClientRect();
const tag = child.localName;
// Elements such as slots take no space but their content does
const hasSize = rect.width > 0 && rect.height > 0;
const override = skeletonOverride(child);
if (override === "none") {
continue;
}
if (override === "keep") {
if (child.shadowRoot) {
walk(child.shadowRoot);
}
walk(child);
continue;
}
if (override !== undefined) {
if (
hasSize &&
(child instanceof HTMLElement || child instanceof SVGElement)
) {
const size = Math.min(rect.width, rect.height);
const piece = box(rect);
pieces.push(
override === "round"
? {
kind: "round",
x: piece.x + (piece.width - size) / 2,
y: piece.y + (piece.height - size) / 2,
width: size,
height: size,
}
: { kind: override, ...piece, radius: style.borderRadius }
);
parts.add(child);
}
continue;
}
if (
surface === undefined &&
hasSize &&
style.backgroundColor !== "rgba(0, 0, 0, 0)" &&
!isSeeThrough(style.backgroundColor)
) {
surface = style.backgroundColor;
}
if (child instanceof HTMLElement && ROUND_TAGS.has(tag)) {
// Use the circle itself, such as the tile icon's 36px background
const circle = (
findRounded(child) ??
findGlyph(child) ??
child
).getBoundingClientRect();
const size =
Math.min(circle.width, circle.height) ||
Math.max(circle.width, circle.height);
const piece = box(circle);
if (size > 0) {
pieces.push({
kind: "round",
x: piece.x + (piece.width - size) / 2,
y: piece.y + (piece.height - size) / 2,
width: size,
height: size,
onDark: onDark(style),
});
parts.add(child);
}
continue;
}
// A see-through bar over a picture stays, so text keeps its contrast
if (
child instanceof HTMLElement &&
hasSize &&
style.position === "absolute" &&
isSeeThrough(style.backgroundColor)
) {
pieces.push({
kind: "scrim",
...box(rect),
radius: style.borderRadius,
background: style.backgroundColor,
});
}
// Pictures drawn as a background, as hui-image does in a fixed ratio
if (
child instanceof HTMLElement &&
hasSize &&
style.backgroundImage.startsWith("url(")
) {
pieces.push({
kind: "block",
...box(rect),
radius: style.borderRadius,
});
parts.add(child);
continue;
}
if (child instanceof HTMLElement && hasSize && BLOCK_TAGS.has(tag)) {
pieces.push({
kind: "block",
...box(rect),
radius: style.borderRadius,
});
parts.add(child);
continue;
}
if (
child instanceof HTMLElement &&
hasSize &&
tag.endsWith("-card-feature")
) {
const control = findRounded(child);
const radius = control
? getComputedStyle(control).borderRadius
: style.borderRadius;
pieces.push({ kind: "block", ...box(rect), radius });
parts.add(child);
continue;
}
if (child instanceof SVGSVGElement && hasSize) {
const piece = box(rect);
const mask = svgMask(child, piece.width, piece.height);
if (mask) {
pieces.push({ kind: "shape", ...piece, mask });
}
child.querySelectorAll("text").forEach((text) => {
const textRect = text.getBoundingClientRect();
if (textRect.width === 0) {
return;
}
// SVG text is scaled with its drawing, as the gauge value is
const scale = text.getScreenCTM()?.a ?? 1;
const textStyle = getComputedStyle(text);
const band = capitalBand(
textStyle,
parseFloat(textStyle.fontSize) * scale
);
pieces.push({
kind: "text",
...box(textRect),
y: textRect.top - origin.top + band.top,
height: band.height,
});
});
parts.add(child);
continue;
}
if (child instanceof HTMLElement) {
addText(child);
}
if (child.shadowRoot) {
walk(child.shadowRoot);
}
walk(child);
}
};
walk(root);
return {
pieces: mergeLines(pieces),
parts: [...parts],
textParts: [...textParts],
};
};
@@ -0,0 +1,412 @@
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";
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 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";
@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;
private _resizeObserver = new ResizeObserver(() => this._scheduleMeasure());
private _intersectionObserver = new IntersectionObserver((entries) => {
this._onScreen = entries[entries.length - 1].isIntersecting;
});
public connectedCallback() {
super.connectedCallback();
this._resizeObserver.observe(this);
this._intersectionObserver.observe(this);
this._scheduleMeasure();
}
public disconnectedCallback() {
super.disconnectedCallback();
this._resizeObserver.disconnect();
this._intersectionObserver.disconnect();
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"
);
}
if (!loading && this._wasLoading) {
this._endLoading();
}
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();
}
private _contentChanged() {
this._resizeObserver.disconnect();
this._resizeObserver.observe(this);
this._contentSlot
?.assignedElements()
.forEach((element) => this._resizeObserver.observe(element));
// Content that went away can't finish loading
const sources = [...this._loadingSources].filter(
(source) => !(source instanceof Node) || source.isConnected
);
if (sources.length !== this._loadingSources.size) {
this._loadingSources = new Set(sources);
}
this._scheduleMeasure();
}
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() {
if (!this._isLoading || 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;
}
}
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 before the first reading, the whole
// content was hidden rather than its parts
const wholeContent = this._customSkeleton || this._pieces === undefined;
this._arriving = {
content: wholeContent
? (this._contentSlot?.assignedElements() ?? [])
: [],
opacityParts: [...this._hiddenOpacity.keys()],
colorParts: [...this._hiddenColor.keys()],
};
this._showParts();
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;
}
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;
}
}
`,
];