Skip to content

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

DEV: Tighten ui-kit and float-kit types for strict mode (#44353)

Sérgio Saquetima04c0b04ec38
diff --git a/frontend/discourse/app/lib/-internals/drag-and-drop/consumer-may-throw.ts b/frontend/discourse/app/lib/-internals/drag-and-drop/consumer-may-throw.ts
index 290d2b5dd3d..1c1585d076d 100644
--- a/frontend/discourse/app/lib/-internals/drag-and-drop/consumer-may-throw.ts
+++ b/frontend/discourse/app/lib/-internals/drag-and-drop/consumer-may-throw.ts
@@ -17,6 +17,8 @@ import { reportClientError } from "discourse/lib/report-client-error";
* @param fallback - Returned when the callback throws. Give a gate its
* conservative answer.
*/
+export function consumerMayThrow<T>(run: () => T, fallback: T): T;
+export function consumerMayThrow<T>(run: () => T): T | undefined;
export function consumerMayThrow<T>(run: () => T, fallback?: T): T | undefined {
try {
return run();
diff --git a/frontend/discourse/app/lib/-internals/drag-and-drop/drop-target-kernel.ts b/frontend/discourse/app/lib/-internals/drag-and-drop/drop-target-kernel.ts
index 6ffa0fdd968..060b31974ec 100644
--- a/frontend/discourse/app/lib/-internals/drag-and-drop/drop-target-kernel.ts
+++ b/frontend/discourse/app/lib/-internals/drag-and-drop/drop-target-kernel.ts
@@ -130,8 +130,10 @@ type LibraryEventArgs<Payload> = {
};
/**
- * What the kernel hands an adapter's `register` function, shaped so the
- * library's registrars accept it without a cast.
+ * What the kernel hands an adapter's `register` function, shaped after the
+ * library's registrars. `getDropEffect` may return `undefined`, which the library
+ * handles at runtime but its type does not admit, so each adapter casts its
+ * registrar to {@link DropTargetRegistrar}.
*/
export type DropTargetRegistrationArgs<Payload> = {
element: Element;
@@ -150,6 +152,11 @@ export type DropTargetRegistrationArgs<Payload> = {
onDrop: (args: LibraryEventArgs<Payload>) => void;
};
+/** Registers the kernel's callbacks with a library adapter. */
+export type DropTargetRegistrar<Payload> = (
+ args: DropTargetRegistrationArgs<Payload>
+) => CleanupFn;
+
/** Adapter-specific configuration for the shared drop-target state machine. */
export interface DropTargetKernelConfig<Payload, Source> {
/** The element to register as a drop target. */
@@ -159,7 +166,7 @@ export interface DropTargetKernelConfig<Payload, Source> {
attribute: "data-drop-target" | "data-drop-target-external";
/** Registers the callbacks with the adapter. */
- register: (args: DropTargetRegistrationArgs<Payload>) => CleanupFn;
+ register: DropTargetRegistrar<Payload>;
/** Converts the adapter payload to the consumer-facing source. */
decorateSource: (payload: Payload) => Source;
diff --git a/frontend/discourse/app/ui-kit/d-async-content.gts b/frontend/discourse/app/ui-kit/d-async-content.gts
index 12b189da487..06b899ac364 100644
--- a/frontend/discourse/app/ui-kit/d-async-content.gts
+++ b/frontend/discourse/app/ui-kit/d-async-content.gts
@@ -43,9 +43,11 @@ interface DAsyncContentSignature<T> {
* - a `Promise` that resolves to the value;
* - an already-constructed `TrackedAsyncData`, when the caller manages the
* async state itself;
- * - an `AsyncDataFn` that produces the value on demand.
+ * - an `AsyncDataFn` that produces the value on demand;
+ * - `undefined`, when there is nothing to load yet; it renders like a value
+ * that resolved empty.
*/
- asyncData: Promise<T> | TrackedAsyncData<T> | AsyncDataFn<T>;
+ asyncData: Promise<T> | TrackedAsyncData<T> | AsyncDataFn<T> | undefined;
/**
* A value forwarded to the function form of `@asyncData`. It is tracked, so
@@ -94,8 +96,11 @@ interface DAsyncContentSignature<T> {
/** Rendered once the data resolves. */
content: [
- /** The resolved value. */
- value: T,
+ /**
+ * The resolved value. `undefined` when the data resolved empty and no
+ * `:empty` block was provided.
+ */
+ value: T | undefined,
];
/** Rendered in place of `content` when the resolved value is falsy. */
@@ -252,9 +257,10 @@ export default class DAsyncContent<T> extends Component<
// a source renders content with no pending/loading phase; a promise resolves
// asynchronously as usual.
//
- // The branch analysis above is exhaustive for the supported `@asyncData`
- // shapes, so `value` is always assigned; the cast drops the never-hit
- // `Promise<void>`/`undefined` members and pins the resolved type to `T`.
+ // An `undefined` `@asyncData` matches neither branch above, so `value` stays
+ // `undefined` and resolves at once, rendering the empty state like any other
+ // falsy value. The cast drops the never-hit `Promise<void>` member and pins the
+ // resolved type to `T`.
return new TrackedAsyncData(value as T | Promise<T>);
}
diff --git a/frontend/discourse/app/ui-kit/d-icon-grid-picker/content.gjs b/frontend/discourse/app/ui-kit/d-icon-grid-picker/content.gjs
index 02308e30622..40688f04c5f 100644
--- a/frontend/discourse/app/ui-kit/d-icon-grid-picker/content.gjs
+++ b/frontend/discourse/app/ui-kit/d-icon-grid-picker/content.gjs
@@ -1,6 +1,7 @@
// @ts-check
import Component from "@glimmer/component";
import { tracked } from "@glimmer/tracking";
+import { assert } from "@ember/debug";
import { fn, hash } from "@ember/helper";
import { on } from "@ember/modifier";
import { action } from "@ember/object";
@@ -94,6 +95,8 @@ export default class DIconGridPickerContent extends Component {
@tracked hasMore = false;
@tracked loadingMore = false;
+
+ /** @type {HTMLElement | null} */
@tracked gridWrapper = null;
registerGridWrapper = modifier((/** @type {HTMLElement} */ element) => {
@@ -367,7 +370,7 @@ export default class DIconGridPickerContent extends Component {
* Loads the first page of icons. Used as the `@asyncData` callback for the
* `AsyncContent` loader, which debounces it and aborts superseded searches.
*
- * @param {string} _filter - Tracked by `@context`; read from `this.filter`.
+ * @param {unknown} _filter - Tracked by `@context`; read from `this.filter`.
* @param {{signal: AbortSignal}} options
* @returns {Promise<Array<{id: string, symbol?: string}>>} The first page.
*/
@@ -403,7 +406,10 @@ export default class DIconGridPickerContent extends Component {
return;
}
- this.icons = [...this.icons, ...icons];
+ // `hasMore` is only set together with the first page, so it is loaded here.
+ const loaded = this.icons;
+ assert("More icons load only after the first page", loaded);
+ this.icons = [...loaded, ...icons];
this.hasMore = hasMore;
this.#page++;
} catch (error) {
@@ -423,13 +429,17 @@ export default class DIconGridPickerContent extends Component {
* scroll into, and moves focus onto the first icon that arrives.
*/
async loadMoreAndFocus() {
- const next = this.icons.length;
+ const loadedIcons = this.icons;
+ assert("The keyboard pages a grid that has loaded", loadedIcons);
+ const next = loadedIcons.length;
await this.loadMore();
schedule("afterRender", () => {
+ const icons = this.icons;
+ assert("The keyboard pages a grid that has loaded", icons);
/** @type {HTMLElement | undefined} */ (
this.gridWrapper?.querySelector(
- `.d-icon-grid-picker__grid [data-icon-id="${this.icons[next]?.id}"]`
+ `.d-icon-grid-picker__grid [data-icon-id="${icons[next]?.id}"]`
)
)?.focus();
});
diff --git a/frontend/discourse/app/ui-kit/d-modal.gts b/frontend/discourse/app/ui-kit/d-modal.gts
index 8153de8cc71..bb0e062e665 100644
--- a/frontend/discourse/app/ui-kit/d-modal.gts
+++ b/frontend/discourse/app/ui-kit/d-modal.gts
@@ -1,5 +1,6 @@
import Component from "@glimmer/component";
import { cached, tracked } from "@glimmer/tracking";
+import { assert } from "@ember/debug";
import { on } from "@ember/modifier";
import { action } from "@ember/object";
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
@@ -190,7 +191,7 @@ export default class DModal extends Component<DModalSignature> {
@tracked animating = false;
registerModalContainer = modifierFn((el: HTMLElement) => {
- this.#modalContainer = el;
+ this.#modalContainerElement = el;
});
setupModalBody = modifierFn((el: HTMLElement) => {
if (this.site.desktopView) {
@@ -222,10 +223,17 @@ export default class DModal extends Component<DModalSignature> {
}
};
});
- #modalContainer: HTMLElement;
+ #modalContainerElement?: HTMLElement;
#lockedScrollY?: number;
@tracked _wrapperElement?: HTMLElement;
+ /** Registered on insert; every reader runs after the modal has rendered. */
+ get #modalContainer(): HTMLElement {
+ const element = this.#modalContainerElement;
+ assert("DModal: the container is read before it was registered", element);
+ return element;
+ }
+
get autofocus() {
return this.args.autofocus ?? true;
}
diff --git a/frontend/discourse/app/ui-kit/d-otp/index.gjs b/frontend/discourse/app/ui-kit/d-otp/index.gjs
index de7a1c0a44c..f2e374c5f73 100644
--- a/frontend/discourse/app/ui-kit/d-otp/index.gjs
+++ b/frontend/discourse/app/ui-kit/d-otp/index.gjs
@@ -79,6 +79,7 @@ export default class DOTP extends Component {
return this.otp.join("");
}
+ /** @param {string} value */
normalizeInput(value) {
if (this.args.normalizeInput) {
return this.args.normalizeInput(value);
@@ -87,6 +88,7 @@ export default class DOTP extends Component {
return value.replace(/[^0-9]/g, "");
}
+ /** @param {number} index */
@action
showSeparator(index) {
return (
@@ -96,6 +98,7 @@ export default class DOTP extends Component {
);
}
+ /** @param {HTMLInputElement} element */
@action
focusInput(element) {
if (!this.autoFocus) {
diff --git a/frontend/discourse/app/ui-kit/d-resize-separator.gts b/frontend/discourse/app/ui-kit/d-resize-separator.gts
index 386889e545c..d77218196a3 100644
--- a/frontend/discourse/app/ui-kit/d-resize-separator.gts
+++ b/frontend/discourse/app/ui-kit/d-resize-separator.gts
@@ -268,8 +268,8 @@ export default class DResizeSeparator extends Component<DResizeSeparatorSignatur
@tracked
_announced: {
now: number | undefined;
- min: number | undefined;
- max: number | undefined;
+ min: number | null | undefined;
+ max: number | null | undefined;
} | null = null;
constructor(owner: Owner, args: DResizeSeparatorSignature["Args"]) {
diff --git a/frontend/discourse/app/ui-kit/d-tabs.gts b/frontend/discourse/app/ui-kit/d-tabs.gts
index 37eb047f88d..5c7507c6287 100644
--- a/frontend/discourse/app/ui-kit/d-tabs.gts
+++ b/frontend/discourse/app/ui-kit/d-tabs.gts
@@ -547,7 +547,8 @@ export default class DTabs extends Component<DTabsSignature> {
node instanceof Element &&
(node.getAttribute("role") !== "tab" ||
registeredKey === undefined ||
- this.#tabs.get(registeredKey) !== node);
+ // `node instanceof Element` already ruled out the `false` branch.
+ this.#tabs.get(registeredKey as string) !== node);
const isStrayText =
node.nodeType === Node.TEXT_NODE &&
(node.textContent ?? "").trim() !== "";
diff --git a/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-auto-scroll.ts b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-auto-scroll.ts
index 896afe66662..3daa73acc39 100644
--- a/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-auto-scroll.ts
+++ b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-auto-scroll.ts
@@ -59,11 +59,24 @@ interface DDragAndDropAutoScrollSignature {
* {@link registerDragAndDropAutoScroll} imperatively rather than through the
* modifier.
*/
-export type DragAndDropAutoScrollArgs =
- DDragAndDropAutoScrollSignature["Args"]["Named"] & {
- /** The scroll container. Required when `target` is `"element"`. */
- element?: HTMLElement;
- };
+export type DragAndDropAutoScrollArgs = Omit<
+ DDragAndDropAutoScrollSignature["Args"]["Named"],
+ "target"
+> &
+ (
+ | {
+ /** Scrolls the window, so no container is needed. */
+ target: "window";
+ /** Ignored when the window is the target. */
+ element?: HTMLElement;
+ }
+ | {
+ /** Scrolls `element`. The default. */
+ target?: "element";
+ /** The scroll container. */
+ element: HTMLElement;
+ }
+ );
/**
* Imperative auto-scroll registration; the `dDragAndDropAutoScroll` modifier
diff --git a/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-external-target.ts b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-external-target.ts
index f20b97a0422..3f3be2922df 100644
--- a/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-external-target.ts
+++ b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-external-target.ts
@@ -6,6 +6,7 @@ import {
type DropTargetKernelArgs,
type DropTargetKernelEvent,
type DropTargetKernelFeedback,
+ type DropTargetRegistrar,
registerDropTargetKernel,
} from "discourse/lib/-internals/drag-and-drop/drop-target-kernel";
import {
@@ -73,7 +74,11 @@ export function registerDragAndDropExternalTarget(
return registerDropTargetKernel({
element,
attribute: "data-drop-target-external",
- register: dropTargetForExternal,
+ // The library falls back to its default drop effect when `getDropEffect`
+ // returns `undefined` (`getDropEffect?.() ?? defaultDropEffect`), but its type
+ // does not admit `undefined`.
+ register:
+ dropTargetForExternal as DropTargetRegistrar<NativeExternalDragPayload>,
decorateSource: (source: NativeExternalDragPayload) =>
decorateExternalSource(source),
accepts: (source) => matchesExternalKind(getArgsRef().accepts, source),
diff --git a/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-target.ts b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-target.ts
index cd13f9d3cf5..75f25994107 100644
--- a/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-target.ts
+++ b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-target.ts
@@ -7,6 +7,7 @@ import {
type DropTargetKernelArgs,
type DropTargetKernelEvent,
type DropTargetKernelFeedback,
+ type DropTargetRegistrar,
registerDropTargetKernel,
} from "discourse/lib/-internals/drag-and-drop/drop-target-kernel";
import {
@@ -112,7 +113,10 @@ export function registerDragAndDropTarget(
return registerDropTargetKernel({
element,
attribute: "data-drop-target",
- register: dropTargetForElements,
+ // The library falls back to its default drop effect when `getDropEffect`
+ // returns `undefined` (`getDropEffect?.() ?? defaultDropEffect`), but its type
+ // does not admit `undefined`.
+ register: dropTargetForElements as DropTargetRegistrar<ElementDragPayload>,
decorateSource: (source: ElementDragPayload) => normalizeDragSource(source),
accepts: (source) => {
const args = getArgsRef();
diff --git a/frontend/discourse/app/ui-kit/modifiers/d-drag-dwell.ts b/frontend/discourse/app/ui-kit/modifiers/d-drag-dwell.ts
index c749a0f8762..692b463acdf 100644
--- a/frontend/discourse/app/ui-kit/modifiers/d-drag-dwell.ts
+++ b/frontend/discourse/app/ui-kit/modifiers/d-drag-dwell.ts
@@ -361,9 +361,10 @@ export function registerDragDwell(
dwell?.update(null);
if (lastEvent) {
+ const endEvent = lastEvent;
consumerMayThrow(() =>
getArgsRef().onDwellEnd?.({
- ...lastEvent,
+ ...endEvent,
reason: "left",
fired,
droppedHere: false,
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 5a78090f68b..7fff3ec773d 100644
--- a/frontend/discourse/app/ui-kit/modifiers/d-pointer-drag.ts
+++ b/frontend/discourse/app/ui-kit/modifiers/d-pointer-drag.ts
@@ -1,3 +1,4 @@
+import { assert } from "@ember/debug";
import { registerDestructor } from "@ember/destroyable";
import type Owner from "@ember/owner";
import Modifier, { type ArgsFor } from "ember-modifier";
@@ -400,7 +401,7 @@ export function registerPointerDrag(
}
pointerId = event.pointerId;
- engaged = !(args.threshold > 0);
+ engaged = !((args.threshold ?? 0) > 0);
// A press bubbles, so an ancestor registration starts its own gesture from
// the same event. Capture requested during `pointerdown` is only pending
@@ -579,7 +580,10 @@ export default class DPointerDragModifier extends Modifier<DPointerDragSignature
// installed once and reads these live.
this.#args = named;
- this.#cleanup ??= registerPointerDrag(element, () => this.#args);
+ this.#cleanup ??= registerPointerDrag(element, () => {
+ assert("dPointerDrag: args are read before `modify`", this.#args);
+ return this.#args;
+ });
// Re-reflected here rather than only at registration: the declaration has to
// be in place before a touch begins, so a consumer that changes it between
diff --git a/frontend/discourse/app/ui-kit/modifiers/d-resize-edge.ts b/frontend/discourse/app/ui-kit/modifiers/d-resize-edge.ts
index 2f992df1664..36d0ed8461e 100644
--- a/frontend/discourse/app/ui-kit/modifiers/d-resize-edge.ts
+++ b/frontend/discourse/app/ui-kit/modifiers/d-resize-edge.ts
@@ -1,3 +1,4 @@
+import { assert } from "@ember/debug";
import { registerDestructor } from "@ember/destroyable";
import type Owner from "@ember/owner";
import Modifier, { type ArgsFor } from "ember-modifier";
@@ -11,6 +12,11 @@ import {
/** How far a single arrow key press moves the edge, in pixels. */
const KEYBOARD_STEP = 16;
+/** `Number.isFinite` that also narrows, so a measurement checked here is a `number` after. */
+function isFiniteNumber(value: unknown): value is number {
+ return Number.isFinite(value);
+}
+
/**
* What produced a size report. A consumer that mirrors the size for assistive
* technology needs this: a held arrow key is one gesture spanning every repeat,
@@ -181,7 +187,7 @@ interface DResizeEdgeSignature {
*/
export default class DResizeEdgeModifier extends Modifier<DResizeEdgeSignature> {
/** The options from the most recent invocation, set by `modify`. */
- #named: DResizeEdgeSignature["Args"]["Named"];
+ #namedArgs?: DResizeEdgeSignature["Args"]["Named"];
#onDragStart = (event: PointerEvent) => {
// A pointer taking over closes any key still being held, so the two inputs
@@ -189,7 +195,7 @@ export default class DResizeEdgeModifier extends Modifier<DResizeEdgeSignature>
this.#endKeyboardGesture();
const startValue = this.#read(this.#named.value);
- if (!Number.isFinite(startValue)) {
+ if (!isFiniteNumber(startValue)) {
// Nothing to resize from. Vetoing hands the press back rather than
// starting a gesture whose first report would be `null + delta` clamped
// to a bound, which moves the box somewhere nobody dragged it.
@@ -272,7 +278,7 @@ export default class DResizeEdgeModifier extends Modifier<DResizeEdgeSignature>
// A jump with no bound has nowhere to land. Leave the key to whatever else
// would act on it, as the size check below does.
- let jumpTarget;
+ let jumpTarget: number | undefined;
if (event.key === "Home" || event.key === "End") {
jumpTarget = this.#read(
event.key === "Home" ? this.#named.min : this.#named.max
@@ -286,7 +292,7 @@ export default class DResizeEdgeModifier extends Modifier<DResizeEdgeSignature>
const startValue = this.#read(this.#named.value);
// Checked before the key is claimed: with no size to step from there is
// nothing to handle, so the key belongs to whatever else would act on it.
- if (!Number.isFinite(startValue)) {
+ if (!isFiniteNumber(startValue)) {
return;
}
@@ -301,16 +307,12 @@ export default class DResizeEdgeModifier extends Modifier<DResizeEdgeSignature>
let next;
- switch (event.key) {
- case shrinkKey:
- next = this.#keyboardValue - KEYBOARD_STEP * this.#growthDirection;
- break;
- case growKey:
- next = this.#keyboardValue + KEYBOARD_STEP * this.#growthDirection;
- break;
- default:
- next = jumpTarget;
- break;
+ if (jumpTarget !== undefined) {
+ next = jumpTarget;
+ } else if (event.key === shrinkKey) {
+ next = this.#keyboardValue - KEYBOARD_STEP * this.#growthDirection;
+ } else {
+ next = this.#keyboardValue + KEYBOARD_STEP * this.#growthDirection;
}
this.#keyboardValue = this.#clamp(next);
@@ -331,7 +333,7 @@ export default class DResizeEdgeModifier extends Modifier<DResizeEdgeSignature>
* the keyup with it without the element ever seeing a blur.
*/
#onBlur = () => this.#endKeyboardGesture();
- #element: HTMLElement;
+ #element?: HTMLElement;
#frame?: number;
/** The key holding the current keyboard gesture open, if any. */
@@ -375,13 +377,20 @@ export default class DResizeEdgeModifier extends Modifier<DResizeEdgeSignature>
* The gesture args handed to `registerPointerDrag`. Typed from the engine's own
* args rather than restated, so narrowing one of them cannot leave this behind.
*/
- #gestureArgs: DPointerDragArgs;
+ #gestureArgs?: DPointerDragArgs;
constructor(owner: Owner, args: ArgsFor<DResizeEdgeSignature>) {
super(owner, args);
registerDestructor(this, (instance) => instance.cleanup());
}
+ /** Set by `modify`; every handler that reads it runs after the first invocation. */
+ get #named(): DResizeEdgeSignature["Args"]["Named"] {
+ const named = this.#namedArgs;
+ assert("dResizeEdge: args are read before `modify`", named);
+ return named;
+ }
+
/**
* The multiplier turning pointer movement into a size change.
*
@@ -406,7 +415,9 @@ export default class DResizeEdgeModifier extends Modifier<DResizeEdgeSignature>
// every read forces a style recalculation. `side` and `axis` above stay live
// reads — only the writing direction is held, and it is not something that
// changes while a pointer is down.
- this.#rtl ??= getComputedStyle(this.#element).direction === "rtl";
+ const element = this.#element;
+ assert("dResizeEdge: a gesture ran before `modify`", element);
+ this.#rtl ??= getComputedStyle(element).direction === "rtl";
return logical * (this.#rtl ? -1 : 1);
}
@@ -417,7 +428,7 @@ export default class DResizeEdgeModifier extends Modifier<DResizeEdgeSignature>
named: DResizeEdgeSignature["Args"]["Named"]
) {
this.#element = element;
- this.#named = named;
+ this.#namedArgs = named;
this.#gestureArgs = {
onDragStart: this.#onDragStart,
@@ -435,10 +446,13 @@ export default class DResizeEdgeModifier extends Modifier<DResizeEdgeSignature>
// The gesture engine owns pointer identity, capture, and the primary-button
// gate; this modifier keeps the value semantics and the keyboard path.
- this.#releaseGesture ??= registerPointerDrag(
- element,
- () => this.#gestureArgs
- );
+ this.#releaseGesture ??= registerPointerDrag(element, () => {
+ assert(
+ "dResizeEdge: gesture args are read before `modify`",
+ this.#gestureArgs
+ );
+ return this.#gestureArgs;
+ });
element.addEventListener("keydown", this.#onKeyDown);
element.addEventListener("keyup", this.#onKeyUp);
@@ -522,7 +536,7 @@ export default class DResizeEdgeModifier extends Modifier<DResizeEdgeSignature>
* @param arg - A size, or a function returning one.
* @returns The size in pixels.
*/
- #read(arg: number | (() => number)) {
+ #read<T extends number | null>(arg: T | (() => T)): T {
return typeof arg === "function" ? arg() : arg;
}
diff --git a/frontend/discourse/app/ui-kit/modifiers/d-trap-tab.ts b/frontend/discourse/app/ui-kit/modifiers/d-trap-tab.ts
index f3f68d94be5..2894c621cae 100644
--- a/frontend/discourse/app/ui-kit/modifiers/d-trap-tab.ts
+++ b/frontend/discourse/app/ui-kit/modifiers/d-trap-tab.ts
@@ -1,3 +1,4 @@
+import { assert } from "@ember/debug";
import { registerDestructor } from "@ember/destroyable";
import type Owner from "@ember/owner";
import { service } from "@ember/service";
@@ -127,10 +128,14 @@ export default class DTrapTabModifier extends Modifier<DTrapTabSignature> {
return;
}
+ // The listener is attached in `modify`, after the element is set.
+ const trapElement = this.#element;
+ assert("dTrapTab: Tab was trapped before `modify`", trapElement);
+
const focusableElements = FOCUSABLE_ELEMENTS + ", button:enabled";
const filteredFocusableElements = Array.from(
- this.#element.querySelectorAll<HTMLElement>(focusableElements)
+ trapElement.querySelectorAll<HTMLElement>(focusableElements)
).filter((element) => {
const tabindex = element.getAttribute("tabindex");
return tabindex !== "-1" && canHoldFocus(element);
@@ -149,7 +154,7 @@ export default class DTrapTabModifier extends Modifier<DTrapTabSignature> {
if (document.activeElement === lastFocusableElement) {
event.preventDefault();
(
- this.#element.querySelector<HTMLElement>(".modal-close") ||
+ trapElement.querySelector<HTMLElement>(".modal-close") ||
firstFocusableElement
)?.focus({ preventScroll: this.#preventScroll });
}
diff --git a/frontend/discourse/float-kit/components/d-float-portal.gts b/frontend/discourse/float-kit/components/d-float-portal.gts
index f4147092528..f9a5fff0bd4 100644
--- a/frontend/discourse/float-kit/components/d-float-portal.gts
+++ b/frontend/discourse/float-kit/components/d-float-portal.gts
@@ -1,4 +1,5 @@
import Component from "@glimmer/component";
+import { assert } from "@ember/debug";
import { isTesting } from "discourse/lib/environment";
interface DFloatPortalSignature {
@@ -27,11 +28,18 @@ export default class DFloatPortal extends Component<DFloatPortalSignature> {
return this.args.inline ?? isTesting();
}
+ /** The outlet to teleport into. A missing one means the portal container is not on the page. */
+ get portalOutlet(): HTMLElement {
+ const outlet = this.args.portalOutletElement;
+ assert("DFloatPortal: the portal outlet is missing from the page", outlet);
+ return outlet;
+ }
+
<template>
{{~#if this.inline}}
{{yield}}
{{else}}
- {{#in-element @portalOutletElement insertBefore=null}}
+ {{#in-element this.portalOutlet insertBefore=null}}
{{yield}}
{{/in-element}}
{{/if~}}
diff --git a/frontend/discourse/float-kit/components/d-menu.gts b/frontend/discourse/float-kit/components/d-menu.gts
index 99d011e0785..cea8f0e529d 100644
--- a/frontend/discourse/float-kit/components/d-menu.gts
+++ b/frontend/discourse/float-kit/components/d-menu.gts
@@ -220,7 +220,11 @@ export default class DMenu<Data = unknown> extends Component<
// does not declare but honors at runtime, so the result is cast to a component type
// describing that passthrough.
return (this.args.triggerComponent ||
- curryComponent(DButton, baseArguments, getOwner(this))) as ComponentLike<{
+ curryComponent(
+ DButton,
+ baseArguments,
+ getOwner(this)!
+ )) as ComponentLike<{
Element: HTMLElement;
Args: { componentArgs?: DMenuComponentArgs<Data> };
Blocks: { default: [] };
diff --git a/frontend/discourse/float-kit/lib/constants.ts b/frontend/discourse/float-kit/lib/constants.ts
index 38ce761d156..4b2c3e2b009 100644
--- a/frontend/discourse/float-kit/lib/constants.ts
+++ b/frontend/discourse/float-kit/lib/constants.ts
@@ -333,20 +333,34 @@ export interface ToastData {
[key: string]: unknown;
}
+/**
+ * The progress-bar arguments a toast component receives. The registration
+ * callback is guaranteed whenever a progress bar is shown.
+ */
+type ToastProgressBarArgs =
+ | {
+ /** Whether to show a progress bar counting down to auto-close. */
+ showProgressBar?: false;
+
+ /** Registers the progress-bar element so the auto-close modifier can animate it. */
+ onRegisterProgressBar?: (element: HTMLElement) => void;
+ }
+ | {
+ /** Whether to show a progress bar counting down to auto-close. */
+ showProgressBar: true;
+
+ /** Registers the progress-bar element so the auto-close modifier can animate it. */
+ onRegisterProgressBar: (element: HTMLElement) => void;
+ };
+
/** The arguments a toast component receives (the default is `DDefaultToast`). */
-export interface ToastComponentArgs {
+export type ToastComponentArgs = ToastProgressBarArgs & {
/** The data to render in the toast. */
data?: ToastData;
/** Closes the toast. */
close?: FloatCallback;
-
- /** Whether to show a progress bar counting down to auto-close. */
- showProgressBar?: boolean;
-
- /** Registers the progress-bar element so the auto-close modifier can animate it. */
- onRegisterProgressBar?: (element: HTMLElement) => void;
-}
+};
/** The signature of a toast component (the default is `DDefaultToast`). */
export type ToastComponent = ComponentLike<{
diff --git a/frontend/discourse/float-kit/lib/d-menu-instance.ts b/frontend/discourse/float-kit/lib/d-menu-instance.ts
index 7f00414640f..2ae06c93104 100644
--- a/frontend/discourse/float-kit/lib/d-menu-instance.ts
+++ b/frontend/discourse/float-kit/lib/d-menu-instance.ts
@@ -1,4 +1,5 @@
import { tracked } from "@glimmer/tracking";
+import { assert } from "@ember/debug";
import { isDestroying } from "@ember/destroyable";
import { action } from "@ember/object";
import { guidFor } from "@ember/object/internals";
@@ -50,7 +51,7 @@ export default class DMenuInstance extends FloatKitInstance {
@tracked options: MenuOptions;
@tracked portalOutletOverrideElement?: HTMLElement | null;
- @tracked _trigger: FloatKitTrigger;
+ @tracked _trigger?: FloatKitTrigger;
constructor(owner: Owner, options: Partial<MenuOptions> = {}) {
super();
@@ -70,8 +71,14 @@ export default class DMenuInstance extends FloatKitInstance {
this.portalOutletOverrideElement = options.portalOutletElement;
}
- get trigger() {
- return this._trigger;
+ /**
+ * Set when the trigger registers, which comes before the float can show or
+ * hand out its API. A read before then is a bug, so it asserts.
+ */
+ get trigger(): FloatKitTrigger {
+ const trigger = this._trigger;
+ assert("DMenuInstance: the trigger is read before it registered", trigger);
+ return trigger;
}
set trigger(element: FloatKitTrigger) {
diff --git a/frontend/discourse/float-kit/lib/d-tooltip-instance.ts b/frontend/discourse/float-kit/lib/d-tooltip-instance.ts
index 8e4be2d385e..b6de762a806 100644
--- a/frontend/discourse/float-kit/lib/d-tooltip-instance.ts
+++ b/frontend/discourse/float-kit/lib/d-tooltip-instance.ts
@@ -1,4 +1,5 @@
import { tracked } from "@glimmer/tracking";
+import { assert } from "@ember/debug";
import { action } from "@ember/object";
import { guidFor } from "@ember/object/internals";
import Owner, { setOwner } from "@ember/owner";
@@ -38,7 +39,7 @@ export default class DTooltipInstance extends FloatKitInstance {
@tracked options: TooltipOptions;
@tracked portalOutletOverrideElement?: HTMLElement | null;
- @tracked _trigger: FloatKitTrigger;
+ @tracked _trigger?: FloatKitTrigger;
constructor(owner: Owner, options: Partial<TooltipOptions> = {}) {
super();
@@ -48,8 +49,17 @@ export default class DTooltipInstance extends FloatKitInstance {
this.portalOutletOverrideElement = options.portalOutletElement;
}
- get trigger() {
- return this._trigger;
+ /**
+ * Set when the trigger registers, which comes before the float can show or
+ * hand out its API. A read before then is a bug, so it asserts.
+ */
+ get trigger(): FloatKitTrigger {
+ const trigger = this._trigger;
+ assert(
+ "DTooltipInstance: the trigger is read before it registered",
+ trigger
+ );
+ return trigger;
}
set trigger(element: FloatKitTrigger) {
diff --git a/frontend/discourse/float-kit/lib/float-kit-instance.ts b/frontend/discourse/float-kit/lib/float-kit-instance.ts
index a44eed9180f..02a5a4542e8 100644
--- a/frontend/discourse/float-kit/lib/float-kit-instance.ts
+++ b/frontend/discourse/float-kit/lib/float-kit-instance.ts
@@ -163,7 +163,7 @@ export default abstract class FloatKitInstance {
/** Drops any pending grace-period close, so the float stays open. */
@action
cancelHoverClose() {
- cancel(this.#hoverCloseTimer);
+ cancel(this.#hoverCloseTimer ?? undefined);
this.#hoverCloseTimer = null;
}
diff --git a/frontend/discourse/tests/integration/ui-kit/d-async-content-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-async-content-test.gjs
index f4fe9aed3b0..ab29d4843ab 100644
--- a/frontend/discourse/tests/integration/ui-kit/d-async-content-test.gjs
+++ b/frontend/discourse/tests/integration/ui-kit/d-async-content-test.gjs
@@ -97,6 +97,28 @@ module("Integration | ui-kit | DAsyncContent", function (hooks) {
assert.dom(".content").hasText("data");
});
+ test("it renders the empty block when undefined", async function (assert) {
+ await render(
+ <template>
+ <DAsyncContent @asyncData={{undefined}}>
+ <:loading>
+ <div class="loading">Loading</div>
+ </:loading>
+ <:content>
+ <div class="content">Content</div>
+ </:content>
+ <:empty>
+ <div class="empty">Empty</div>
+ </:empty>
+ </DAsyncContent>
+ </template>
+ );
+
+ assert.dom(".empty").exists("there is nothing to load");
+ assert.dom(".loading").doesNotExist();
+ assert.dom(".content").doesNotExist();
+ });
+
test("it surfaces a synchronous throw", async function (assert) {
const load = () => {
throw new Error("sync failure");
diff --git a/frontend/discourse/type-tests/float-kit/toast-component-args-errors-test.gts b/frontend/discourse/type-tests/float-kit/toast-component-args-errors-test.gts
new file mode 100644
index 00000000000..fe8f6912158
--- /dev/null
+++ b/frontend/discourse/type-tests/float-kit/toast-component-args-errors-test.gts
@@ -0,0 +1,17 @@
+// Negative type assertions for the arguments a toast component receives: every
+// invocation below must fail to compile. They are quarantined here because a
+// Glint error directive suppresses reporting elsewhere in its file. Positives
+// live in toast-component-args-test.gts.
+import DDefaultToast from "discourse/float-kit/components/d-default-toast";
+
+declare const shown: boolean;
+
+const Negatives = <template>
+ {{! @glint-expect-error - a progress bar needs its registration callback }}
+ <DDefaultToast @showProgressBar={{true}} />
+
+ {{! @glint-expect-error - a flag that may be true needs the callback too }}
+ <DDefaultToast @showProgressBar={{shown}} />
+</template>;
+
+export default Negatives;
diff --git a/frontend/discourse/type-tests/float-kit/toast-component-args-test.gts b/frontend/discourse/type-tests/float-kit/toast-component-args-test.gts
new file mode 100644
index 00000000000..792b7849c21
--- /dev/null
+++ b/frontend/discourse/type-tests/float-kit/toast-component-args-test.gts
@@ -0,0 +1,29 @@
+// Positive type assertions for the arguments a toast component receives: every
+// invocation below must compile. Keep this file free of Glint error directives,
+// because one would suppress reporting for the rest of the file. Negatives live
+// in toast-component-args-errors-test.gts.
+import DDefaultToast from "discourse/float-kit/components/d-default-toast";
+
+declare function register(element: HTMLElement): void;
+declare const shown: boolean;
+
+const Positives = <template>
+ {{! A progress bar comes with its registration callback }}
+ <DDefaultToast
+ @onRegisterProgressBar={{register}}
+ @showProgressBar={{true}}
+ />
+
+ {{! Without a progress bar the callback is optional }}
+ <DDefaultToast />
+ <DDefaultToast @showProgressBar={{false}} />
+ <DDefaultToast @onRegisterProgressBar={{register}} />
+
+ {{! A computed flag is fine as long as the callback is there }}
+ <DDefaultToast
+ @onRegisterProgressBar={{register}}
+ @showProgressBar={{shown}}
+ />
+</template>;
+
+export default Positives;