A platform for community discussion. Free, open, simple.
DEV: Convert four ui-kit primitives to TypeScript (#41623)
Sérgio Saquetim83680d6d781e
diff --git a/frontend/discourse/app/blocks/block-outlet.gjs b/frontend/discourse/app/blocks/block-outlet.gjsindex 233104a2d68..66dad9b359c 100644--- a/frontend/discourse/app/blocks/block-outlet.gjs+++ b/frontend/discourse/app/blocks/block-outlet.gjs@@ -41,7 +41,6 @@ import { validateLayout } from "discourse/lib/blocks/-internals/validation/layouimport { isRailsTesting, isTesting } from "discourse/lib/environment";import { buildArgsWithDeprecations } from "discourse/lib/outlet-args";import { BLOCK_OUTLETS } from "discourse/lib/registry/block-outlets";-/** @type {import("discourse/ui-kit/d-async-content.gjs")} */import DAsyncContent from "discourse/ui-kit/d-async-content";/**diff --git a/frontend/discourse/app/templates/tags/index.gjs b/frontend/discourse/app/templates/tags/index.gjsindex b2ba10b2b80..a11f4583dfa 100644--- a/frontend/discourse/app/templates/tags/index.gjs+++ b/frontend/discourse/app/templates/tags/index.gjs@@ -6,7 +6,7 @@ import TagList from "discourse/components/tag-list";import lazyHash from "discourse/helpers/lazy-hash";import withEventValue from "discourse/helpers/with-event-value";import { not, or } from "discourse/truth-helpers";-import DAsyncContent from "discourse/ui-kit/d-async-content.gjs";+import DAsyncContent from "discourse/ui-kit/d-async-content";import DButton from "discourse/ui-kit/d-button";import DExpandingTextArea from "discourse/ui-kit/d-expanding-text-area";import dDiscourseTags from "discourse/ui-kit/helpers/d-discourse-tags";diff --git a/frontend/discourse/app/ui-kit/d-async-content.gjs b/frontend/discourse/app/ui-kit/d-async-content.gjsdeleted file mode 100644index 7e13ea740c8..00000000000--- a/frontend/discourse/app/ui-kit/d-async-content.gjs+++ /dev/null@@ -1,135 +0,0 @@-import Component from "@glimmer/component";-import { cached } from "@glimmer/tracking";-import { hash } from "@ember/helper";-import { trustHTML } from "@ember/template";-import { TrackedAsyncData } from "ember-async-data";-import { Promise as RsvpPromise } from "rsvp";-import { extractErrorInfo, popupAjaxError } from "discourse/lib/ajax-error";-import discourseDebounce from "discourse/lib/debounce";-import { bind } from "discourse/lib/decorators";-import { INPUT_DELAY } from "discourse/lib/environment";-import { eq } from "discourse/truth-helpers";-import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";-import DFlashMessage from "discourse/ui-kit/d-flash-message";--const ERROR_MODES = ["flash", "popup"];-const DEFAULT_ERROR_MODE = "flash";--export default class DAsyncContent extends Component {- #debounce = false;-- @cached- get data() {- const asyncData = this.args.asyncData;- const context = this.args.context;-- if (this.isDestroying || this.isDestroyed) {- return;- }-- if (asyncData instanceof TrackedAsyncData) {- return asyncData;- }-- let value;-- if (this.#isPromise(asyncData)) {- value = asyncData;- } else if (typeof asyncData === "function") {- value = this.#debounce- ? new Promise((resolve, reject) => {- discourseDebounce(- this,- this.#resolveAsyncData,- asyncData,- context,- resolve,- reject,- this.#debounce- );- })- : this.#resolveAsyncData(asyncData, context);- }-- if (value && !this.#isPromise(value)) {- throw new Error(- `\`<AsyncContent />\` expects @asyncData to be an async function or a promise`- );- }-- return new TrackedAsyncData(value);- }-- get errorMode() {- return this.args.errorMode ?? DEFAULT_ERROR_MODE;- }-- @bind- verifyParameters({ hasErrorBlock }) {- if (hasErrorBlock && this.args.errorMode) {- throw `@errorMode cannot be used when a block named "error" is provided`;- }-- if (this.errorMode && !ERROR_MODES.includes(this.errorMode)) {- throw `@errorMode must be one of \`${ERROR_MODES.join("`, `")}\``;- }- }-- #isPromise(value) {- return value instanceof Promise || value instanceof RsvpPromise;- }-- // a stable reference to a function to use the `debounce` method- #resolveAsyncData(asyncData, context, resolve, reject) {- this.#debounce =- this.args.debounce === true ? INPUT_DELAY : this.args.debounce;-- // when a resolve function is provided, we need to resolve the promise once asyncData is done- // otherwise, we just call asyncData- return resolve- ? asyncData(context).then(resolve).catch(reject)- : asyncData(context);- }-- <template>- {{this.verifyParameters (hash hasErrorBlock=(has-block "error"))}}- {{#if this.data.isPending}}- {{#if (has-block "loading")}}- {{yield to="loading"}}- {{else}}- <DConditionalLoadingSpinner @condition={{this.data.isPending}} />- {{/if}}- {{else if this.data.isResolved}}- {{#if this.data.value}}- {{yield this.data.value to="content"}}- {{else if (has-block "empty")}}- {{yield to="empty"}}- {{else}}- {{yield this.data.value to="content"}}- {{/if}}- {{else if this.data.isRejected}}- {{#if (has-block "error")}}- {{yield- this.data.error- (component AsyncContentInlineError error=this.data.error)- to="error"- }}- {{else if (eq this.errorMode "flash")}}- <AsyncContentInlineError @error={{this.data.error}} />- {{else if (eq this.errorMode "popup")}}- {{popupAjaxError this.data.error}}- {{/if}}- {{/if}}- </template>-}--class AsyncContentInlineError extends Component {- get errorMessage() {- const errorInfo = extractErrorInfo(this.args.error);- return errorInfo.html ? trustHTML(errorInfo.message) : errorInfo.message;- }-- <template>- <DFlashMessage role="alert" @flash={{this.errorMessage}} @type="error" />- </template>-}diff --git a/frontend/discourse/app/ui-kit/d-async-content.gts b/frontend/discourse/app/ui-kit/d-async-content.gtsnew file mode 100644index 00000000000..097ca7ce857--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-async-content.gts@@ -0,0 +1,241 @@+import Component from "@glimmer/component";+import { cached } from "@glimmer/tracking";+import { hash } from "@ember/helper";+import { type TrustedHTML, trustHTML } from "@ember/template";+import type { WithBoundArgs } from "@glint/template";+import { TrackedAsyncData } from "ember-async-data";+import { Promise as RsvpPromise } from "rsvp";+import { extractErrorInfo, popupAjaxError } from "discourse/lib/ajax-error";+import discourseDebounce from "discourse/lib/debounce";+import { bind } from "discourse/lib/decorators";+import { INPUT_DELAY } from "discourse/lib/environment";+import { eq } from "discourse/truth-helpers";+import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";+import DFlashMessage from "discourse/ui-kit/d-flash-message";++const ERROR_MODES = ["flash", "popup"];+const DEFAULT_ERROR_MODE = "flash";++type ErrorMode = "flash" | "popup";++/**+ * A function data source. It receives the `@context` value and returns either+ * the resolved value directly (a client-only data source) or a promise for it.+ */+type AsyncDataFn<T> = (context: unknown) => T | Promise<T>;++interface DAsyncContentSignature<T> {+ Args: {+ /**+ * The source of the data to render. One of:+ * - a `Promise` that resolves to the value;+ * - an already-constructed `TrackedAsyncData`, when the caller manages the+ * async state itself;+ * - a function returning the value, or a promise for it, re-invoked+ * whenever the tracked state it reads (including `@context`) changes.+ */+ asyncData: Promise<T> | TrackedAsyncData<T> | AsyncDataFn<T>;++ /**+ * A value forwarded to the function form of `@asyncData`. It is tracked, so+ * updating it re-invokes the function and reloads the data. Pass the+ * reactive state the data source depends on here to refresh the content+ * when that state changes.+ */+ context?: unknown;++ /**+ * Whether to debounce re-invocations of the function form of `@asyncData`,+ * so rapidly changing input does not refetch on every change. `true` uses+ * the default input delay; a number sets the delay in milliseconds.+ */+ debounce?: boolean | number;++ /**+ * How a rejection is surfaced when no `error` block is provided. Cannot be+ * combined with an `error` block.+ */+ errorMode?: ErrorMode;+ };++ Blocks: {+ /**+ * Rendered while the data is pending. When omitted, a loading spinner is+ * shown in its place.+ */+ loading: [];++ /** Rendered once the data resolves. */+ content: [+ /** The resolved value. */+ value: T,+ ];++ /** Rendered in place of `content` when the resolved value is falsy. */+ empty: [];++ /**+ * Rendered when the data rejects. When omitted, the rejection is handled+ * according to `@errorMode`.+ */+ error: [+ /** The rejection reason. */+ error: Error,++ /**+ * A component, pre-bound to the error, that renders the default inline+ * error message.+ */+ retry: WithBoundArgs<typeof AsyncContentInlineError, "error">,+ ];+ };+}++export default class DAsyncContent<T> extends Component<+ DAsyncContentSignature<T>+> {+ #debounce: boolean | number | undefined = false;++ @cached+ get data(): TrackedAsyncData<T> | undefined {+ const asyncData = this.args.asyncData;+ const context = this.args.context;++ if (this.isDestroying || this.isDestroyed) {+ return;+ }++ if (asyncData instanceof TrackedAsyncData) {+ return asyncData;+ }++ let value: T | Promise<T> | Promise<void> | undefined;++ if (this.#isPromise(asyncData)) {+ value = asyncData;+ } else if (typeof asyncData === "function") {+ value = this.#debounce+ ? new Promise<T>((resolve, reject) => {+ discourseDebounce(+ this,+ this.#resolveAsyncData,+ asyncData,+ context,+ resolve,+ reject,+ this.#debounce+ );+ })+ : this.#resolveAsyncData(asyncData, context);+ }++ if (value && !this.#isPromise(value)) {+ throw new Error(+ `\`<AsyncContent />\` expects @asyncData to be an async function or a promise`+ );+ }++ // 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`.+ return new TrackedAsyncData(value as T | Promise<T>);+ }++ // The rejection reason. `TrackedAsyncData` types `error` as `unknown`; the+ // rejected state carries the rejection reason, surfaced to the `:error` block+ // and the inline error display as `Error` (matching what consumers expect).+ get rejection(): Error {+ return this.data?.error as Error;+ }++ get errorMode(): ErrorMode {+ return this.args.errorMode ?? DEFAULT_ERROR_MODE;+ }++ @bind+ verifyParameters({ hasErrorBlock }: { hasErrorBlock: boolean }) {+ if (hasErrorBlock && this.args.errorMode) {+ throw `@errorMode cannot be used when a block named "error" is provided`;+ }++ if (this.errorMode && !ERROR_MODES.includes(this.errorMode)) {+ throw `@errorMode must be one of \`${ERROR_MODES.join("`, `")}\``;+ }+ }++ #isPromise(value: unknown): value is Promise<T> {+ return value instanceof Promise || value instanceof RsvpPromise;+ }++ // a stable reference to a function to use the `debounce` method+ #resolveAsyncData(+ asyncData: AsyncDataFn<T>,+ context: unknown,+ resolve?: (value: T | PromiseLike<T>) => void,+ reject?: (reason?: unknown) => void+ ): T | Promise<T> | Promise<void> {+ this.#debounce =+ this.args.debounce === true ? INPUT_DELAY : this.args.debounce;++ // when a resolve function is provided, we need to resolve the promise once asyncData is done+ // otherwise, we just call asyncData+ //+ // The debounced path only runs against async data sources, so the result is+ // cast to `Promise<T>` to settle the outer promise via `.then`/`.catch`.+ return resolve+ ? (asyncData(context) as Promise<T>).then(resolve).catch(reject)+ : asyncData(context);+ }++ <template>+ {{this.verifyParameters (hash hasErrorBlock=(has-block "error"))}}+ {{#if this.data.isPending}}+ {{#if (has-block "loading")}}+ {{yield to="loading"}}+ {{else}}+ <DConditionalLoadingSpinner @condition={{this.data.isPending}} />+ {{/if}}+ {{else if this.data.isResolved}}+ {{#if this.data.value}}+ {{yield this.data.value to="content"}}+ {{else if (has-block "empty")}}+ {{yield to="empty"}}+ {{else}}+ {{yield this.data.value to="content"}}+ {{/if}}+ {{else if this.data.isRejected}}+ {{#if (has-block "error")}}+ {{yield+ this.rejection+ (component AsyncContentInlineError error=this.rejection)+ to="error"+ }}+ {{else if (eq this.errorMode "flash")}}+ <AsyncContentInlineError @error={{this.rejection}} />+ {{else if (eq this.errorMode "popup")}}+ {{popupAjaxError this.rejection}}+ {{/if}}+ {{/if}}+ </template>+}++interface AsyncContentInlineErrorSignature {+ Args: {+ error: Error;+ };+}++class AsyncContentInlineError extends Component<AsyncContentInlineErrorSignature> {+ get errorMessage(): string | TrustedHTML {+ // `extractErrorInfo` is authored in untyped `.js`; annotate the fields we+ // read so the getter's return type stays precise rather than widening to `any`.+ const errorInfo: { html: boolean; message: string } = extractErrorInfo(+ this.args.error+ );+ return errorInfo.html ? trustHTML(errorInfo.message) : errorInfo.message;+ }++ <template>+ <DFlashMessage role="alert" @flash={{this.errorMessage}} @type="error" />+ </template>+}diff --git a/frontend/discourse/app/ui-kit/d-button.gts b/frontend/discourse/app/ui-kit/d-button.gtsindex dd194165bc3..c5c51f59ed7 100644--- a/frontend/discourse/app/ui-kit/d-button.gts+++ b/frontend/discourse/app/ui-kit/d-button.gts@@ -69,7 +69,6 @@ interface DButtonSignature {class?: string;};- // Root element type (enables ...attributes type checking)Element: HTMLButtonElement;// Optional yielddiff --git a/frontend/discourse/app/ui-kit/d-conditional-loading-spinner.gjs b/frontend/discourse/app/ui-kit/d-conditional-loading-spinner.gjsdeleted file mode 100644index acfdb0a9396..00000000000--- a/frontend/discourse/app/ui-kit/d-conditional-loading-spinner.gjs+++ /dev/null@@ -1,30 +0,0 @@-import PluginOutlet from "discourse/components/plugin-outlet";-import lazyHash from "discourse/helpers/lazy-hash";-import { eq } from "discourse/truth-helpers";-import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";--const DConditionalLoadingSpinner = <template>- <PluginOutlet- @name="conditional-loading-spinner"- @defaultGlimmer={{true}}- @outletArgs={{lazyHash condition=@condition size=@size}}- >- <div- class={{dConcatClass- "loading-container"- (if @condition "visible")- (if (eq @size "small") "inline-spinner")- }}- data-loading={{@condition}}- ...attributes- >- {{#if @condition}}- <div class="spinner {{@size}}"></div>- {{else}}- {{yield}}- {{/if}}- </div>- </PluginOutlet>-</template>;--export default DConditionalLoadingSpinner;diff --git a/frontend/discourse/app/ui-kit/d-conditional-loading-spinner.gts b/frontend/discourse/app/ui-kit/d-conditional-loading-spinner.gtsnew file mode 100644index 00000000000..75402237c9f--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-conditional-loading-spinner.gts@@ -0,0 +1,49 @@+import type { TemplateOnlyComponent } from "@ember/component/template-only";+import PluginOutlet from "discourse/components/plugin-outlet";+import lazyHash from "discourse/helpers/lazy-hash";+import { eq } from "discourse/truth-helpers";+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";++interface DConditionalLoadingSpinnerSignature {+ Args: {+ /** Whether the content is still loading. */+ condition?: boolean;++ /** The spinner size. */+ size?: string;+ };++ Element: HTMLDivElement;++ Blocks: {+ /** The content to reveal once loading has finished. */+ default: [];+ };+}++const DConditionalLoadingSpinner: TemplateOnlyComponent<DConditionalLoadingSpinnerSignature> =+ <template>+ <PluginOutlet+ @name="conditional-loading-spinner"+ @defaultGlimmer={{true}}+ @outletArgs={{lazyHash condition=@condition size=@size}}+ >+ <div+ class={{dConcatClass+ "loading-container"+ (if @condition "visible")+ (if (eq @size "small") "inline-spinner")+ }}+ data-loading={{@condition}}+ ...attributes+ >+ {{#if @condition}}+ <div class="spinner {{@size}}"></div>+ {{else}}+ {{yield}}+ {{/if}}+ </div>+ </PluginOutlet>+ </template>;++export default DConditionalLoadingSpinner;diff --git a/frontend/discourse/app/ui-kit/d-filter-input.gjs b/frontend/discourse/app/ui-kit/d-filter-input.gtssimilarity index 63%rename from frontend/discourse/app/ui-kit/d-filter-input.gjsrename to frontend/discourse/app/ui-kit/d-filter-input.gtsindex 664ab97ad86..be9f997228f 100644--- a/frontend/discourse/app/ui-kit/d-filter-input.gjs+++ b/frontend/discourse/app/ui-kit/d-filter-input.gts@@ -10,14 +10,46 @@ import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import dIcon from "discourse/ui-kit/helpers/d-icon";import { i18n } from "discourse-i18n";-export default class DFilterInput extends Component {+interface DFilterInputSignature {+ Args: {+ /** The current input value. */+ value?: string;++ /** Handler fired on each `input` event. */+ filterAction?: (event: Event) => void;++ /** Handler fired when the clear button is clicked. */+ onClearInput?: (event: Event) => void;++ /** Icons displayed inside the input. */+ icons?: {+ /** ID of the icon displayed at the start of the input. */+ left?: string;++ /** ID of the icon displayed at the end of the input. */+ right?: string;+ };++ /** Extra class applied to the container wrapping the input. */+ containerClass?: string;+ };++ Element: HTMLInputElement;++ Blocks: {+ /** Content rendered inside the container, after the input. */+ default: [];+ };+}++export default class DFilterInput extends Component<DFilterInputSignature> {@tracked isFocused = false;- registerInput = modifier((element) => {- this.input = element;+ registerInput = modifier((element: HTMLInputElement) => {+ this.#input = element;});- focusState = modifier((element) => {+ focusState = modifier((element: HTMLInputElement) => {const focusInHandler = () => {this.isFocused = true;};@@ -34,10 +66,12 @@ export default class DFilterInput extends Component {};});+ #input?: HTMLInputElement;+@action- onClearInput(event) {- this.args.onClearInput(event);- this.input?.focus();+ onClearInput(event: Event) {+ this.args.onClearInput?.(event);+ this.#input?.focus();}<template>diff --git a/frontend/discourse/app/ui-kit/d-flash-message.gjs b/frontend/discourse/app/ui-kit/d-flash-message.gjsdeleted file mode 100644index ba6dfe97b2e..00000000000--- a/frontend/discourse/app/ui-kit/d-flash-message.gjs+++ /dev/null@@ -1,21 +0,0 @@-import Component from "@glimmer/component";-import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";--const FLASH_TYPES = ["success", "error", "warning", "info"];--export default class DFlashMessage extends Component {- get flashClass() {- if (this.args.type && !FLASH_TYPES.includes(this.args.type)) {- throw `@type must be one of ${FLASH_TYPES.join(", ")}`;- }- return this.args.type ? `alert-${this.args.type}` : null;- }-- <template>- {{#if @flash}}- <div class={{dConcatClass "alert" this.flashClass}} ...attributes>- {{~@flash~}}- </div>- {{/if}}- </template>-}diff --git a/frontend/discourse/app/ui-kit/d-flash-message.gts b/frontend/discourse/app/ui-kit/d-flash-message.gtsnew file mode 100644index 00000000000..de2bd7a85a4--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-flash-message.gts@@ -0,0 +1,36 @@+import Component from "@glimmer/component";+import type { TrustedHTML } from "@ember/template";+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";++const FLASH_TYPES = ["success", "error", "warning", "info"] as const;++export type FlashType = (typeof FLASH_TYPES)[number];++interface DFlashMessageSignature {+ Args: {+ /** The message to display. Accepts a plain string or trusted HTML. */+ flash?: string | TrustedHTML;++ /** The severity of the message. */+ type?: FlashType;+ };++ Element: HTMLDivElement;+}++export default class DFlashMessage extends Component<DFlashMessageSignature> {+ get flashClass() {+ if (this.args.type && !FLASH_TYPES.includes(this.args.type)) {+ throw `@type must be one of ${FLASH_TYPES.join(", ")}`;+ }+ return this.args.type ? `alert-${this.args.type}` : null;+ }++ <template>+ {{#if @flash}}+ <div class={{dConcatClass "alert" this.flashClass}} ...attributes>+ {{~@flash~}}+ </div>+ {{/if}}+ </template>+}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.gjsindex f99e5bbc359..cb6f8c11626 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@@ -9,7 +9,6 @@ import { modifier } from "ember-modifier";import withEventValue from "discourse/helpers/with-event-value";import { ajax } from "discourse/lib/ajax";import { eq } from "discourse/truth-helpers";-/** @type {import("discourse/ui-kit/d-async-content.gjs")} */import DAsyncContent from "discourse/ui-kit/d-async-content";import DFilterInput from "discourse/ui-kit/d-filter-input";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";@@ -292,7 +291,6 @@ export default class DIconGridPickerContent extends Component {><div class="d-icon-grid-picker__filter-container"><DFilterInput- {{! @glint-expect-error: FilterInput lacks Element type declaration }}aria-label={{i18n "d_icon_grid_picker.search_placeholder"}}aria-controls="d-icon-grid-picker-listbox"placeholder={{i18n "d_icon_grid_picker.search_placeholder"}}