A platform for community discussion. Free, open, simple.
DEV: Cancel superseded requests and add retainWhileReloading to d-async-content (#41634)
Sérgio Saquetim3af83540b027
diff --git a/frontend/discourse/app/ui-kit/d-async-content.gts b/frontend/discourse/app/ui-kit/d-async-content.gtsindex 097ca7ce857..867bd455de4 100644--- a/frontend/discourse/app/ui-kit/d-async-content.gts+++ b/frontend/discourse/app/ui-kit/d-async-content.gts@@ -19,10 +19,21 @@ 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.+ * A function data source, re-invoked whenever the tracked state it reads+ * (including `@context`) changes. Returns the value or a promise for it.*/-type AsyncDataFn<T> = (context: unknown) => T | Promise<T>;+type AsyncDataFn<T> = (+ /** The value passed through `@context`. */+ context: unknown,+ /** Per-call values passed alongside `@context`. */+ options: {+ /**+ * Aborted when a later call supersedes this one. Forward it to your request+ * (e.g. `fetch`) to cancel the superseded work; ignoring it is fine.+ */+ signal: AbortSignal;+ }+) => T | Promise<T>;interface DAsyncContentSignature<T> {Args: {@@ -31,8 +42,7 @@ interface DAsyncContentSignature<T> {* - 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.+ * - an `AsyncDataFn` that produces the value on demand.*/asyncData: Promise<T> | TrackedAsyncData<T> | AsyncDataFn<T>;@@ -51,6 +61,12 @@ interface DAsyncContentSignature<T> {*/debounce?: boolean | number;+ /**+ * Keep rendering the previously resolved value while a subsequent load is+ * pending, rather than reverting to the loading state.+ */+ retainWhileReloading?: boolean;+/*** How a rejection is surfaced when no `error` block is provided. Cannot be* combined with an `error` block.@@ -95,6 +111,72 @@ export default class DAsyncContent<T> extends Component<DAsyncContentSignature<T>> {#debounce: boolean | number | undefined = false;+ #abortController: AbortController | null = null;++ // The value from the most recent resolution, kept so we can keep rendering it+ // while a *subsequent* load is pending (opt-in via `@retainWhileReloading`).+ // Plain fields, not tracked: they are written from within the `resolution`+ // getter and only read back when the next load is pending, so they never need+ // to drive their own invalidation.+ #lastResolvedValue: T | undefined = undefined;+ #hasResolvedOnce = false;++ willDestroy(): void {+ super.willDestroy();+ this.#abortController?.abort();+ }++ /**+ * Resolves the current async state into a single render mode. Collapsing the+ * states into one getter (rather than branching on `data.isPending` /+ * `isResolved` directly in the template) lets the `:content` block stay+ * mounted across a pending→resolved transition when retaining: both phases+ * report `mode: "content"`, so Glimmer keeps the same DOM and the yielded+ * value simply updates in place.+ */+ @cached+ get resolution(): {+ mode: "idle" | "loading" | "content" | "error";+ value?: T;+ error?: Error;+ } {+ const data = this.data;++ if (!data) {+ return { mode: "idle" };+ }++ if (data.isResolved) {+ // Remember the resolved value so a later pending phase can keep showing+ // it. These are plain, untracked fields — writing them mid-computation+ // can't dirty a tag or trigger a re-render loop, which is what the+ // no-side-effects rule guards against.+ // `TrackedAsyncData` types `value` as `T | null`; in the resolved state it+ // is the resolved `T`, and a falsy value is routed to the `:empty` block,+ // so the `:content` block yields `T`.+ /* eslint-disable ember/no-side-effects */+ this.#lastResolvedValue = data.value as T;+ this.#hasResolvedOnce = true;+ /* eslint-enable ember/no-side-effects */+ return { mode: "content", value: data.value as T };+ }++ if (data.isRejected) {+ // `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 of that chain expect).+ return { mode: "error", error: data.error as Error };+ }++ // Pending. When the consumer opts into `@retainWhileReloading`, keep showing+ // the last resolved value so the content subtree isn't unmounted on a reload+ // (useful when long-lived component state lives inside the `:content` block).+ if ((this.args.retainWhileReloading ?? false) && this.#hasResolvedOnce) {+ return { mode: "content", value: this.#lastResolvedValue };+ }++ return { mode: "loading" };+ }@cachedget data(): TrackedAsyncData<T> | undefined {@@ -109,6 +191,11 @@ export default class DAsyncContent<T> extends Component<return asyncData;}+ // Each (re)computation supersedes the previous fetch: abort the prior request so a+ // stale response is cancelled at the network layer, not merely ignored on render.+ // Consumers opt in by honoring the `signal` passed to their async function.+ const signal = this.#supersedeRequest();+let value: T | Promise<T> | Promise<void> | undefined;if (this.#isPromise(asyncData)) {@@ -121,33 +208,26 @@ export default class DAsyncContent<T> extends Component<this.#resolveAsyncData,asyncData,context,+ signal,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`- );+ : this.#resolveAsyncData(asyncData, context, signal);}+ // A function may return a synchronous value (a client-only data source) rather+ // than a promise. `TrackedAsyncData` resolves a non-promise synchronously, so such+ // 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`.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;}@@ -167,53 +247,72 @@ export default class DAsyncContent<T> extends Component<return value instanceof Promise || value instanceof RsvpPromise;}+ // Aborts the previous fetch's controller and mints a fresh one, returning its+ // signal. Kept out of the `data` getter body so the (benign, untracked) mutation+ // isn't a computed side-effect.+ #supersedeRequest(): AbortSignal {+ this.#abortController?.abort();+ this.#abortController = new AbortController();+ return this.#abortController.signal;+ }+// a stable reference to a function to use the `debounce` method#resolveAsyncData(asyncData: AsyncDataFn<T>,context: unknown,+ signal: AbortSignal,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 async function receives an AbortSignal as a second arg so it can cancel an+ // in-flight request when superseded; existing zero/one-arg functions ignore it.+ // When a resolve fn is provided (the debounced path) we settle the outer promise;+ // otherwise we return the function's result directly (a promise OR a sync value).//// 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);+ ? (asyncData(context, { signal }) as Promise<T>)+ .then(resolve)+ .catch(reject)+ : asyncData(context, { signal });}<template>{{this.verifyParameters (hash hasErrorBlock=(has-block "error"))}}- {{#if this.data.isPending}}+ {{#if (eq this.resolution.mode "loading")}}{{#if (has-block "loading")}}{{yield to="loading"}}{{else}}- <DConditionalLoadingSpinner @condition={{this.data.isPending}} />+ <DConditionalLoadingSpinner @condition={{true}} />{{/if}}- {{else if this.data.isResolved}}- {{#if this.data.value}}- {{yield this.data.value to="content"}}+ {{else if (eq this.resolution.mode "content")}}+ {{#if this.resolution.value}}+ {{yield this.resolution.value to="content"}}{{else if (has-block "empty")}}{{yield to="empty"}}{{else}}- {{yield this.data.value to="content"}}+ {{yield this.resolution.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}}+ {{else if (eq this.resolution.mode "error")}}+ {{! In error mode the resolution error is always present; this guard+ narrows it from a possibly-undefined value to a definite error for the+ yields and arguments below. }}+ {{#if this.resolution.error}}+ {{#if (has-block "error")}}+ {{yield+ this.resolution.error+ (component AsyncContentInlineError error=this.resolution.error)+ to="error"+ }}+ {{else if (eq this.errorMode "flash")}}+ <AsyncContentInlineError @error={{this.resolution.error}} />+ {{else if (eq this.errorMode "popup")}}+ {{popupAjaxError this.resolution.error}}+ {{/if}}{{/if}}{{/if}}</template>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.gjsindex 32fc8fb8938..ff6a22b455b 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@@ -2,7 +2,7 @@ import Component from "@glimmer/component";import { tracked } from "@glimmer/tracking";import { on } from "@ember/modifier";import { action } from "@ember/object";-import { click, render, waitFor } from "@ember/test-helpers";+import { click, render, settled, waitFor } from "@ember/test-helpers";import { TrackedAsyncData } from "ember-async-data";import { module, test } from "qunit";import { Promise as RsvpPromise } from "rsvp";@@ -446,4 +446,162 @@ module("Integration | ui-kit | DAsyncContent", function (hooks) {assert.dom(".error").doesNotExist();});});++ module("@retainWhileReloading", function () {+ test("keeps the resolved content mounted while a later load is pending", async function (assert) {+ let buildCount = 0;+ let resolveSecond;+ let host;++ // Counts constructions so we can prove the content subtree is not torn+ // down and rebuilt across a reload.+ class CountingContent extends Component {+ constructor() {+ super(...arguments);+ buildCount++;+ }++ <template>+ <div class="counting-content">{{@value}}</div>+ </template>+ }++ class Host extends Component {+ // Start already-resolved so the initial render settles without us+ // having to await a pending promise. Reassigned from the test body via+ // the captured `host` reference, which the lint rule can't see.+ // eslint-disable-next-line discourse/no-unnecessary-tracked+ @tracked asyncData = Promise.resolve("v1");++ constructor() {+ super(...arguments);+ // Captured so the test can swap `asyncData` directly.+ host = this;+ }++ <template>+ <DAsyncContent+ @asyncData={{this.asyncData}}+ @retainWhileReloading={{true}}+ >+ <:loading>+ <div class="provided-loading"></div>+ </:loading>+ <:content as |value|>+ <CountingContent @value={{value}} />+ </:content>+ </DAsyncContent>+ </template>+ }++ await render(<template><Host /></template>);+ assert.dom(".counting-content").hasText("v1", "first value renders");+ assert.strictEqual(buildCount, 1, "content built once initially");++ // Reload with a promise that stays pending across a render. We poll the+ // DOM with `waitFor` rather than awaiting `settled`/`rerender`, which+ // would block on the pending `TrackedAsyncData`'s async waiter.+ host.asyncData = new Promise((resolve) => (resolveSecond = resolve));+ await waitFor(".counting-content");++ // Because the content is retained (never unmounted for the loading+ // state), `waitFor` finds it immediately and no loading block renders.+ assert+ .dom(".provided-loading")+ .doesNotExist("no loading state on reload");+ assert+ .dom(".counting-content")+ .hasText("v1", "previous content retained while pending");+ assert.strictEqual(+ buildCount,+ 1,+ "content instance is not rebuilt during the pending reload"+ );++ resolveSecond("v2");+ await settled();++ assert.dom(".counting-content").hasText("v2", "new value swaps in");+ assert.strictEqual(+ buildCount,+ 1,+ "content instance survived the reload (not torn down)"+ );+ });+ });++ module("synchronous sources and cancellation", function () {+ test("a synchronous return renders content with no loading phase", async function (assert) {+ const load = () => ["a", "b"];++ await render(+ <template>+ <DAsyncContent @asyncData={{load}}>+ <:loading><div class="the-loading"></div></:loading>+ <:content as |rows|>+ <div class="the-content">{{rows.length}}</div>+ </:content>+ </DAsyncContent>+ </template>+ );++ assert+ .dom(".the-loading")+ .doesNotExist("a synchronous value never shows the loading state");+ assert+ .dom(".the-content")+ .hasText("2", "the synchronous value renders immediately as content");+ });++ test("passes an AbortSignal and aborts the prior request when the context changes", async function (assert) {+ const signals = [];++ class Host extends Component {+ @tracked term = "a";++ // Records each call's signal so we can assert the superseded request is+ // aborted. Resolves immediately so `settled` never blocks on a waiter.+ load = (context, { signal }) => {+ signals.push(signal);+ return Promise.resolve([]);+ };++ @action+ retype() {+ this.term = "ab";+ }++ <template>+ <button+ class="retype"+ type="button"+ {{on "click" this.retype}}+ >x</button>+ <DAsyncContent @asyncData={{this.load}} @context={{this.term}}>+ <:content as |v|>{{v.length}}</:content>+ </DAsyncContent>+ </template>+ }++ await render(<template><Host /></template>);+ assert.strictEqual(+ signals.length,+ 1,+ "the async function receives a signal"+ );+ assert.false(signals[0].aborted, "the first request starts un-aborted");++ await click(".retype");+ assert.strictEqual(+ signals.length,+ 2,+ "a context change starts a new request"+ );+ assert.true(+ signals[0].aborted,+ "the superseded request's signal is aborted"+ );+ assert.false(signals[1].aborted, "the latest request stays active");+ });+ });});