Skip to content

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

DEV: Fill ui-kit gaps that force consumers to hand-roll (#43422)

Sérgio Saquetime927501a4296
diff --git a/app/assets/stylesheets/common/components/d-page-header.scss b/app/assets/stylesheets/common/components/d-page-header.scss
index 7ef3ce61d4d..9d899ab2360 100644
--- a/app/assets/stylesheets/common/components/d-page-header.scss
+++ b/app/assets/stylesheets/common/components/d-page-header.scss
@@ -9,12 +9,17 @@ $mobile-breakpoint: 700px;
align-items: stretch;
margin-bottom: var(--space-2);
+ // Keyed on the title classes as well as the tags: a subheader nested under
+ // another heading picks its own level, and its styling must not depend on
+ // which level it picked.
h1,
- h2 {
+ h2,
+ .d-page-header__title,
+ .d-page-subheader__title {
margin: 0;
}
- h2 {
+ .d-page-subheader__title {
font-size: var(--font-up-2);
}
diff --git a/app/assets/stylesheets/common/components/empty-states.scss b/app/assets/stylesheets/common/components/empty-states.scss
index c89ad783137..733b9c19e63 100644
--- a/app/assets/stylesheets/common/components/empty-states.scss
+++ b/app/assets/stylesheets/common/components/empty-states.scss
@@ -49,6 +49,17 @@
@include viewport.until(sm) {
margin-top: 8vh;
}
+
+ // Sized as a glyph, overriding the illustration width above.
+ &.--icon svg {
+ width: 3rem;
+ height: 3rem;
+ color: var(--primary-low-mid);
+
+ @include viewport.until(sm) {
+ width: 3rem;
+ }
+ }
}
&__cta {
diff --git a/frontend/discourse/app/lib/avatar-utils.js b/frontend/discourse/app/lib/avatar-utils.js
index 4c830da9dcb..930d8da5d3f 100644
--- a/frontend/discourse/app/lib/avatar-utils.js
+++ b/frontend/discourse/app/lib/avatar-utils.js
@@ -86,7 +86,12 @@ export function avatarImg(options, customGetURL) {
loading = ` loading='${escaped}'`;
}
- return `<img alt='' width='${size}' height='${size}' src='${url}' class='${classes}'${title}${loading}>`;
+ // Empty by default: an avatar almost always sits beside the name it belongs
+ // to, where alt text would only repeat it. Pass `alt` where the image is the
+ // sole identification of the person.
+ const alt = escape(options.alt || "");
+
+ return `<img alt='${alt}' width='${size}' height='${size}' src='${url}' class='${classes}'${title}${loading}>`;
}
export function tinyAvatar(avatarTemplate, options) {
diff --git a/frontend/discourse/app/ui-kit/d-button.gts b/frontend/discourse/app/ui-kit/d-button.gts
index ce2836cdd3c..eac8d22628a 100644
--- a/frontend/discourse/app/ui-kit/d-button.gts
+++ b/frontend/discourse/app/ui-kit/d-button.gts
@@ -63,6 +63,11 @@ export interface DButtonSignature<P = undefined> {
// Actions / events
/** Passed to `@action` as its first argument. */
actionParam?: P;
+ /**
+ * Runs `@action` inside the click instead of deferring it, so the handler
+ * keeps the click's transient user activation.
+ */
+ immediate?: boolean;
onKeyDown?: (event: KeyboardEvent) => void;
// Navigation
@@ -212,6 +217,8 @@ export default class DButton<P = undefined> extends Component<
/**
* Binds `@action` to this click: `@actionParam`, plus the event when
* `@forwardEvent` is set. Returns nothing when `@action` holds no handler.
+ * A `{ value }` handler is called as a method when the closure runs, so it
+ * keeps its receiver and a `.value` replaced before a deferred run wins.
*/
#bindAction(event: Event): (() => void) | undefined {
const args = this.args;
@@ -240,19 +247,19 @@ export default class DButton<P = undefined> extends Component<
_triggerAction(event: Event) {
const { action: actionVal, route, routeModels } = this.args;
- const isIOS = this.capabilities?.isIOS;
if (actionVal || route) {
if (actionVal) {
const invoke = this.#bindAction(event);
if (invoke) {
- if (isIOS) {
- // Don't optimise INP in iOS
- // it results in focus events not being triggered
+ // `next()` defers the handler so the browser can paint first (INP).
+ // Two cases must run inside the dispatch instead: iOS, where the
+ // deferral stops focus events firing, and handlers needing the
+ // click's transient user activation, which does not survive it.
+ if (this.args.immediate || this.capabilities?.isIOS) {
invoke();
} else {
- // Using `next()` to optimise INP
next(invoke);
}
}
diff --git a/frontend/discourse/app/ui-kit/d-combo-button.gts b/frontend/discourse/app/ui-kit/d-combo-button.gts
index 7346b3539d2..9bb8cc07ed8 100644
--- a/frontend/discourse/app/ui-kit/d-combo-button.gts
+++ b/frontend/discourse/app/ui-kit/d-combo-button.gts
@@ -4,7 +4,10 @@ import { hash } from "@ember/helper";
import { getOwner } from "@ember/owner";
import type { WithBoundArgs } from "@glint/template";
import curryComponent from "ember-curry-component";
-import DMenu, { DMenuSignature } from "discourse/float-kit/components/d-menu";
+import DMenu, {
+ DMenuComponentArgs,
+ DMenuSignature,
+} from "discourse/float-kit/components/d-menu";
import DButton, { DButtonSignature } from "discourse/ui-kit/d-button";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
@@ -35,7 +38,8 @@ interface MenuSignature {
/** Curried in by the group; the menu renders only when it is true. */
hasMenu?: boolean;
};
- Blocks: { default: [] };
+ /** The menu's own API, forwarded so content can close the menu it sits in. */
+ Blocks: { default: [DMenuComponentArgs] };
}
class Button extends Component<ButtonSignature> {
@@ -76,8 +80,8 @@ class Menu extends Component<MenuSignature> {
@icon={{or @icon "chevron-down"}}
@placement={{or @placement "bottom-end"}}
>
- <:content>
- {{yield}}
+ <:content as |menu|>
+ {{yield menu}}
</:content>
</CurriedComponent>
{{/let}}
@@ -109,12 +113,19 @@ interface DComboButtonSignature {
* Pass `@hasMenu` rather than adding `--has-menu` by hand: the group publishes
* that class itself and uses the same flag to decide whether the menu renders.
*
+ * `combo.Menu` yields the menu's own API, so an item can close the menu it sits
+ * in without the call site registering the instance separately.
+ *
* @example
* ```gjs
* <DComboButton @hasMenu={{this.hasDrafts}} @btnTypeClass="btn-default" as |combo|>
* <combo.Button @label="topic.create" @action={{this.createTopic}} />
- * <combo.Menu @identifier="drafts">
- * <DDropdownMenu as |dropdown|>…</DDropdownMenu>
+ * <combo.Menu @identifier="drafts" as |menu|>
+ * <DDropdownMenu as |dropdown|>
+ * <dropdown.item>
+ * <DButton @action={{fn this.openDraft menu.close}} @label="drafts.open" />
+ * </dropdown.item>
+ * </DDropdownMenu>
* </combo.Menu>
* </DComboButton>
* ```
diff --git a/frontend/discourse/app/ui-kit/d-empty-state.gjs b/frontend/discourse/app/ui-kit/d-empty-state.gjs
index d4fa6030115..df66557954f 100644
--- a/frontend/discourse/app/ui-kit/d-empty-state.gjs
+++ b/frontend/discourse/app/ui-kit/d-empty-state.gjs
@@ -6,13 +6,18 @@ const DEmptyState = <template>
<div
class="empty-state__container
{{if @identifier (concat '--' @identifier)}}
- {{if @svgContent '--with-image' '--text-only'}}"
+ {{if (or @svgContent @icon) '--with-image' '--text-only'}}"
+ ...attributes
>
<div class="empty-state">
{{#if @svgContent}}
<div class="empty-state__image">
{{@svgContent}}
</div>
+ {{else if @icon}}
+ <div class="empty-state__image --icon">
+ {{dIcon @icon}}
+ </div>
{{/if}}
{{#if @title}}
diff --git a/frontend/discourse/app/ui-kit/d-page-subheader.gjs b/frontend/discourse/app/ui-kit/d-page-subheader.gjs
index f1e10068642..dea2a954f2c 100644
--- a/frontend/discourse/app/ui-kit/d-page-subheader.gjs
+++ b/frontend/discourse/app/ui-kit/d-page-subheader.gjs
@@ -1,4 +1,5 @@
import Component from "@glimmer/component";
+import { assert } from "@ember/debug";
import { hash } from "@ember/helper";
import { service } from "@ember/service";
import { trustHTML } from "@ember/template";
@@ -13,16 +14,34 @@ import {
WrappedActionListItem,
WrappedButton,
} from "discourse/ui-kit/d-page-action-button";
+import dElement from "discourse/ui-kit/helpers/d-element";
import { i18n } from "discourse-i18n";
export default class DPageSubheader extends Component {
@service site;
+ /**
+ * The element the title renders as. A subheader nested under another heading
+ * needs to continue that heading structure rather than restart it at `h2`.
+ *
+ * @returns {object} A component wrapping the heading tag.
+ */
+ get titleTag() {
+ const level = this.args.titleHeadingLevel ?? 2;
+
+ assert(
+ `DPageSubheader @titleHeadingLevel must be 1-6, got ${level}`,
+ Number.isInteger(level) && level >= 1 && level <= 6
+ );
+
+ return dElement(`h${level}`);
+ }
+
<template>
<div class="d-page-subheader">
<div class="d-page-subheader__title-row">
{{#if @titleLabel}}
- <h2 class="d-page-subheader__title">
+ <this.titleTag class="d-page-subheader__title">
{{#if @titleUrl}}
<a class="d-page-subheader__title-link" href={{@titleUrl}}>
{{@titleLabel}}
@@ -30,7 +49,7 @@ export default class DPageSubheader extends Component {
{{else}}
{{@titleLabel}}
{{/if}}
- </h2>
+ </this.titleTag>
{{/if}}
{{#if (has-block "actions")}}
<div class="d-page-subheader__actions">
diff --git a/frontend/discourse/app/ui-kit/d-resize-handles.gts b/frontend/discourse/app/ui-kit/d-resize-handles.gts
index b96a6af54d4..2a97fda599a 100644
--- a/frontend/discourse/app/ui-kit/d-resize-handles.gts
+++ b/frontend/discourse/app/ui-kit/d-resize-handles.gts
@@ -204,12 +204,16 @@ interface DResizeHandlesSignature<
dragInfo: DResizeHandleDragInfo<NoInfer<Payload>, Session>
) => void;
- /** A class toggled on the active handle while it is being dragged. */
+ /**
+ * A class toggled on the active handle while it is being dragged. Under a
+ * `@threshold` it waits for that distance, so a click on a handle never
+ * looks like a resize.
+ */
draggingClass?: string;
/**
- * Pixels of travel before `@onResize` starts firing, to absorb the jitter of
- * a click that was never meant to be a drag.
+ * Pixels of travel before `@onResize` starts firing and `@draggingClass`
+ * goes on, to absorb the jitter of a click that was never meant to be a drag.
*/
threshold?: number;
diff --git a/frontend/discourse/app/ui-kit/helpers/d-avatar.js b/frontend/discourse/app/ui-kit/helpers/d-avatar.js
index b0faa1d21a9..1d2259e9a84 100644
--- a/frontend/discourse/app/ui-kit/helpers/d-avatar.js
+++ b/frontend/discourse/app/ui-kit/helpers/d-avatar.js
@@ -73,6 +73,9 @@ export function renderAvatar(user, options) {
extraClasses: get(user, "extras") || options.extraClasses,
loading: options.loading,
title: options.hideTitle ? null : title || displayName,
+ // `alt: true` names the person rather than making the caller repeat the
+ // display-name logic above; a string sets it verbatim.
+ alt: options.alt === true ? displayName : options.alt,
avatarTemplate,
});
} else {
diff --git a/frontend/discourse/app/ui-kit/helpers/d-element.gts b/frontend/discourse/app/ui-kit/helpers/d-element.gts
index f06608eba8a..fda9ba256d0 100644
--- a/frontend/discourse/app/ui-kit/helpers/d-element.gts
+++ b/frontend/discourse/app/ui-kit/helpers/d-element.gts
@@ -13,7 +13,13 @@ type ShortcutTag =
| "td"
| "aside"
| "ul"
- | "li";
+ | "li"
+ | "h1"
+ | "h2"
+ | "h3"
+ | "h4"
+ | "h5"
+ | "h6";
/**
* A wrapper component for a single known tag, typed with the matching element so
@@ -61,6 +67,24 @@ const shortcuts: { [K in ShortcutTag]: ElementWrapper<K> } = {
li: <template>
<li ...attributes>{{yield}}</li>
</template>,
+ h1: <template>
+ <h1 ...attributes>{{yield}}</h1>
+ </template>,
+ h2: <template>
+ <h2 ...attributes>{{yield}}</h2>
+ </template>,
+ h3: <template>
+ <h3 ...attributes>{{yield}}</h3>
+ </template>,
+ h4: <template>
+ <h4 ...attributes>{{yield}}</h4>
+ </template>,
+ h5: <template>
+ <h5 ...attributes>{{yield}}</h5>
+ </template>,
+ h6: <template>
+ <h6 ...attributes>{{yield}}</h6>
+ </template>,
};
/**
diff --git a/frontend/discourse/app/ui-kit/modifiers/d-pointer-drag.ts b/frontend/discourse/app/ui-kit/modifiers/d-pointer-drag.ts
index 7fff3ec773d..c398c08d173 100644
--- a/frontend/discourse/app/ui-kit/modifiers/d-pointer-drag.ts
+++ b/frontend/discourse/app/ui-kit/modifiers/d-pointer-drag.ts
@@ -89,6 +89,9 @@ interface DPointerDragSignature {
* A class toggled on the element for the gesture's duration. A single
* token: a value with whitespace in it is rejected by the DOM, which costs
* the drag its styling but leaves the gesture working.
+ *
+ * Applied when the gesture engages, so under a `threshold` it waits for
+ * the same distance `onDrag` does rather than landing on the press.
*/
draggingClass?: string;
@@ -104,16 +107,24 @@ interface DPointerDragSignature {
* Reach for a class on a shared ancestor, not this, when the target is
* simply outside the dragged element's subtree — a sibling is still
* reachable from the parent the two have in common.
+ *
+ * Applied when the gesture engages, on the same terms as `draggingClass`.
*/
bodyClass?: string;
/**
* Pixels of travel, measured as a straight line from the press origin, that
- * `onDrag` waits for before it starts firing. Reaching the distance is
- * enough; it does not have to be exceeded. Suppresses the jitter of a click
- * that was never meant to be a drag. Defaults to `0`. Read live until the
- * distance is reached; only the latch is permanent, so raising it after
- * movement has engaged will not re-suppress a gesture already under way.
+ * the gesture waits for before it engages: `onDrag` starts firing, and
+ * `draggingClass` and `bodyClass` go on. Reaching the distance is enough;
+ * it does not have to be exceeded. Suppresses the jitter of a click that
+ * was never meant to be a drag, in behaviour and in appearance alike.
+ * Defaults to `0`. Read live until the distance is reached; only the latch
+ * is permanent, so raising it after movement has engaged will not
+ * re-suppress a gesture already under way.
+ *
+ * `onDragStart` and `onDragEnd` are NOT gated by it: a press that never
+ * travels far enough still opens and commits the gesture, so read the
+ * position rather than assuming movement. `info.moved` tells the two apart.
*/
threshold?: number;
@@ -263,6 +274,38 @@ export function registerPointerDrag(
moved,
});
+ /**
+ * Marks the element and the body as dragging. Called when the gesture
+ * ENGAGES rather than when it is pressed, which for a gesture carrying a
+ * `threshold` are different moments: below that distance the press is still a
+ * click, and a rule keyed on these classes must not contradict that. A class
+ * that suppresses pointer events on descendants would otherwise take every
+ * plain click on the element. Without a threshold a gesture engages at the
+ * press, so this still runs there.
+ *
+ * @param args - The gesture's args, as read for the dispatch that engaged it.
+ */
+ const applyGestureClasses = (args: DPointerDragArgs) => {
+ if (args.draggingClass) {
+ try {
+ element.classList.add(args.draggingClass);
+ // Only once it is really on the element, so `finish` never tries to
+ // remove a token the DOM rejected.
+ appliedClass = args.draggingClass;
+ } catch {
+ // A whitespace token is a caller mistake: it costs the drag its styling
+ // but must not abort the gesture.
+ }
+ }
+ if (args.bodyClass) {
+ try {
+ bodyClassLease = new ElementClassLease(document.body, args.bodyClass);
+ } catch {
+ // Same as above: a rejected token costs the page-level styling only.
+ }
+ }
+ };
+
const finish = () => {
const finishedPointer = pointerId;
const classToRemove = appliedClass;
@@ -413,23 +456,8 @@ export function registerPointerDrag(
const superseded = pointerOwners.get(event.pointerId);
pointerOwners.set(event.pointerId, { element, supersede: onSuperseded });
- if (args.draggingClass) {
- try {
- element.classList.add(args.draggingClass);
- // Only once it is really on the element, so `finish` never tries to
- // remove a token the DOM rejected.
- appliedClass = args.draggingClass;
- } catch {
- // A whitespace token is a caller mistake: it costs the drag its styling
- // but must not abort the gesture.
- }
- }
- if (args.bodyClass) {
- try {
- bodyClassLease = new ElementClassLease(document.body, args.bodyClass);
- } catch {
- // Same as above: a rejected token costs the page-level styling only.
- }
+ if (engaged) {
+ applyGestureClasses(args);
}
// Only an accepted press is suppressed. A secondary button, a press during
@@ -457,6 +485,7 @@ export function registerPointerDrag(
return;
}
engaged = true;
+ applyGestureClasses(args);
}
// Latched before the dispatch, so this report already counts as movement.
moved = true;
diff --git a/frontend/discourse/tests/integration/ui-kit/d-button-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-button-test.gjs
index 46c8a6151ab..8c944261924 100644
--- a/frontend/discourse/tests/integration/ui-kit/d-button-test.gjs
+++ b/frontend/discourse/tests/integration/ui-kit/d-button-test.gjs
@@ -7,6 +7,16 @@ import { setupRenderingTest } from "discourse/tests/helpers/component-test";
import DButton from "discourse/ui-kit/d-button";
import I18n, { i18n } from "discourse-i18n";
+/**
+ * Clicks the button without settling, so a test can observe what has and has
+ * not run while the dispatch is still on the stack.
+ */
+function dispatchClick() {
+ const event = new MouseEvent("click", { bubbles: true, cancelable: true });
+ document.querySelector(".btn").dispatchEvent(event);
+ return event;
+}
+
module("Integration | ui-kit | DButton", function (hooks) {
setupRenderingTest(hooks);
@@ -330,6 +340,48 @@ module("Integration | ui-kit | DButton", function (hooks) {
assert.dom(".btn").exists("the click is handled without throwing");
});
+ test("claims the click for an @action it cannot call", async function (assert) {
+ for (const uncallable of ["invalid", 7, {}]) {
+ await render(<template><DButton @action={{uncallable}} /></template>);
+ const event = dispatchClick();
+ await settled();
+
+ assert.true(
+ event.defaultPrevented,
+ `prevents the default for ${JSON.stringify(uncallable)}`
+ );
+ }
+ });
+
+ test("calls a function @action even when it has a value property", async function (assert) {
+ const calls = [];
+ const handler = () => calls.push("function");
+ handler.value = () => calls.push("property");
+
+ await render(<template><DButton @action={{handler}} /></template>);
+ await click(".btn");
+
+ assert.deepEqual(calls, ["function"]);
+ });
+
+ test("@action takes precedence over @route", async function (assert) {
+ const transitionTo = sinon.stub(
+ this.owner.lookup("service:router"),
+ "transitionTo"
+ );
+ const record = this.record;
+
+ await render(
+ <template>
+ <DButton @action={{record}} @route="discovery.latest" />
+ </template>
+ );
+ await click(".btn");
+
+ assert.deepEqual(this.calls, [[undefined]], "runs the action");
+ assert.false(transitionTo.called, "does not navigate");
+ });
+
test("dispatches after the click on most platforms", async function (assert) {
sinon.stub(capabilities, "isIOS").value(false);
const record = this.record;
@@ -353,6 +405,156 @@ module("Integration | ui-kit | DButton", function (hooks) {
assert.deepEqual(this.calls, [["topic"]], "not deferred on iOS");
});
+
+ test("@action object form is triggered on click", async function (assert) {
+ // A method, not an arrow: an extracted-reference call would lose `this`
+ // and leave `seen` on the object untouched.
+ const handler = {
+ seen: null,
+ value(param) {
+ this.seen = param;
+ },
+ };
+
+ await render(
+ <template>
+ <DButton @action={{handler}} @actionParam="param" />
+ </template>
+ );
+
+ await click(".btn");
+
+ assert.strictEqual(
+ handler.seen,
+ "param",
+ "invokes value() as a method, so it keeps its receiver"
+ );
+ });
+
+ test("@action object form resolves value at invocation time", async function (assert) {
+ sinon.stub(capabilities, "isIOS").get(() => false);
+
+ const calls = [];
+ const handler = { value: () => calls.push("original") };
+
+ await render(<template><DButton @action={{handler}} /></template>);
+
+ dispatchClick();
+ // Swapped after dispatch but before the deferred run: the replacement wins
+ // only if the lookup happens when the handler actually runs.
+ handler.value = () => calls.push("replacement");
+
+ await settled();
+
+ assert.deepEqual(calls, ["replacement"], "reads .value when it runs");
+ });
+
+ test("@immediate runs the action inside the click dispatch", async function (assert) {
+ sinon.stub(capabilities, "isIOS").get(() => false);
+
+ let ran = false;
+ const handler = () => (ran = true);
+
+ await render(
+ <template><DButton @action={{handler}} @immediate={{true}} /></template>
+ );
+
+ assert.false(ran, "has not run before anything was dispatched");
+
+ dispatchClick();
+
+ assert.true(
+ ran,
+ "runs before the dispatch returns, so transient user activation survives"
+ );
+
+ await settled();
+ });
+
+ test("@immediate forwards the event when asked", async function (assert) {
+ sinon.stub(capabilities, "isIOS").get(() => false);
+
+ const received = [];
+ const handler = (...args) => received.push(args);
+
+ await render(
+ <template>
+ <DButton
+ @action={{handler}}
+ @forwardEvent={{true}}
+ @immediate={{true}}
+ />
+ </template>
+ );
+
+ const dispatched = dispatchClick();
+
+ assert.strictEqual(received.length, 1, "runs exactly once");
+ assert.strictEqual(
+ received[0][1],
+ dispatched,
+ "receives the very event that was dispatched, not merely an Event"
+ );
+
+ await settled();
+
+ assert.strictEqual(
+ received.length,
+ 1,
+ "and does not run again on settle"
+ );
+ });
+
+ for (const isIOS of [false, true]) {
+ for (const immediate of [false, true]) {
+ for (const type of ["click", "keydown"]) {
+ test(`forwards the original ${type} event and @actionParam (iOS=${isIOS}, @immediate=${immediate})`, async function (assert) {
+ sinon.stub(capabilities, "isIOS").get(() => isIOS);
+
+ const calls = [];
+ const param = { marker: true };
+ const handler = (value, event) =>
+ calls.push({ value, event, phase: event.eventPhase });
+
+ await render(
+ <template>
+ <DButton
+ @action={{handler}}
+ @actionParam={{param}}
+ @forwardEvent={{true}}
+ @immediate={{immediate}}
+ />
+ </template>
+ );
+
+ const event =
+ type === "click"
+ ? new MouseEvent(type, { bubbles: true, cancelable: true })
+ : new KeyboardEvent(type, {
+ key: "Enter",
+ bubbles: true,
+ cancelable: true,
+ });
+ document.querySelector(".btn").dispatchEvent(event);
+
+ const runsInDispatch = isIOS || immediate;
+ assert.strictEqual(calls.length, runsInDispatch ? 1 : 0);
+ assert.true(event.defaultPrevented, "claims the event");
+
+ await settled();
+
+ assert.strictEqual(calls.length, 1, "runs exactly once");
+ assert.strictEqual(calls[0].event, event, "the same event object");
+ assert.strictEqual(calls[0].value, param, "the same param object");
+ assert.strictEqual(
+ calls[0].phase,
+ runsInDispatch ? Event.AT_TARGET : Event.NONE,
+ "runs in the listener, or after the dispatch has finished"
+ );
+ });
+ }
+ }
+ }
});
test("ellipses", async function (assert) {
diff --git a/frontend/discourse/tests/integration/ui-kit/d-combo-button-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-combo-button-test.gjs
index 756ed3cb396..73d4e8a3f03 100644
--- a/frontend/discourse/tests/integration/ui-kit/d-combo-button-test.gjs
+++ b/frontend/discourse/tests/integration/ui-kit/d-combo-button-test.gjs
@@ -1,7 +1,8 @@
import { tracked } from "@glimmer/tracking";
-import { render, rerender, triggerEvent } from "@ember/test-helpers";
+import { click, render, rerender, triggerEvent } from "@ember/test-helpers";
import { module, test } from "qunit";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import DButton from "discourse/ui-kit/d-button";
import DComboButton from "discourse/ui-kit/d-combo-button";
module("Integration | ui-kit | DComboButton", function (hooks) {
@@ -187,4 +188,37 @@ module("Integration | ui-kit | DComboButton", function (hooks) {
assert.dom(".d-combo-button").hasClass("second");
assert.dom(".d-combo-button").doesNotHaveClass("first");
});
+
+ test("combo.Menu yields the menu API so its content can close it", async function (assert) {
+ await render(
+ <template>
+ <DComboButton @hasMenu={{true}} as |combo|>
+ <combo.Button @translatedLabel="Action" />
+ <combo.Menu @inline={{true}} @visibilityOptimizer="none" as |menu|>
+ <DButton class="inert" @translatedLabel="Inert" />
+ <DButton
+ class="close-from-content"
+ @action={{menu.close}}
+ @translatedLabel="Close"
+ />
+ </combo.Menu>
+ </DComboButton>
+ </template>
+ );
+ await open();
+
+ assert.dom(".close-from-content").exists("the content block rendered");
+
+ await click(".inert");
+
+ assert
+ .dom(".fk-d-menu")
+ .exists("a click inside the content alone does not close it");
+
+ await click(".close-from-content");
+
+ assert
+ .dom(".fk-d-menu")
+ .doesNotExist("the yielded close() shut the menu it belongs to");
+ });
});
diff --git a/frontend/discourse/tests/integration/ui-kit/d-element-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-element-test.gjs
index 1d4d852b27d..83b80998f80 100644
--- a/frontend/discourse/tests/integration/ui-kit/d-element-test.gjs
+++ b/frontend/discourse/tests/integration/ui-kit/d-element-test.gjs
@@ -18,6 +18,28 @@ module("Integration | ui-kit | dElement", function (hooks) {
assert.dom(".probe").hasTagName("ul");
});
+ test("heading shortcuts render the bare heading with caller attributes", async function (assert) {
+ const Heading = dElement("h2");
+
+ assert.strictEqual(dElement("h2"), Heading, "one wrapper per tag");
+ assert.notStrictEqual(dElement("h3"), Heading, "a wrapper for each level");
+
+ await render(
+ <template>
+ <Heading aria-label="Accessible title" class="probe" id="heading">
+ Body
+ </Heading>
+ </template>
+ );
+
+ assert
+ .dom("h2#heading")
+ .doesNotHaveClass("ember-view", "renders the shortcut, not the fallback");
+ assert.dom("h2#heading").hasClass("probe");
+ assert.dom("h2#heading").hasAria("label", "Accessible title");
+ assert.dom("h2#heading").hasText("Body", "no element wraps the content");
+ });
+
test("an unlisted tag falls back to a wrapper for that tag", async function (assert) {
const Tag = dElement("section");
diff --git a/frontend/discourse/tests/integration/ui-kit/d-empty-state-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-empty-state-test.gjs
index c7e38866750..b57f7f5ca5a 100644
--- a/frontend/discourse/tests/integration/ui-kit/d-empty-state-test.gjs
+++ b/frontend/discourse/tests/integration/ui-kit/d-empty-state-test.gjs
@@ -1,4 +1,5 @@
-import { render } from "@ember/test-helpers";
+import { tracked } from "@glimmer/tracking";
+import { render, rerender } from "@ember/test-helpers";
import { module, test } from "qunit";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
import DEmptyState from "discourse/ui-kit/d-empty-state";
@@ -17,6 +18,86 @@ module("Integration | ui-kit | DEmptyState", function (hooks) {
assert.dom("[data-test-body]").exists();
});
+ test("text-only without an image or an icon", async function (assert) {
+ await render(<template><DEmptyState @title="title" /></template>);
+
+ assert.dom(".empty-state__container").hasClass("--text-only");
+ assert.dom(".empty-state__image").doesNotExist();
+ });
+
+ test("@icon renders an icon in place of an illustration", async function (assert) {
+ await render(
+ <template><DEmptyState @icon="table-columns" @title="title" /></template>
+ );
+
+ assert.dom(".empty-state__image.--icon .d-icon-table-columns").exists();
+ assert
+ .dom(".empty-state__container")
+ .hasClass("--with-image", "an icon counts as the image slot");
+ });
+
+ test("@svgContent wins over @icon", async function (assert) {
+ await render(
+ <template>
+ <DEmptyState @icon="table-columns" @svgContent="art" @title="title" />
+ </template>
+ );
+
+ assert.dom(".empty-state__image").hasText("art");
+ assert
+ .dom(".empty-state__image .d-icon-table-columns")
+ .doesNotExist("the icon does not render alongside the illustration");
+ });
+
+ test("attributes reach the container", async function (assert) {
+ await render(
+ <template>
+ <DEmptyState class="extra" data-test-thing="yes" @title="title" />
+ </template>
+ );
+
+ assert.dom(".empty-state__container").hasClass("extra");
+ assert
+ .dom(".empty-state__container")
+ .hasAttribute("data-test-thing", "yes");
+ });
+
+ test("dynamic classes and @icon update without dropping its own classes", async function (assert) {
+ const state = new (class {
+ @tracked extra = "first";
+ @tracked icon = "gear";
+ })();
+
+ await render(
+ <template>
+ <DEmptyState
+ class={{state.extra}}
+ role="status"
+ @icon={{state.icon}}
+ @identifier="probe"
+ @title="Empty"
+ />
+ </template>
+ );
+
+ assert.dom(".empty-state__container").hasClass("--probe");
+ assert.dom(".empty-state__container").hasClass("--with-image");
+
+ state.extra = "second";
+ state.icon = null;
+ await rerender();
+
+ assert
+ .dom(".empty-state__container")
+ .hasClass("second")
+ .doesNotHaveClass("first")
+ .hasClass("--probe")
+ .hasClass("--text-only")
+ .doesNotHaveClass("--with-image")
+ .hasAttribute("role", "status");
+ assert.dom(".empty-state__image").doesNotExist();
+ });
+
test("@ctaDisabled", async function (assert) {
await render(
<template>
diff --git a/frontend/discourse/tests/integration/ui-kit/d-page-subheader-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-page-subheader-test.gjs
index 860ff66caea..db62248d260 100644
--- a/frontend/discourse/tests/integration/ui-kit/d-page-subheader-test.gjs
+++ b/frontend/discourse/tests/integration/ui-kit/d-page-subheader-test.gjs
@@ -1,4 +1,12 @@
-import { click, render } from "@ember/test-helpers";
+import { tracked } from "@glimmer/tracking";
+import {
+ click,
+ find,
+ render,
+ rerender,
+ resetOnerror,
+ setupOnerror,
+} from "@ember/test-helpers";
import { module, test } from "qunit";
import { forceMobile } from "discourse/lib/mobile";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
@@ -18,6 +26,124 @@ module("Integration | ui-kit | DPageSubheader", function (hooks) {
.hasText(i18n("admin.title"));
});
+ test("the title is an h2 by default", async function (assert) {
+ await render(<template><DPageSubheader @titleLabel="Title" /></template>);
+
+ assert.dom("h2.d-page-subheader__title").exists();
+ });
+
+ test("@titleHeadingLevel picks the heading element", async function (assert) {
+ await render(
+ <template>
+ <DPageSubheader @titleHeadingLevel={{3}} @titleLabel="Title" />
+ </template>
+ );
+
+ assert.dom("h3.d-page-subheader__title").exists();
+ assert
+ .dom("h2.d-page-subheader__title")
+ .doesNotExist("it does not also render the default level");
+ });
+
+ test("a null @titleHeadingLevel falls back to h2", async function (assert) {
+ await render(
+ <template>
+ <DPageSubheader @titleHeadingLevel={{null}} @titleLabel="Title" />
+ </template>
+ );
+
+ assert.dom("h2.d-page-subheader__title").exists();
+ });
+
+ // One test per value: after a render error the app refuses to render again.
+ for (const level of [0, 7, -1, 2.5, "3", NaN]) {
+ const label = typeof level === "string" ? `"${level}"` : String(level);
+
+ test(`@titleHeadingLevel rejects ${label}`, async function (assert) {
+ let raised;
+ setupOnerror((error) => (raised = error));
+
+ try {
+ await render(
+ <template>
+ <DPageSubheader @titleHeadingLevel={{level}} @titleLabel="Title" />
+ </template>
+ );
+ } finally {
+ resetOnerror();
+ }
+
+ assert.true(/must be 1-6/.test(raised?.message));
+ });
+ }
+
+ test("the title keeps its subheader styling at any heading level", async function (assert) {
+ await render(
+ <template>
+ <DPageSubheader @titleLabel="Default" />
+ <DPageSubheader @titleHeadingLevel={{3}} @titleLabel="Nested" />
+ </template>
+ );
+
+ const h2 = getComputedStyle(find("h2.d-page-subheader__title"));
+ const h3 = getComputedStyle(find("h3.d-page-subheader__title"));
+
+ // Pins the stylesheet as loaded: without it both titles would match at
+ // browser defaults and the comparisons below would pass vacuously.
+ assert.strictEqual(h2.marginBottom, "0px");
+ assert.strictEqual(h3.marginBottom, h2.marginBottom, "same margin");
+ assert.strictEqual(h3.fontSize, h2.fontSize, "same font size");
+ });
+
+ test("the title updates in place and survives level changes", async function (assert) {
+ const state = new (class {
+ @tracked level = 2;
+ @tracked title = "First";
+ })();
+
+ await render(
+ <template>
+ <DPageSubheader
+ @titleHeadingLevel={{state.level}}
+ @titleLabel={{state.title}}
+ @titleUrl="#target"
+ />
+ </template>
+ );
+
+ const heading = find("h2.d-page-subheader__title");
+ const link = find(".d-page-subheader__title-link");
+
+ assert
+ .dom(heading)
+ .doesNotHaveClass("ember-view", "renders no classic component wrapper");
+
+ state.title = "Second";
+ await rerender();
+
+ assert.strictEqual(
+ find("h2.d-page-subheader__title"),
+ heading,
+ "keeps the heading node"
+ );
+ assert.strictEqual(
+ find(".d-page-subheader__title-link"),
+ link,
+ "keeps the link node"
+ );
+ assert.dom(link).hasText("Second");
+
+ for (const level of [1, 3, 4, 5, 6, 2]) {
+ state.level = level;
+ await rerender();
+
+ assert.dom(`h${level}.d-page-subheader__title`).exists({ count: 1 });
+ assert
+ .dom(".d-page-subheader__title-link")
+ .hasAttribute("href", "#target", `keeps the link at h${level}`);
+ }
+ });
+
test("no @descriptionLabel", async function (assert) {
await render(<template><DPageSubheader /></template>);
assert.dom(".d-page-subheader__description").doesNotExist();
diff --git a/frontend/discourse/tests/integration/ui-kit/helpers/d-avatar-test.gjs b/frontend/discourse/tests/integration/ui-kit/helpers/d-avatar-test.gjs
new file mode 100644
index 00000000000..683d10684aa
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/helpers/d-avatar-test.gjs
@@ -0,0 +1,52 @@
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import dAvatar from "discourse/ui-kit/helpers/d-avatar";
+
+module("Integration | ui-kit | Helper | dAvatar", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.siteSettings.prioritize_username_in_ux = false;
+ this.siteSettings.enable_names = true;
+ this.user = {
+ username: "login_name",
+ name: "O'Name <&>",
+ title: "Moderator",
+ avatar_template: "/avatar/{size}.png",
+ };
+ });
+
+ test("alt is empty by default", async function (assert) {
+ const user = this.user;
+
+ await render(<template>{{dAvatar user imageSize="tiny"}}</template>);
+
+ assert.dom("img.avatar").hasAttribute("alt", "");
+ });
+
+ test("alt=true uses the display name and leaves the title alone", async function (assert) {
+ const user = this.user;
+
+ await render(
+ <template>{{dAvatar user alt=true imageSize="tiny"}}</template>
+ );
+
+ assert.dom("img.avatar").hasAttribute("alt", user.name);
+ assert.dom("img.avatar").hasAttribute("title", "Moderator");
+ });
+
+ test("an alt string is escaped as text", async function (assert) {
+ const user = this.user;
+ const alt = "' onerror='alert(1)";
+
+ await render(
+ <template>{{dAvatar user alt=alt imageSize="tiny"}}</template>
+ );
+
+ assert.dom("img.avatar").hasAttribute("alt", alt);
+ assert
+ .dom("img.avatar")
+ .doesNotHaveAttribute("onerror", "it cannot break out of the attribute");
+ });
+});
diff --git a/frontend/discourse/tests/integration/ui-kit/modifiers/d-pointer-drag-test.gjs b/frontend/discourse/tests/integration/ui-kit/modifiers/d-pointer-drag-test.gjs
index 24c97a86df3..e00f387632c 100644
--- a/frontend/discourse/tests/integration/ui-kit/modifiers/d-pointer-drag-test.gjs
+++ b/frontend/discourse/tests/integration/ui-kit/modifiers/d-pointer-drag-test.gjs
@@ -611,7 +611,212 @@ module("Integration | ui-kit | d-pointer-drag", function (hooks) {
assert.deepEqual(
calls,
["start", "end:2"],
- "the threshold gates onDrag only: a click on a thresholded handle still commits, so a consumer must read the position rather than assume movement"
+ "the threshold does not gate the ends of the gesture: a click on a thresholded handle still commits, so a consumer must read the position rather than assume movement"
+ );
+ });
+
+ test("the dragging class is held back until a thresholded gesture engages", async function (assert) {
+ await render(
+ <template>
+ <div
+ class="dpd-target"
+ {{dPointerDrag threshold=5 draggingClass="--dragging"}}
+ ></div>
+ </template>
+ );
+
+ const target = find(".dpd-target");
+ stubPointerCapture(target);
+
+ await triggerEvent(target, "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ clientX: 0,
+ clientY: 0,
+ });
+ assert
+ .dom(target)
+ .doesNotHaveClass(
+ "--dragging",
+ "the press alone is not yet a drag, so it carries no dragging class"
+ );
+
+ await triggerEvent(target, "pointermove", {
+ pointerId: 1,
+ clientX: 4,
+ clientY: 0,
+ });
+ assert
+ .dom(target)
+ .doesNotHaveClass(
+ "--dragging",
+ "nor does movement that stays inside the threshold"
+ );
+
+ await triggerEvent(target, "pointermove", {
+ pointerId: 1,
+ clientX: 5,
+ clientY: 0,
+ });
+ assert
+ .dom(target)
+ .hasClass(
+ "--dragging",
+ "reaching the threshold engages the gesture and marks it"
+ );
+
+ await triggerEvent(target, "pointermove", {
+ pointerId: 1,
+ clientX: 1,
+ clientY: 0,
+ });
+ assert
+ .dom(target)
+ .hasClass(
+ "--dragging",
+ "and returning inside the threshold keeps the mark, as the engagement latch does"
+ );
+
+ await triggerEvent(target, "pointerup", {
+ pointerId: 1,
+ clientX: 1,
+ clientY: 0,
+ });
+ assert
+ .dom(target)
+ .doesNotHaveClass("--dragging", "release clears it as usual");
+ });
+
+ test("the body class is held back until a thresholded gesture engages", async function (assert) {
+ await render(
+ <template>
+ <div
+ class="dpd-target"
+ {{dPointerDrag threshold=5 bodyClass="dragging"}}
+ ></div>
+ </template>
+ );
+
+ const target = find(".dpd-target");
+ stubPointerCapture(target);
+
+ await triggerEvent(target, "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ clientX: 0,
+ clientY: 0,
+ });
+ assert
+ .dom(document.body)
+ .doesNotHaveClass(
+ "dragging",
+ "the press alone leaves the body unmarked"
+ );
+
+ await triggerEvent(target, "pointermove", {
+ pointerId: 1,
+ clientX: 4,
+ clientY: 0,
+ });
+ assert
+ .dom(document.body)
+ .doesNotHaveClass("dragging", "as does movement inside the threshold");
+
+ await triggerEvent(target, "pointermove", {
+ pointerId: 1,
+ clientX: 5,
+ clientY: 0,
+ });
+ assert
+ .dom(document.body)
+ .hasClass("dragging", "reaching the threshold marks the body");
+
+ // Two further moves past the latch. The body class is held by a counted
+ // lease, so an implementation that re-takes one per move would need as
+ // many releases as it took, and the single release below would leave the
+ // class stranded on the body.
+ await triggerEvent(target, "pointermove", {
+ pointerId: 1,
+ clientX: 9,
+ clientY: 0,
+ });
+ await triggerEvent(target, "pointermove", {
+ pointerId: 1,
+ clientX: 14,
+ clientY: 0,
+ });
+
+ await triggerEvent(target, "pointerup", {
+ pointerId: 1,
+ clientX: 14,
+ clientY: 0,
+ });
+ assert
+ .dom(document.body)
+ .doesNotHaveClass(
+ "dragging",
+ "release unmarks it, however many moves the gesture saw"
+ );
+ });
+
+ test("a click on a thresholded handle applies neither gesture class", async function (assert) {
+ const calls = [];
+ const onDragStart = () => calls.push("start");
+ const onDragEnd = () => calls.push("end");
+
+ await render(
+ <template>
+ <div
+ class="dpd-target"
+ {{dPointerDrag
+ threshold=5
+ draggingClass="--dragging"
+ bodyClass="dragging"
+ onDragStart=onDragStart
+ onDragEnd=onDragEnd
+ }}
+ ></div>
+ </template>
+ );
+
+ const target = find(".dpd-target");
+ stubPointerCapture(target);
+
+ await triggerEvent(target, "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ clientX: 0,
+ clientY: 0,
+ });
+ await triggerEvent(target, "pointermove", {
+ pointerId: 1,
+ clientX: 2,
+ clientY: 0,
+ });
+
+ // Read while the press is still held. Waiting for the release would prove
+ // nothing: the gesture clears both classes on the way out, so a press that
+ // wrongly applied them looks identical to one that never did.
+ assert
+ .dom(target)
+ .doesNotHaveClass(
+ "--dragging",
+ "a press that never became a drag never looks like one"
+ );
+ assert
+ .dom(document.body)
+ .doesNotHaveClass("dragging", "and never marks the body either");
+
+ await triggerEvent(target, "pointerup", {
+ pointerId: 1,
+ clientX: 2,
+ clientY: 0,
+ });
+
+ assert.deepEqual(
+ calls,
+ ["start", "end"],
+ "and the gesture still runs its lifecycle, so withholding the classes is not withholding the gesture"
);
});
diff --git a/frontend/discourse/tests/unit/lib/avatar-utils-test.js b/frontend/discourse/tests/unit/lib/avatar-utils-test.js
index 941f9a88641..0768b2542b5 100644
--- a/frontend/discourse/tests/unit/lib/avatar-utils-test.js
+++ b/frontend/discourse/tests/unit/lib/avatar-utils-test.js
@@ -88,6 +88,26 @@ module("Unit | Utilities", function (hooks) {
"it doesn't render avatars for invalid avatar template"
);
+ assert.strictEqual(
+ avatarImg({
+ avatarTemplate,
+ size: "tiny",
+ alt: "evilest trout",
+ }),
+ "<img alt='evilest trout' width='24' height='24' src='/path/to/avatar/48.png' class='avatar'>",
+ "it sets alt text if supplied"
+ );
+
+ assert.strictEqual(
+ avatarImg({
+ avatarTemplate,
+ size: "tiny",
+ alt: "<script>alert('x')</script>",
+ }),
+ "<img alt='&lt;script&gt;alert(&#x27;x&#x27;)&lt;/script&gt;' width='24' height='24' src='/path/to/avatar/48.png' class='avatar'>",
+ "it escapes the alt text"
+ );
+
setDevicePixelRatio(oldRatio);
});
});