Skip to content

A platform for community discussion. Free, open, simple.

DEV: Add a `DSkeleton` loading-placeholder primitive (#42380)

Sérgio Saquetimd250a71cf11e
diff --git a/app/assets/stylesheets/common/components/_index.scss b/app/assets/stylesheets/common/components/_index.scss
index fa74929a94e..ad1af47216c 100644
--- a/app/assets/stylesheets/common/components/_index.scss
+++ b/app/assets/stylesheets/common/components/_index.scss
@@ -12,6 +12,7 @@
@import "buttons";
@import "d-segmented-control";
@import "d-select";
+@import "d-skeleton";
@import "d-access-control";
@import "color-input";
@import "char-counter";
diff --git a/app/assets/stylesheets/common/components/d-skeleton.scss b/app/assets/stylesheets/common/components/d-skeleton.scss
new file mode 100644
index 00000000000..39836d2727d
--- /dev/null
+++ b/app/assets/stylesheets/common/components/d-skeleton.scss
@@ -0,0 +1,75 @@
+// Theming tokens (fill, shimmer, duration, radius) are deliberately not declared
+// here: left undeclared they can be set by a consumer class on the skeleton or
+// scoped from any ancestor, and their defaults live at the point of use below.
+// Layout tokens are declared, so an ancestor cannot silently relay out a nested
+// skeleton that had nothing to do with the intent — but at zero specificity, so
+// a consumer's own class still outranks them whatever order the stylesheets load
+// in. Variant blocks override this one and must follow it.
+:where(.d-skeleton) {
+ --d-skeleton-gap: 0.5em;
+ --d-skeleton-display: flex;
+ --d-skeleton-item-width: auto;
+}
+
+// A lone line matches the real element's line box; stacked lines drop to ink
+// height and sit one leading apart, so a paragraph reads as separate lines. The
+// two are mutually exclusive rather than ordered, so moving one cannot change
+// what wins.
+:where(.d-skeleton--text:not(.d-skeleton--multiline)) {
+ --d-skeleton-item-height: 1lh;
+}
+
+:where(.d-skeleton--text.d-skeleton--multiline) {
+ --d-skeleton-item-height: 1em;
+
+ // The leading is deliberately not derived from the item height a caller may
+ // have supplied. That value can be taller than the line box, or `auto`, or a
+ // variable resolving to nothing — each of which either bottoms the
+ // subtraction out or makes it uncomputable, closing the gap entirely.
+ --d-skeleton-gap: max(0.25em, calc(1lh - 1em));
+}
+
+:where(.d-skeleton--rect) {
+ --d-skeleton-item-height: 2.5em;
+}
+
+:where(.d-skeleton--circle) {
+ --d-skeleton-item-height: 2em;
+ --d-skeleton-item-width: 2em;
+ --d-skeleton-radius: 50%;
+}
+
+// Structure keeps its normal specificity: only the tokens above are meant to be
+// overridden.
+.d-skeleton {
+ display: var(--d-skeleton-display);
+ flex-direction: column;
+ gap: var(--d-skeleton-gap);
+
+ &__item {
+ width: var(--d-skeleton-item-width);
+ height: var(--d-skeleton-item-height, 1em);
+
+ // The reserved height is the point, so don't let a constrained parent
+ // compress it.
+ flex-shrink: 0;
+ background: var(--d-skeleton-fill, var(--primary-very-low));
+ border-radius: var(--d-skeleton-radius, var(--d-border-radius, 0.25em));
+
+ @media (prefers-reduced-motion: no-preference) {
+ &.placeholder-animation {
+ background-image: linear-gradient(
+ to right,
+ var(--d-skeleton-fill, var(--primary-very-low)),
+ var(--d-skeleton-shimmer, var(--primary-low)) 50%,
+ var(--d-skeleton-fill, var(--primary-very-low))
+ );
+
+ // fixed band matching the shared keyframe's 2100px travel, so the
+ // shimmer loops seamlessly at a width-independent speed
+ background-size: 2100px 100%;
+ animation-duration: var(--d-skeleton-duration, 2.5s);
+ }
+ }
+ }
+}
diff --git a/frontend/discourse/app/ui-kit/d-skeleton.gts b/frontend/discourse/app/ui-kit/d-skeleton.gts
new file mode 100644
index 00000000000..e1cb99d63e7
--- /dev/null
+++ b/frontend/discourse/app/ui-kit/d-skeleton.gts
@@ -0,0 +1,220 @@
+import Component from "@glimmer/component";
+import { concat } from "@ember/helper";
+import { type TrustedHTML, trustHTML } from "@ember/template";
+import { eq } from "discourse/truth-helpers";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+
+const DEFAULT_COUNT = 1;
+
+/** A placeholder longer than this reserves space no real content will occupy. */
+const MAX_COUNT = 50;
+
+const VARIANTS = ["text", "rect", "circle"] as const;
+
+type SkeletonVariant = (typeof VARIANTS)[number];
+
+/**
+ * The dimension custom properties, each paired with the property the stylesheet
+ * feeds it to. A value is emitted only if it is valid for that property, which
+ * is what stops one from carrying further declarations into the style attribute.
+ */
+const DIMENSIONS = {
+ "--d-skeleton-item-width": "width",
+ "--d-skeleton-item-height": "height",
+ "--d-skeleton-radius": "border-radius",
+} as const;
+
+type DimensionValues = Partial<Record<keyof typeof DIMENSIONS, string>>;
+
+/**
+ * Valid for any property, so `CSS.supports` waves them through, but a custom
+ * property holding one is guaranteed-invalid rather than the keyword's usual
+ * meaning. Rejecting them here keeps the variant's own sizing instead.
+ */
+const CSS_WIDE_KEYWORDS = new Set([
+ "initial",
+ "inherit",
+ "unset",
+ "revert",
+ "revert-layer",
+]);
+
+function buildDimensionStyle(values: DimensionValues): TrustedHTML | undefined {
+ const declarations = Object.entries(values).flatMap(([property, value]) => {
+ const target = DIMENSIONS[property as keyof typeof DIMENSIONS];
+ return value != null &&
+ !CSS_WIDE_KEYWORDS.has(value.trim().toLowerCase()) &&
+ CSS.supports(target, value)
+ ? [`${property}:${value}`]
+ : [];
+ });
+
+ return declarations.length ? trustHTML(declarations.join(";")) : undefined;
+}
+
+interface DSkeletonSignature {
+ Args: {
+ count?: number;
+ variant?: SkeletonVariant;
+ animated?: boolean;
+ width?: string;
+ height?: string;
+ radius?: string;
+ size?: string;
+ lastLineWidth?: string;
+ };
+ Element: HTMLDivElement;
+}
+
+/**
+ * Reusable loading placeholder. Renders one or more shimmer items shaped by
+ * `@variant` (a text line, a rectangle, or a circle) and sized to reserve the
+ * space the real content will occupy, so revealing the content doesn't shift
+ * the surrounding layout.
+ *
+ * A lone `text` bar takes the inherited line box (`1lh`), matching a real
+ * one-line element; stacked text lines drop to ink height (`1em`) spaced one
+ * line-height apart, so a paragraph reads as separate lines. Either way the
+ * sizing follows the surrounding typography, so a skeleton in a given context
+ * (e.g. a heading) needs no hard-coded height or gap. `@lastLineWidth` narrows
+ * a multi-line block's final line the way a real paragraph's does.
+ *
+ * The shimmer comes from the shared `.placeholder-animation` class, which only
+ * paints under `prefers-reduced-motion: no-preference`. The items therefore
+ * keep a static fill underneath (from the scss) so the placeholder still reads
+ * when the animation is suppressed (reduced motion, or `@animated={{false}}`).
+ *
+ * The placeholder is decorative and the wrapper is `aria-hidden`, so assistive
+ * technology sees nothing here. Announcing the load is the caller's half of the
+ * contract: mark the region whose content is being replaced `aria-busy` while it
+ * resolves. Passing `role="status"` to this component announces nothing on its
+ * own, because the wrapper stays hidden; override `aria-hidden` through
+ * `...attributes` if the placeholder itself has to be exposed.
+ *
+ * Adjust it through the custom properties. The theming ones —
+ * `--d-skeleton-fill`, `--d-skeleton-shimmer`, `--d-skeleton-duration` and
+ * `--d-skeleton-radius` — can be set by a class on the placeholder or scoped from
+ * any ancestor, so a container can retint everything inside it. The `circle`
+ * variant is the one exception: its radius is what makes it a circle, so it is
+ * not themeable from outside. The layout ones,
+ * `--d-skeleton-display` and `--d-skeleton-gap`, only take effect on the
+ * placeholder itself, so a container cannot relay out a nested one by accident.
+ * Keep `--d-skeleton-display` a flex value, since the line rhythm comes from
+ * `gap`.
+ *
+ * The consumer's `...attributes` are forwarded to the wrapper, but `style` is the
+ * component's own: it carries the dimensions, so anything passed there is
+ * discarded. Use a class.
+ */
+export default class DSkeleton extends Component<DSkeletonSignature> {
+ /**
+ * The variant, defaulting to a text line. Stamped on both the wrapper and
+ * each item so the scss can key variant-specific defaults off it. An
+ * unrecognised value falls back rather than stamping a modifier no rule
+ * matches, which would leave an item with none of its variant's sizing.
+ */
+ get variant(): SkeletonVariant {
+ const requested = this.args.variant as SkeletonVariant;
+ return VARIANTS.includes(requested) ? requested : "text";
+ }
+
+ /**
+ * Whether more than one item is stacked, so the scss can treat a stack
+ * differently from a lone bar (e.g. stacked text lines drop from a full line
+ * box to ink height so they read as separate lines).
+ */
+ get multiline(): boolean {
+ return this.#itemCount > 1;
+ }
+
+ /**
+ * How many items to render. Coerced and clamped because the count reaches the
+ * component from callers that only assert its type: a non-finite value would
+ * otherwise render nothing, and an unbounded one would allocate until the tab
+ * gave up.
+ */
+ get #itemCount(): number {
+ const requested = Number(this.args.count ?? DEFAULT_COUNT);
+
+ if (!Number.isFinite(requested)) {
+ return DEFAULT_COUNT;
+ }
+
+ return Math.min(Math.max(1, Math.floor(requested)), MAX_COUNT);
+ }
+
+ /** The indices of the placeholder items to render, one per `@count`. */
+ get items(): number[] {
+ return Array.from({ length: this.#itemCount }, (_, index) => index);
+ }
+
+ /**
+ * The shared class applied to every item: the base item class, its variant
+ * modifier, and the shimmer class when animated.
+ */
+ get itemClass(): string {
+ const classes = ["d-skeleton__item", `d-skeleton__item--${this.variant}`];
+
+ if (this.args.animated ?? true) {
+ classes.push("placeholder-animation");
+ }
+
+ return classes.join(" ");
+ }
+
+ /**
+ * The dimensions shared by every item, emitted as inline custom properties
+ * (not `width`/`height`/`border-radius` themselves) so the stylesheet owns the
+ * property mapping. They sit on the wrapper because they are uniform, and the
+ * items inherit them. `@size` is a shorthand that makes a square; explicit
+ * `@width`/`@height` win over it. `undefined` when nothing is set, so the
+ * variant's scss tokens apply.
+ */
+ get dimensionStyle(): TrustedHTML | undefined {
+ const { width, height, radius, size } = this.args;
+
+ return buildDimensionStyle({
+ "--d-skeleton-item-width": width ?? size,
+ "--d-skeleton-item-height": height ?? size,
+ "--d-skeleton-radius": radius,
+ });
+ }
+
+ /** Overrides the width of the final line so it tapers like a real paragraph's. */
+ get lastLineStyle(): TrustedHTML | undefined {
+ return buildDimensionStyle({
+ "--d-skeleton-item-width": this.args.lastLineWidth,
+ });
+ }
+
+ /**
+ * The item `@lastLineWidth` applies to, or `-1` when it applies to none. A
+ * lone bar is left at full width: it stands in for a whole element, not for
+ * the last line of a paragraph.
+ */
+ get lastLineIndex(): number {
+ return this.multiline && this.args.lastLineWidth != null
+ ? this.#itemCount - 1
+ : -1;
+ }
+
+ <template>
+ <div
+ class={{dConcatClass
+ "d-skeleton"
+ (concat "d-skeleton--" this.variant)
+ (if this.multiline "d-skeleton--multiline")
+ }}
+ aria-hidden="true"
+ ...attributes
+ style={{this.dimensionStyle}}
+ >
+ {{#each this.items key="@index" as |index|}}
+ <div
+ class={{this.itemClass}}
+ style={{if (eq index this.lastLineIndex) this.lastLineStyle}}
+ ></div>
+ {{/each}}
+ </div>
+ </template>
+}
diff --git a/frontend/discourse/tests/integration/ui-kit/d-skeleton-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-skeleton-test.gjs
new file mode 100644
index 00000000000..5c23bbcd82d
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-skeleton-test.gjs
@@ -0,0 +1,482 @@
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import DSkeleton from "discourse/ui-kit/d-skeleton";
+
+let consumerSheet;
+
+/**
+ * Adds a rule the way a consumer's stylesheet would, at the *top* of the head so
+ * it loses on source order. It can then only take effect by outranking the
+ * component's defaults, which is what declaring them at zero specificity buys.
+ */
+function consumerRule(css) {
+ consumerSheet = document.createElement("style");
+ consumerSheet.textContent = css;
+ document.head.insertBefore(consumerSheet, document.head.firstChild);
+}
+
+/**
+ * Whether the wrapper has a real gap. An invalidated gap computes to `normal`,
+ * so this distinguishes it from both zero and a length.
+ */
+function assertPositiveRowGap(assert, message) {
+ const gap = getComputedStyle(document.querySelector(".d-skeleton")).rowGap;
+ assert.strictEqual(parseFloat(gap) > 0, true, `${message} (got ${gap})`);
+}
+
+module("Integration | ui-kit | DSkeleton", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.afterEach(function () {
+ consumerSheet?.remove();
+ consumerSheet = null;
+ });
+
+ test("defaults to a single animated text item", async function (assert) {
+ await render(<template><DSkeleton /></template>);
+
+ assert.dom(".d-skeleton").exists();
+ assert.dom(".d-skeleton__item").exists({ count: 1 });
+ assert.dom(".d-skeleton__item").hasClass("d-skeleton__item--text");
+ assert
+ .dom(".d-skeleton__item")
+ .hasClass("placeholder-animation", "the shimmer class is applied");
+ assert
+ .dom(".d-skeleton")
+ .hasAttribute("aria-hidden", "true", "it is hidden from assistive tech");
+ });
+
+ test("@variant selects the shape and @count repeats the item", async function (assert) {
+ await render(
+ <template><DSkeleton @variant="circle" @count={{3}} /></template>
+ );
+
+ assert.dom(".d-skeleton__item").exists({ count: 3 });
+ assert.dom(".d-skeleton__item--circle").exists({ count: 3 });
+ });
+
+ test("@animated={{false}} drops the shimmer but keeps a visible fill", async function (assert) {
+ await render(<template><DSkeleton @animated={{false}} /></template>);
+
+ // The static fill (a real background) must remain so the placeholder still
+ // reads with the shimmer suppressed (also the reduced-motion case).
+ assert
+ .dom(".d-skeleton__item")
+ .doesNotHaveClass(
+ "placeholder-animation",
+ "the shimmer class is omitted"
+ );
+ assert.dom(".d-skeleton__item").hasClass("d-skeleton__item--text");
+ assert
+ .dom(".d-skeleton__item")
+ .doesNotHaveStyle(
+ { backgroundColor: "rgba(0, 0, 0, 0)" },
+ "a fill still paints without the shimmer"
+ );
+ });
+
+ test("dimensions apply via inline custom properties", async function (assert) {
+ await render(
+ <template>
+ <DSkeleton @variant="rect" @width="50%" @height="4em" @radius="1em" />
+ </template>
+ );
+
+ // Match the inline style attribute, not computed style, which would
+ // resolve relative units (%/em) to pixels. They sit on the wrapper and
+ // reach the items by inheritance.
+ assert
+ .dom(".d-skeleton")
+ .hasAttribute("style", /--d-skeleton-item-width:\s*50%/);
+ assert
+ .dom(".d-skeleton")
+ .hasAttribute("style", /--d-skeleton-item-height:\s*4em/);
+ assert
+ .dom(".d-skeleton")
+ .hasAttribute("style", /--d-skeleton-radius:\s*1em/);
+ });
+
+ test("@count coerces to a sane number of items", async function (assert) {
+ // `@count` reaches the component from callers that only assert its type, so
+ // every one of these is a value it can actually be handed at runtime. A
+ // non-finite count carries no intent and falls back to the default; a
+ // finite one is clamped.
+ const cases = [
+ { count: NaN, expected: 1, label: "NaN" },
+ { count: "abc", expected: 1, label: "a non-numeric string" },
+ { count: "3", expected: 3, label: "a numeric string" },
+ { count: Infinity, expected: 1, label: "Infinity" },
+ { count: 1e9, expected: 50, label: "an oversized but finite count" },
+ { count: 0, expected: 1, label: "zero" },
+ { count: -3, expected: 1, label: "a negative count" },
+ { count: 2.7, expected: 2, label: "a fractional count" },
+ ];
+
+ for (const { count, expected, label } of cases) {
+ await render(<template><DSkeleton @count={{count}} /></template>);
+ assert
+ .dom(".d-skeleton__item")
+ .exists({ count: expected }, `${label} renders ${expected}`);
+ }
+ });
+
+ test("an unknown @variant falls back to text", async function (assert) {
+ await render(<template><DSkeleton @variant="blob" /></template>);
+
+ assert.dom(".d-skeleton").hasClass("d-skeleton--text");
+ assert.dom(".d-skeleton__item").hasClass("d-skeleton__item--text");
+ });
+
+ test("a dimension value cannot introduce extra declarations", async function (assert) {
+ await render(
+ <template><DSkeleton @width="1px;position:fixed;inset:0" /></template>
+ );
+
+ assert
+ .dom(".d-skeleton")
+ .doesNotHaveStyle(
+ { position: "fixed" },
+ "the wrapper does not take an injected declaration"
+ );
+ assert
+ .dom(".d-skeleton__item")
+ .doesNotHaveStyle(
+ { position: "fixed" },
+ "the item does not take an injected declaration"
+ );
+ });
+
+ test("a computed dimension value survives validation", async function (assert) {
+ await render(
+ <template>
+ <DSkeleton
+ @variant="rect"
+ @width="calc(100% - 2ch)"
+ @height="var(--d-input-height)"
+ />
+ </template>
+ );
+
+ assert
+ .dom(".d-skeleton")
+ .hasAttribute(
+ "style",
+ /--d-skeleton-item-width:\s*calc\(100% - 2ch\)/,
+ "calc() is not rejected"
+ );
+ assert
+ .dom(".d-skeleton")
+ .hasAttribute(
+ "style",
+ /--d-skeleton-item-height:\s*var\(--d-input-height\)/,
+ "var() is not rejected"
+ );
+ });
+
+ test("@lastLineWidth tapers only the final line of a multi-line block", async function (assert) {
+ await render(
+ <template>
+ <DSkeleton
+ @variant="text"
+ @count={{3}}
+ @width="100%"
+ @lastLineWidth="55%"
+ />
+ </template>
+ );
+
+ const items = [...document.querySelectorAll(".d-skeleton__item")];
+ assert.strictEqual(items.length, 3, "renders one item per line");
+
+ // The shared width sits on the wrapper; only the tapered final line carries
+ // an override of its own.
+ assert
+ .dom(".d-skeleton")
+ .hasAttribute("style", /--d-skeleton-item-width:\s*100%/);
+ assert.dom(items[0]).doesNotHaveAttribute("style");
+ assert.dom(items[1]).doesNotHaveAttribute("style");
+ assert
+ .dom(items[2])
+ .hasAttribute(
+ "style",
+ /--d-skeleton-item-width:\s*55%/,
+ "the last line is shorter"
+ );
+ });
+
+ test("@lastLineWidth is ignored for a single item", async function (assert) {
+ await render(
+ <template>
+ <DSkeleton @variant="text" @width="100%" @lastLineWidth="55%" />
+ </template>
+ );
+
+ assert
+ .dom(".d-skeleton")
+ .hasAttribute(
+ "style",
+ /--d-skeleton-item-width:\s*100%/,
+ "a lone line keeps the full width"
+ );
+ assert
+ .dom(".d-skeleton__item")
+ .doesNotHaveAttribute("style", "the lone line takes no taper override");
+ });
+
+ test("stamps the variant on the wrapper for variant-specific styling", async function (assert) {
+ await render(<template><DSkeleton @variant="text" /></template>);
+ assert
+ .dom(".d-skeleton")
+ .hasClass(
+ "d-skeleton--text",
+ "the wrapper carries the variant so the scss can set its line rhythm"
+ );
+ });
+
+ test("marks a stacked skeleton multiline, a lone one not", async function (assert) {
+ await render(<template><DSkeleton @count={{3}} /></template>);
+ assert
+ .dom(".d-skeleton")
+ .hasClass(
+ "d-skeleton--multiline",
+ "stacked items are multiline so text lines drop to ink height"
+ );
+ assert
+ .dom(".d-skeleton")
+ .doesNotHaveStyle({ rowGap: "0px" }, "stacked lines are spaced apart");
+ const stackedHeight = getComputedStyle(
+ document.querySelector(".d-skeleton__item")
+ ).height;
+
+ await render(<template><DSkeleton /></template>);
+ assert
+ .dom(".d-skeleton")
+ .doesNotHaveClass(
+ "d-skeleton--multiline",
+ "a lone bar matches its element's full line box"
+ );
+ assert.notStrictEqual(
+ getComputedStyle(document.querySelector(".d-skeleton__item")).height,
+ stackedHeight,
+ "a lone bar takes the line box, a stacked one only its ink height"
+ );
+ });
+
+ test("a tall @height does not collapse the derived gap", async function (assert) {
+ // The gap subtracts the item height from the line box, so a height taller
+ // than the line box would bottom out and leave the bars touching.
+ await render(<template><DSkeleton @count={{3}} @height="3em" /></template>);
+
+ // Not `!== "0px"`: an invalidated gap computes to `normal`, which would pass
+ // that assertion while still rendering no separation at all.
+ assertPositiveRowGap(assert, "the gap is a real length");
+ });
+
+ test("a CSS-wide keyword is not accepted as a dimension", async function (assert) {
+ // `CSS.supports` accepts `initial`/`inherit`/`unset` for any property, but
+ // stored in a custom property they are guaranteed-invalid, which would take
+ // the derived gap down with them.
+ await render(
+ <template><DSkeleton @count={{3}} @height="initial" /></template>
+ );
+
+ assert
+ .dom(".d-skeleton")
+ .doesNotHaveAttribute("style", "the keyword is rejected outright");
+ assertPositiveRowGap(assert, "the gap survives");
+ });
+
+ test("an unresolved var() dimension does not collapse the gap", async function (assert) {
+ // Unlike a keyword this has to be accepted — a var() reference is exactly
+ // what callers pass — so the gap carries its own fallback instead.
+ await render(
+ <template>
+ <DSkeleton @count={{3}} @height="var(--not-a-real-token)" />
+ </template>
+ );
+
+ assert
+ .dom(".d-skeleton")
+ .hasAttribute(
+ "style",
+ /--d-skeleton-item-height/,
+ "the value is accepted"
+ );
+ assertPositiveRowGap(assert, "the gap survives");
+ });
+
+ test('@height="auto" does not close the gap between lines', async function (assert) {
+ // `auto` is valid for `height`, so validation cannot reject it, and it is
+ // uncomputable in a subtraction. The line rhythm is therefore independent of
+ // whatever height the caller asks for.
+ await render(
+ <template><DSkeleton @count={{3}} @height="auto" /></template>
+ );
+
+ assertPositiveRowGap(assert, "the gap does not depend on the caller");
+ });
+
+ test("an ancestor cannot square off a circle", async function (assert) {
+ // Radius is themeable from an ancestor, with the circle a deliberate
+ // exception: its 50% is what makes it a circle, not a style choice.
+ consumerRule(".squared-region { --d-skeleton-radius: 2px; }");
+ await render(
+ <template>
+ <div class="squared-region"><DSkeleton @variant="circle" /></div>
+ </template>
+ );
+
+ assert.dom(".d-skeleton__item").hasStyle({ borderRadius: "50%" });
+ });
+
+ test("@size is a square shorthand", async function (assert) {
+ await render(
+ <template><DSkeleton @variant="circle" @size="3em" /></template>
+ );
+
+ assert
+ .dom(".d-skeleton")
+ .hasAttribute("style", /--d-skeleton-item-width:\s*3em/);
+ assert
+ .dom(".d-skeleton")
+ .hasAttribute("style", /--d-skeleton-item-height:\s*3em/);
+ });
+
+ test("@width wins over the @size shorthand", async function (assert) {
+ await render(
+ <template>
+ <DSkeleton @variant="circle" @size="3em" @width="8em" />
+ </template>
+ );
+
+ assert
+ .dom(".d-skeleton")
+ .hasAttribute("style", /--d-skeleton-item-width:\s*8em/);
+ assert
+ .dom(".d-skeleton")
+ .hasAttribute(
+ "style",
+ /--d-skeleton-item-height:\s*3em/,
+ "@size still supplies the height"
+ );
+ });
+
+ test("@radius overrides the circle default", async function (assert) {
+ await render(
+ <template>
+ <DSkeleton @variant="circle" @size="3em" @radius="4px" />
+ </template>
+ );
+
+ assert
+ .dom(".d-skeleton__item")
+ .hasStyle(
+ { borderRadius: "4px" },
+ "the inline radius beats the variant's 50%"
+ );
+ });
+
+ test("a variant's tokens beat the base defaults", async function (assert) {
+ // The base block declares a width of `auto` and the circle one overrides it,
+ // both at zero specificity, so this rests on source order and would break
+ // silently if the blocks were reordered.
+ await render(<template><DSkeleton @variant="circle" /></template>);
+
+ const { width, height } = getComputedStyle(
+ document.querySelector(".d-skeleton__item")
+ );
+ assert.strictEqual(
+ width,
+ height,
+ "the circle sizes both axes rather than stretching to the base `auto`"
+ );
+ assert.dom(".d-skeleton__item").hasStyle({ borderRadius: "50%" });
+ });
+
+ test("--d-skeleton-duration retimes the shimmer", async function (assert) {
+ consumerRule(".slow-skeleton { --d-skeleton-duration: 9s; }");
+ await render(<template><DSkeleton class="slow-skeleton" /></template>);
+
+ assert.dom(".d-skeleton__item").hasStyle({ animationDuration: "9s" });
+ });
+
+ test("--d-skeleton-display puts the placeholder in inline flow", async function (assert) {
+ await render(<template><DSkeleton /></template>);
+ assert
+ .dom(".d-skeleton")
+ .hasStyle({ display: "flex" }, "it is block-level by default");
+
+ consumerRule(".inline-skeleton { --d-skeleton-display: inline-flex; }");
+ await render(<template><DSkeleton class="inline-skeleton" /></template>);
+
+ assert.dom(".d-skeleton").hasStyle({ display: "inline-flex" });
+ });
+
+ test("a theming token can be scoped from an ancestor", async function (assert) {
+ consumerRule(".themed-region { --d-skeleton-duration: 9s; }");
+ await render(
+ <template>
+ <div class="themed-region"><DSkeleton /></div>
+ </template>
+ );
+
+ assert.dom(".d-skeleton__item").hasStyle({ animationDuration: "9s" });
+ });
+
+ test("layout tokens do not leak in from an ancestor", async function (assert) {
+ // The counterpart to the test above: a container retinting its skeletons is
+ // meaningful, a container silently relaying out every nested one is not.
+ consumerRule(
+ ".layout-region { --d-skeleton-display: inline-flex; --d-skeleton-item-width: 5em; }"
+ );
+ await render(
+ <template>
+ <div class="layout-region"><DSkeleton /></div>
+ </template>
+ );
+
+ assert
+ .dom(".d-skeleton")
+ .hasStyle({ display: "flex" }, "display stays the component's own");
+ assert
+ .dom(".d-skeleton__item")
+ .doesNotHaveStyle({ width: "80px" }, "the item keeps its own sizing");
+ });
+
+ test("a consumer style is discarded, so the dimensions survive", async function (assert) {
+ // `style` carries the dimensions, so the component keeps it by declaring it
+ // after ...attributes. Everything a caller legitimately needs is a token.
+ await render(
+ <template><DSkeleton @width="8ch" style="margin-top: 1em" /></template>
+ );
+
+ assert
+ .dom(".d-skeleton")
+ .hasAttribute("style", /--d-skeleton-item-width:\s*8ch/);
+ assert.dom(".d-skeleton").doesNotHaveStyle({ marginTop: "16px" });
+
+ await render(<template><DSkeleton style="margin-top: 1em" /></template>);
+ assert
+ .dom(".d-skeleton")
+ .doesNotHaveStyle(
+ { marginTop: "16px" },
+ "also when there are no dimensions to set"
+ );
+ });
+
+ test("aria-hidden can be overridden through ...attributes", async function (assert) {
+ await render(<template><DSkeleton aria-hidden="false" /></template>);
+
+ assert.dom(".d-skeleton").hasAttribute("aria-hidden", "false");
+ });
+
+ test("forwards attributes to the root element", async function (assert) {
+ await render(
+ <template><DSkeleton class="extra" data-test-skeleton="yes" /></template>
+ );
+
+ assert.dom(".d-skeleton").hasClass("extra");
+ assert.dom(".d-skeleton").hasAttribute("data-test-skeleton", "yes");
+ });
+});