A platform for community discussion. Free, open, simple.
DEV: Type `DButton` actions from `@actionParam` (#44350)
Sérgio Saquetim62b78e48d282
diff --git a/frontend/discourse/app/form-kit/components/fk/submit.gjs b/frontend/discourse/app/form-kit/components/fk/submit.gjsindex 0ebf2ddd2d6..7c86ddc8f62 100644--- a/frontend/discourse/app/form-kit/components/fk/submit.gjs+++ b/frontend/discourse/app/form-kit/components/fk/submit.gjs@@ -13,7 +13,7 @@ export default class FKSubmit extends Component {...attributes@action={{@onSubmit}}@disabled={{@disabled}}- @forwardEvent="true"+ @forwardEvent={{true}}@isLoading={{@isLoading}}@label={{this.label}}/>diff --git a/frontend/discourse/app/ui-kit/d-button.gts b/frontend/discourse/app/ui-kit/d-button.gtsindex 8a98a9313cd..dffa01da3bb 100644--- a/frontend/discourse/app/ui-kit/d-button.gts+++ b/frontend/discourse/app/ui-kit/d-button.gts@@ -1,28 +1,60 @@import Component from "@glimmer/component";import { on } from "@ember/modifier";import { action, computed } from "@ember/object";+import type RouterService from "@ember/routing/router-service";import { next } from "@ember/runloop";import { service } from "@ember/service";import { trustHTML } from "@ember/template";import { isEmpty } from "@ember/utils";+import type { CapabilitiesService } from "discourse/services/capabilities";import { or } from "discourse/truth-helpers";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import dElement from "discourse/ui-kit/helpers/d-element";import dIcon from "discourse/ui-kit/helpers/d-icon";import { i18n } from "discourse-i18n";-type DButtonActionCallback = (...args: unknown[]) => void;--interface DButtonActionObject {- value: DButtonActionCallback;+/** A handler for `@action`, called with the given parameters. */+type DButtonCallback<Params extends unknown[]> = (...params: Params) => void;++/** `@action` as a function, or as an object holding one under `value`. */+type DButtonAction<Params extends unknown[]> =+ | DButtonCallback<Params>+ | { value: DButtonCallback<Params> };++/**+ * `@action` together with `@forwardEvent`. The event reaches the handler only when+ * `@forwardEvent` is true, so a handler that needs it requires the flag. `NoInfer`+ * makes `P` come from `@actionParam` alone, so a handler cannot widen it to a+ * parameter the button never supplies.+ */+type DButtonActionArgs<P> =+ | {+ /** Called on click with `@actionParam`. */+ action?: DButtonAction<[param: NoInfer<P>]>;+ /** Whether `@action` also receives the triggering event. */+ forwardEvent?: false;+ }+ | {+ /** Called on click with `@actionParam` and the triggering event. */+ action?: DButtonAction<[param: NoInfer<P>, event: Event]>;+ /** Whether `@action` also receives the triggering event. */+ forwardEvent: true;+ };++/**+ * Whether the button passes the event to `@action`. Truthiness rather than `=== true`,+ * because callers pass values such as the string `"true"`.+ */+function forwardsEvent<Args extends { forwardEvent?: boolean }>(+ args: Args+): args is Extract<Args, { forwardEvent: true }> {+ return Boolean(args.forwardEvent);}-type DButtonAction = DButtonActionCallback | DButtonActionObject;-type RouteModel = string | number | object;-export interface DButtonSignature {- Args: {+export interface DButtonSignature<P = undefined> {+ Args: DButtonActionArgs<P> & {// Texttitle?: string;translatedTitle?: string;@@ -30,9 +62,8 @@ export interface DButtonSignature {translatedLabel?: string;// Actions / events- action?: DButtonAction;- actionParam?: unknown;- forwardEvent?: boolean;+ /** Passed to `@action` as its first argument. */+ actionParam?: P;onKeyDown?: (event: KeyboardEvent) => void;// Navigation@@ -77,9 +108,11 @@ export interface DButtonSignature {};}-export default class DButton extends Component<DButtonSignature> {- @service router;- @service capabilities;+export default class DButton<P = undefined> extends Component<+ DButtonSignature<P>+> {+ @service declare router: RouterService;+ @service declare capabilities: CapabilitiesService;@computed("args.icon")get btnIcon() {@@ -177,47 +210,51 @@ export default class DButton extends Component<DButtonSignature> {}}+ /**+ * Binds `@action` to this click: `@actionParam`, plus the event when+ * `@forwardEvent` is set. Returns nothing when `@action` holds no handler.+ */+ #bindAction(event: Event): (() => void) | undefined {+ const args = this.args;+ // Optional only so it can be omitted, which leaves `P` as `undefined`.+ const param = args.actionParam as P;++ if (forwardsEvent(args)) {+ const handler = args.action;+ if (typeof handler === "object" && handler.value) {+ return () => handler.value(param, event);+ }+ if (typeof handler === "function") {+ return () => handler(param, event);+ }+ return;+ }++ const handler = args.action;+ if (typeof handler === "object" && handler.value) {+ return () => handler.value(param);+ }+ if (typeof handler === "function") {+ return () => handler(param);+ }+ }+_triggerAction(event: Event) {const { action: actionVal, route, routeModels } = this.args;const isIOS = this.capabilities?.isIOS;if (actionVal || route) {if (actionVal) {- const { actionParam, forwardEvent } = this.args;+ const invoke = this.#bindAction(event);- if (typeof actionVal === "object" && actionVal.value) {- if (isIOS) {- // Don't optimise INP in iOS- // it results in focus events not being triggered- if (forwardEvent) {- actionVal.value(actionParam, event);- } else {- actionVal.value(actionParam);- }- } else {- // Using `next()` to optimise INP- next(() =>- forwardEvent- ? actionVal.value(actionParam, event)- : actionVal.value(actionParam)- );- }- } else if (typeof actionVal === "function") {+ if (invoke) {if (isIOS) {// Don't optimise INP in iOS// it results in focus events not being triggered- if (forwardEvent) {- actionVal(actionParam, event);- } else {- actionVal(actionParam);- }+ invoke();} else {// Using `next()` to optimise INP- next(() =>- forwardEvent- ? actionVal(actionParam, event)- : actionVal(actionParam)- );+ next(invoke);}}} else if (route) {diff --git a/frontend/discourse/app/ui-kit/d-filter-input.gts b/frontend/discourse/app/ui-kit/d-filter-input.gtsindex 3943c611ab6..1b522bb85d4 100644--- a/frontend/discourse/app/ui-kit/d-filter-input.gts+++ b/frontend/discourse/app/ui-kit/d-filter-input.gts@@ -19,7 +19,7 @@ interface DFilterInputSignature {filterAction?: (event: Event) => void;/** Handler fired when the clear button is clicked. */- onClearInput?: (event: Event) => void;+ onClearInput?: () => void;/** Icons displayed inside the input. */icons?: {@@ -69,8 +69,8 @@ export default class DFilterInput extends Component<DFilterInputSignature> {#input?: HTMLInputElement;@action- onClearInput(event: Event) {- this.args.onClearInput?.(event);+ onClearInput() {+ this.args.onClearInput?.();this.#input?.focus();}diff --git a/frontend/discourse/tests/integration/ui-kit/d-button-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-button-test.gjsindex 0294b2539b1..46c8a6151ab 100644--- a/frontend/discourse/tests/integration/ui-kit/d-button-test.gjs+++ b/frontend/discourse/tests/integration/ui-kit/d-button-test.gjs@@ -1,5 +1,8 @@-import { click, render, triggerKeyEvent } from "@ember/test-helpers";+import { hash } from "@ember/helper";+import { click, render, settled, triggerKeyEvent } from "@ember/test-helpers";import { module, test } from "qunit";+import sinon from "sinon";+import { capabilities } from "discourse/services/capabilities";import { setupRenderingTest } from "discourse/tests/helpers/component-test";import DButton from "discourse/ui-kit/d-button";import I18n, { i18n } from "discourse-i18n";@@ -241,6 +244,117 @@ module("Integration | ui-kit | DButton", function (hooks) {assert.strictEqual(this.foo, "bar");});+ module("action dispatch", function (nestedHooks) {+ nestedHooks.beforeEach(function () {+ this.calls = [];+ this.record = (...args) => this.calls.push(args);+ });++ test("dispatches @actionParam as the only argument", async function (assert) {+ const record = this.record;++ await render(+ <template><DButton @action={{record}} @actionParam="topic" /></template>+ );+ await click(".btn");++ assert.deepEqual(this.calls, [["topic"]]);+ });++ test("dispatches undefined when there is no @actionParam", async function (assert) {+ const record = this.record;++ await render(<template><DButton @action={{record}} /></template>);+ await click(".btn");++ assert.deepEqual(this.calls, [[undefined]]);+ });++ test("dispatches the event after @actionParam with @forwardEvent", async function (assert) {+ const record = this.record;++ await render(+ <template>+ <DButton+ @action={{record}}+ @actionParam="topic"+ @forwardEvent={{true}}+ />+ </template>+ );+ await click(".btn");++ assert.strictEqual(this.calls.length, 1);+ assert.strictEqual(this.calls[0][0], "topic");+ assert.true(this.calls[0][1] instanceof MouseEvent, "the click event");+ });++ test("dispatches the event for a truthy non-boolean @forwardEvent", async function (assert) {+ const record = this.record;++ await render(+ <template><DButton @action={{record}} @forwardEvent="true" /></template>+ );+ await click(".btn");++ assert.strictEqual(this.calls.length, 1);+ assert.true(this.calls[0][1] instanceof MouseEvent, "the click event");+ });++ test("dispatches to the value of an object @action", async function (assert) {+ const record = this.record;++ await render(+ <template>+ <DButton @action={{hash value=record}} @actionParam="topic" />+ <DButton+ class="forwarding"+ @action={{hash value=record}}+ @actionParam="draft"+ @forwardEvent={{true}}+ />+ </template>+ );+ await click(".btn:not(.forwarding)");+ await click(".btn.forwarding");++ assert.deepEqual(this.calls[0], ["topic"]);+ assert.strictEqual(this.calls[1][0], "draft");+ assert.true(this.calls[1][1] instanceof MouseEvent, "the click event");+ });++ test("dispatches nothing for an object @action without a value", async function (assert) {+ await render(<template><DButton @action={{hash}} /></template>);+ await click(".btn");++ assert.dom(".btn").exists("the click is handled without throwing");+ });++ test("dispatches after the click on most platforms", async function (assert) {+ sinon.stub(capabilities, "isIOS").value(false);+ const record = this.record;++ await render(<template><DButton @action={{record}} /></template>);+ document.querySelector(".btn").click();++ assert.deepEqual(this.calls, [], "deferred past the click");+ await settled();+ assert.deepEqual(this.calls, [[undefined]]);+ });++ test("dispatches during the click on iOS", async function (assert) {+ sinon.stub(capabilities, "isIOS").value(true);+ const record = this.record;++ await render(+ <template><DButton @action={{record}} @actionParam="topic" /></template>+ );+ document.querySelector(".btn").click();++ assert.deepEqual(this.calls, [["topic"]], "not deferred on iOS");+ });+ });+test("ellipses", async function (assert) {await render(<template>diff --git a/frontend/discourse/type-tests/ui-kit/d-button-action-errors-test.gts b/frontend/discourse/type-tests/ui-kit/d-button-action-errors-test.gtsnew file mode 100644index 00000000000..eca809c7192--- /dev/null+++ b/frontend/discourse/type-tests/ui-kit/d-button-action-errors-test.gts@@ -0,0 +1,42 @@+// Negative type assertions for DButton's `@action` typing: every invocation below+// must fail to compile. They are quarantined here because a Glint error directive+// suppresses reporting elsewhere in its file, which would let a positive pass+// against a broken declaration. Positives live in d-button-action-test.gts.+//+// Each case stays on one line, hence the short names: the strict and non-strict+// projects report a multi-line invocation's error on different lines, and a+// directive only covers the line after it.+import DButton from "discourse/ui-kit/d-button";++interface Topic {+ id: number;+}++interface Draft {+ key: string;+}++declare const topic: Topic;+declare const flag: boolean;+declare function withEvent(topic: Topic, event: Event): void;+declare function readEvent(param: undefined, event: Event): void;+declare function save(draft: Draft): void;++// A handler that needs a parameter while `@actionParam` is omitted is also rejected,+// but only under `strictNullChecks`, where `undefined` stops fitting every type. This+// file is checked by the non-strict project as well, so that case is not asserted here.+const Negatives = <template>+ {{! @glint-expect-error - the handler wants a Draft but @actionParam is a Topic }}+ <DButton @action={{save}} @actionParam={{topic}} />++ {{! @glint-expect-error - the event only arrives with @forwardEvent }}+ <DButton @action={{withEvent}} @actionParam={{topic}} />++ {{! @glint-expect-error - an explicit false still withholds the event }}+ <DButton @action={{readEvent}} @forwardEvent={{false}} />++ {{! @glint-expect-error - a flag that may be false may withhold the event }}+ <DButton @action={{readEvent}} @forwardEvent={{flag}} />+</template>;++export default Negatives;diff --git a/frontend/discourse/type-tests/ui-kit/d-button-action-test.gts b/frontend/discourse/type-tests/ui-kit/d-button-action-test.gtsnew file mode 100644index 00000000000..faff88528ab--- /dev/null+++ b/frontend/discourse/type-tests/ui-kit/d-button-action-test.gts@@ -0,0 +1,46 @@+// Positive type assertions for DButton's `@action` typing: 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+// d-button-action-errors-test.gts.+import { hash } from "@ember/helper";+import DButton from "discourse/ui-kit/d-button";++interface Topic {+ id: number;+}++declare const topic: Topic;+declare function archive(topic: Topic): void;+declare function archiveWithEvent(topic: Topic, event: Event): void;+declare function readEvent(param: undefined, event: Event): void;+declare function refresh(): void;++const Positives = <template>+ {{! @actionParam decides the parameter type }}+ <DButton @action={{archive}} @actionParam={{topic}} />++ {{! @forwardEvent adds the triggering event }}+ <DButton+ @action={{archiveWithEvent}}+ @actionParam={{topic}}+ @forwardEvent={{true}}+ />++ {{! The event can be requested without a parameter }}+ <DButton @action={{readEvent}} @forwardEvent={{true}} />++ {{! A handler may ignore what it is given }}+ <DButton @action={{refresh}} />+ <DButton @action={{refresh}} @actionParam={{topic}} />+ <DButton @action={{refresh}} @forwardEvent={{true}} />+ <DButton @action={{archive}} @actionParam={{topic}} @forwardEvent={{true}} />+ <DButton @action={{archive}} @actionParam={{topic}} @forwardEvent={{false}} />++ {{! The object form follows the same rules }}+ <DButton @action={{hash value=archive}} @actionParam={{topic}} />++ {{! No action at all }}+ <DButton @label="topic.create" />+</template>;++export default Positives;