A platform for community discussion. Free, open, simple.
DEV: Add `registerReviewableComponent` plugin API (#42508)
David Taylor7f1f91377b81
diff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex 4da9cc5e9fb..4e8e332d6ba 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -931,6 +931,7 @@ en:date_filter: "Posted between"in_reply_to: "in reply to"filtered_flagged_by: "Flagged by"+ no_component_found: "No component found for %{type}"unknown:title:one: "You have pending review queue items from disabled plugin:"diff --git a/frontend/discourse/app/components/reviewable/index.gjs b/frontend/discourse/app/components/reviewable/index.gjsindex 0c43d9b7d66..855cc60b207 100644--- a/frontend/discourse/app/components/reviewable/index.gjs+++ b/frontend/discourse/app/components/reviewable/index.gjs@@ -1,60 +1,35 @@-import Component from "@glimmer/component";-import { getOwner } from "@ember/owner";-import { dasherize } from "@ember/string";import ReviewFilters from "discourse/components/review-filters";import ReviewableItem from "discourse/components/reviewable/item";-import { bind } from "discourse/lib/decorators";import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";import DLoadMore from "discourse/ui-kit/d-load-more";import { i18n } from "discourse-i18n";-export default class ReviewIndexRefresh extends Component {- @bind- reviewableComponentExists(reviewable) {- const owner = getOwner(this);- // TODO plugins are still using `reviewable-refresh/` path. Once they are fixed, it can be remove.- let dasherized = dasherize(reviewable.type).replace(- "reviewable-",- "reviewable-refresh/"- );- if (owner.hasRegistration(`component:${dasherized}`)) {- return true;- }-- dasherized = dasherize(reviewable.type).replace(- "reviewable-",- "reviewable/"- );- return owner.hasRegistration(`component:${dasherized}`);- }-- <template>- <div class="reviewable-container">- <ReviewFilters @controller={{@controller}} />- <div class="reviewable-list">- {{#if @controller.reviewables.content}}- <DLoadMore @action={{@controller.loadMore}}>- <div class="reviewables">- {{#each @controller.reviewables.content as |r|}}- {{#if (this.reviewableComponentExists r)}}- <ReviewableItem- @reviewable={{r}}- @showHelp={{false}}- @updateStatuses={{@controller.updateStatuses}}- />- {{/if}}- {{/each}}- </div>- </DLoadMore>- <DConditionalLoadingSpinner- @condition={{@controller.reviewables.loadingMore}}- />- {{else}}- <div class="no-review">- {{i18n "review.none"}}+const ReviewableIndex = <template>+ <div class="reviewable-container">+ <ReviewFilters @controller={{@controller}} />+ <div class="reviewable-list">+ {{#if @controller.reviewables.content}}+ <DLoadMore @action={{@controller.loadMore}}>+ <div class="reviewables">+ {{#each @controller.reviewables.content as |r|}}+ <ReviewableItem+ @reviewable={{r}}+ @showHelp={{false}}+ @updateStatuses={{@controller.updateStatuses}}+ />+ {{/each}}</div>- {{/if}}- </div>+ </DLoadMore>+ <DConditionalLoadingSpinner+ @condition={{@controller.reviewables.loadingMore}}+ />+ {{else}}+ <div class="no-review">+ {{i18n "review.none"}}+ </div>+ {{/if}}</div>- </template>-}+ </div>+</template>;++export default ReviewableIndex;diff --git a/frontend/discourse/app/components/reviewable/item.gjs b/frontend/discourse/app/components/reviewable/item.gjsindex 85e9c170d13..6893c4cd690 100644--- a/frontend/discourse/app/components/reviewable/item.gjs+++ b/frontend/discourse/app/components/reviewable/item.gjs@@ -1,7 +1,7 @@/* eslint-disable ember/no-classic-components */import { tracked } from "@glimmer/tracking";import Component from "@ember/component";-import { concat, fn } from "@ember/helper";+import { fn, get } from "@ember/helper";import { on } from "@ember/modifier";import { action, computed, set } from "@ember/object";import { getOwner } from "@ember/owner";@@ -19,6 +19,11 @@ import ReviewableTimeline from "discourse/components/reviewable/timeline";import ReviewableBundledAction from "discourse/components/reviewable-bundled-action";import ReviewableClaimedTopic from "discourse/components/reviewable-claimed-topic";import ReviewableCreatedBy from "discourse/components/reviewable-created-by";+import ReviewableFieldCategory from "discourse/components/reviewable-field-category";+import ReviewableFieldEditor from "discourse/components/reviewable-field-editor";+import ReviewableFieldTags from "discourse/components/reviewable-field-tags";+import ReviewableFieldText from "discourse/components/reviewable-field-text";+import ReviewableFieldTextarea from "discourse/components/reviewable-field-textarea";import editableValue from "discourse/helpers/editable-value";import { newReviewableStatus } from "discourse/helpers/reviewable-status";import { ajax } from "discourse/lib/ajax";@@ -27,6 +32,7 @@ import { bind } from "discourse/lib/decorators";import { getAbsoluteURL } from "discourse/lib/get-url";import optionalService from "discourse/lib/optional-service";import { showAlert } from "discourse/lib/post-action-feedback";+import { resolveReviewableComponent } from "discourse/lib/reviewable-registry";import { clipboardCopy } from "discourse/lib/utilities";import Category from "discourse/models/category";import Composer from "discourse/models/composer";@@ -34,6 +40,7 @@ import { PENDING } from "discourse/models/reviewable";import { CLAIMED, UNCLAIMED } from "discourse/models/reviewable-history";import Topic from "discourse/models/topic";import { eq, not } from "discourse/truth-helpers";+import DAsyncContent from "discourse/ui-kit/d-async-content";import DButton from "discourse/ui-kit/d-button";import DHorizontalOverflowNav from "discourse/ui-kit/d-horizontal-overflow-nav";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";@@ -42,7 +49,13 @@ import dFormatDate from "discourse/ui-kit/helpers/d-format-date";import dIcon from "discourse/ui-kit/helpers/d-icon";import { i18n } from "discourse-i18n";-let _components = {};+const fieldComponents = {+ category: ReviewableFieldCategory,+ editor: ReviewableFieldEditor,+ tags: ReviewableFieldTags,+ text: ReviewableFieldText,+ textarea: ReviewableFieldTextarea,+};export const pluginReviewableParams = {};const reviewableTypeLabels = {};@@ -84,10 +97,6 @@ export function registerReviewableTypeLabel(reviewableType, labelKey) {reviewableTypeLabels[reviewableType] = labelKey;}-function lookupComponent(context, name) {- return getOwner(context).resolveRegistration(`component:${name}`);-}-@tagName("")export default class ReviewableItem extends Component {@service dialog;@@ -131,6 +140,11 @@ export default class ReviewableItem extends Component {}}+ @bind+ resolveReviewableComponent(type) {+ return resolveReviewableComponent(getOwner(this), type);+ }+@computed("reviewable.type","reviewable.last_performing_username",@@ -249,35 +263,6 @@ export default class ReviewableItem extends Component {return this.siteSettings?.reviewable_claiming !== "required";}- // Find a component to render, if one exists. For example:- // `ReviewableUser` will return `reviewable/user` or `reviewable-user`.- // The former is the new reviewable component, so will only be returned if it exists.- @computed("reviewable.type")- get reviewableComponent() {- if (_components[this.reviewable?.type] !== undefined) {- return _components[this.reviewable?.type];- }-- const owner = getOwner(this);- const dasherized = dasherize(this.reviewable?.type);- const componentNames = [- dasherized.replace("reviewable-", "reviewable-refresh/"),- dasherized.replace("reviewable-", "reviewable/"),- dasherized,- ];-- for (const componentName of componentNames) {- const componentExists =- owner.hasRegistration(`component:${componentName}`) ||- owner.hasRegistration(`template:components/${componentName}`);- if (componentExists) {- _components[this.reviewable?.type] = componentName;- break;- }- }- return _components[this.reviewable?.type] || null;- }-@computed("_updates.category_id", "reviewable.category.id")get tagCategoryId() {return this._updates?.category_id || this.reviewable?.category?.id;@@ -755,10 +740,7 @@ export default class ReviewableItem extends Component {<div class="editable-fields">{{#each this.reviewable.editable_fields as |f|}}<div class="editable-field {{dDasherize f.id}}">- {{#let- (lookupComponent this (concat "reviewable-field-" f.type))- as |FieldComponent|- }}+ {{#let (get fieldComponents f.type) as |FieldComponent|}}<FieldComponent@tagName=""@value={{editableValue this.reviewable f.id}}@@ -771,16 +753,25 @@ export default class ReviewableItem extends Component {{{/each}}</div>{{else}}-- {{#let- (lookupComponent this this.reviewableComponent)- as |ReviewableComponent|- }}- <ReviewableComponent- @reviewable={{this.reviewable}}- @tagName=""- />- {{/let}}+ <DAsyncContent+ @asyncData={{this.resolveReviewableComponent}}+ @context={{this.reviewable.type}}+ >+ <:content as |ReviewableComponent|>+ <ReviewableComponent+ @reviewable={{this.reviewable}}+ @tagName=""+ />+ </:content>+ <:empty>+ <div class="alert alert-error review-item__no-component">+ {{i18n+ "review.no_component_found"+ type=this.reviewable.type+ }}+ </div>+ </:empty>+ </DAsyncContent>{{/if}}</div>diff --git a/frontend/discourse/app/lib/plugin-api.gjs b/frontend/discourse/app/lib/plugin-api.gjsindex a9d289e8a90..930a97675e0 100644--- a/frontend/discourse/app/lib/plugin-api.gjs+++ b/frontend/discourse/app/lib/plugin-api.gjs@@ -2464,6 +2464,43 @@ class _PluginApi {registerReviewableActionModal(reviewableType, modalClass);}+ /**+ * Registers the component used to render a reviewable type in the review queue.+ *+ * The loader returns the component class, or a promise resolving to it — in+ * which case the module is only loaded when a reviewable of that type is+ * rendered.+ *+ * @param {String} reviewableType - The reviewable type class name (e.g. "ReviewableChatMessage")+ * @param {Function} loader - A function returning the component class, or a promise+ * resolving to it+ *+ * @example+ * ```+ * api.registerReviewableComponent("ReviewableChatMessage", () => ReviewableChatMessage);+ * ```+ *+ * @example+ * ```+ * api.registerReviewableComponent(+ * "ReviewableChatMessage",+ * async () => (await import("../components/reviewable/chat-message")).default+ * );+ * ```+ **/+ registerReviewableComponent(reviewableType, loader) {+ if (typeof loader !== "function") {+ throw new Error(+ `registerReviewableComponent("${reviewableType}", ...) requires a function as second argument.`+ );+ }++ this.registerValueTransformer(+ "reviewable-component",+ ({ value, context }) => (context.type === reviewableType ? loader : value)+ );+ }+/*** Register custom status names for a reviewable type, used in the* review queue status badge (e.g. "Tool approved" instead of "Flag approved").diff --git a/frontend/discourse/app/lib/registry/transformers.js b/frontend/discourse/app/lib/registry/transformers.jsindex d1284601ec6..a6454058c84 100644--- a/frontend/discourse/app/lib/registry/transformers.js+++ b/frontend/discourse/app/lib/registry/transformers.js@@ -127,6 +127,7 @@ export const VALUE_TRANSFORMERS = Object.freeze(["poster-name-user-title","preferences-save-attributes","quote-params",+ "reviewable-component","route-to-url","sidebar-anonymous-default-categories","site-setting-allows-none",diff --git a/frontend/discourse/app/lib/reviewable-registry.js b/frontend/discourse/app/lib/reviewable-registry.jsnew file mode 100644index 00000000000..23869d680e9--- /dev/null+++ b/frontend/discourse/app/lib/reviewable-registry.js@@ -0,0 +1,69 @@+import { dasherize } from "@ember/string";+import ReviewableFlaggedPost from "discourse/components/reviewable/flagged-post";+import ReviewablePost from "discourse/components/reviewable/post";+import ReviewableQueuedPost from "discourse/components/reviewable/queued-post";+import ReviewableUser from "discourse/components/reviewable/user";+import deprecated from "discourse/lib/deprecated";+import { applyValueTransformer } from "discourse/lib/transformer";++const coreLoaders = {+ ReviewableFlaggedPost: () => ReviewableFlaggedPost,+ ReviewablePost: () => ReviewablePost,+ ReviewableQueuedPost: () => ReviewableQueuedPost,+ ReviewableUser: () => ReviewableUser,+};++function registeredLoaderFor(type) {+ return applyValueTransformer(+ "reviewable-component",+ coreLoaders[type] ?? null,+ { type }+ );+}++// Fallback for plugins that ship a component at a conventional path instead of+// registering it via `api.registerReviewableComponent`. Only works when the+// plugin's modules are eagerly define()d.+function legacyComponentName(owner, type) {+ const dasherized = dasherize(type);+ const componentNames = [+ dasherized.replace("reviewable-", "reviewable-refresh/"),+ dasherized.replace("reviewable-", "reviewable/"),+ dasherized,+ ];++ return componentNames.find(+ (name) =>+ owner.hasRegistration(`component:${name}`) ||+ owner.hasRegistration(`template:components/${name}`)+ );+}++/**+ * Resolves the component used to render the given reviewable type.+ *+ * Returns the component class directly when it is available synchronously, or+ * a promise resolving to it when the type was registered with an async loader.+ *+ * @param {import("@ember/owner").default} owner+ * @param {string} type - The reviewable type class name (e.g. "ReviewableUser")+ * @returns {unknown | Promise<unknown> | null}+ */+export function resolveReviewableComponent(owner, type) {+ const loader = registeredLoaderFor(type);++ if (loader) {+ return loader();+ }++ const name = legacyComponentName(owner, type);+ if (name) {+ deprecated(+ `Reviewable components must be registered with api.registerReviewableComponent ("${type}" was resolved from the "${name}" module path)`,+ { id: "discourse.reviewable.legacy-component-lookup" }+ );+ return owner.resolveRegistration(`component:${name}`);+ }++ return null;+}diff --git a/frontend/discourse/app/templates/review/show.gjs b/frontend/discourse/app/templates/review/show.gjsindex 58cc68017ac..6d456c88ce6 100644--- a/frontend/discourse/app/templates/review/show.gjs+++ b/frontend/discourse/app/templates/review/show.gjs@@ -1,42 +1,16 @@-import Component from "@glimmer/component";-import { getOwner } from "@ember/owner";import { LinkTo } from "@ember/routing";-import { dasherize } from "@ember/string";import ReviewableItem from "discourse/components/reviewable/item";import dIcon from "discourse/ui-kit/helpers/d-icon";import { i18n } from "discourse-i18n";-export default class extends Component {- // TODO plugins are still using `reviewable-refresh/` path. Once they are fixed, it can be remove.- get reviewableComponentExists() {- const owner = getOwner(this);- let dasherized = dasherize(this.args.controller.reviewable.type).replace(- "reviewable-",- "reviewable-refresh/"- );- if (owner.hasRegistration(`component:${dasherized}`)) {- return true;- }+const ReviewShow = <template>+ <div class="reviewable-top-nav">+ <LinkTo @route="review.index">+ {{dIcon "arrow-left"}}+ {{i18n "review.back_to_queue"}}+ </LinkTo>+ </div>+ <ReviewableItem @reviewable={{@controller.reviewable}} @showHelp={{true}} />+</template>;- dasherized = dasherize(this.args.controller.reviewable.type).replace(- "reviewable-",- "reviewable/"- );- return owner.hasRegistration(`component:${dasherized}`);- }-- <template>- {{#if this.reviewableComponentExists}}- <div class="reviewable-top-nav">- <LinkTo @route="review.index">- {{dIcon "arrow-left"}}- {{i18n "review.back_to_queue"}}- </LinkTo>- </div>- <ReviewableItem- @reviewable={{@controller.reviewable}}- @showHelp={{true}}- />- {{/if}}- </template>-}+export default ReviewShow;diff --git a/frontend/discourse/tests/integration/components/reviewable/item-test.gjs b/frontend/discourse/tests/integration/components/reviewable/item-test.gjsindex f90a71002d3..dbf998f9943 100644--- a/frontend/discourse/tests/integration/components/reviewable/item-test.gjs+++ b/frontend/discourse/tests/integration/components/reviewable/item-test.gjs@@ -2,6 +2,7 @@ import { getOwner } from "@ember/owner";import { render } from "@ember/test-helpers";import { module, test } from "qunit";import ReviewableItem from "discourse/components/reviewable/item";+import { withPluginApi } from "discourse/lib/plugin-api";import { APPROVED, PENDING } from "discourse/models/reviewable";import { CLAIMED, UNCLAIMED } from "discourse/models/reviewable-history";import { setupRenderingTest } from "discourse/tests/helpers/component-test";@@ -207,4 +208,73 @@ module("Integration | Component | Reviewable | Item", function (hooks) {"the server only logs claims on pending reviewables");});++ test("renders a component registered via the plugin API", async function (assert) {+ const CustomComponent = <template>+ <div class="custom-reviewable">{{@reviewable.type}}</div>+ </template>;++ withPluginApi((api) => {+ api.registerReviewableComponent(+ "ReviewableCustomThing",+ () => CustomComponent+ );+ });++ const customReviewable = {+ id: 987,+ type: "ReviewableCustomThing",+ topic: null,+ reviewable_scores: [],+ };++ await render(+ <template><ReviewableItem @reviewable={{customReviewable}} /></template>+ );++ assert.dom(".custom-reviewable").hasText("ReviewableCustomThing");+ });++ test("shows an error when no component exists for the reviewable type", async function (assert) {+ const unknownReviewable = {+ id: 988,+ type: "ReviewableMissingThing",+ topic: null,+ reviewable_scores: [],+ };++ await render(+ <template><ReviewableItem @reviewable={{unknownReviewable}} /></template>+ );++ assert+ .dom(".review-item__no-component")+ .hasText("No component found for ReviewableMissingThing");+ });++ test("renders a lazily loaded component registered via the plugin API", async function (assert) {+ const CustomComponent = <template>+ <div class="custom-reviewable">{{@reviewable.type}}</div>+ </template>;++ withPluginApi((api) => {+ api.registerReviewableComponent(+ "ReviewableCustomThing",+ async () => CustomComponent+ );+ });++ const customReviewable = {+ id: 987,+ type: "ReviewableCustomThing",+ topic: null,+ reviewable_scores: [],+ };++ await render(+ <template><ReviewableItem @reviewable={{customReviewable}} /></template>+ );++ assert.dom(".custom-reviewable").hasText("ReviewableCustomThing");+ });});diff --git a/plugins/chat/assets/javascripts/discourse/initializers/chat-setup.js b/plugins/chat/assets/javascripts/discourse/initializers/chat-setup.jsindex 7976c29e0d4..459cec209d7 100644--- a/plugins/chat/assets/javascripts/discourse/initializers/chat-setup.js+++ b/plugins/chat/assets/javascripts/discourse/initializers/chat-setup.js@@ -32,6 +32,12 @@ class ChatSetupInit {this.appEvents.on("discourse:focus-changed", this, "_handleFocusChanged");withPluginApi((api) => {+ api.registerReviewableComponent(+ "ReviewableChatMessage",+ async () =>+ (await import("../components/reviewable/chat-message")).default+ );+api.addAboutPageActivity("chat_messages", (periods) => {const count = periods["7_days"];if (count) {diff --git a/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-reviewable-status.js b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-reviewable-status.jsindex 97411672085..af0572bf28e 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-reviewable-status.js+++ b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-reviewable-status.js@@ -10,6 +10,21 @@ export default {"approved_tool_action","rejected_tool_action");++ api.registerReviewableComponent(+ "ReviewableAiChatMessage",+ async () =>+ (await import("../components/reviewable/ai-chat-message")).default+ );+ api.registerReviewableComponent(+ "ReviewableAiPost",+ async () => (await import("../components/reviewable/ai-post")).default+ );+ api.registerReviewableComponent(+ "ReviewableAiToolAction",+ async () =>+ (await import("../components/reviewable/ai-tool-action")).default+ );});},};diff --git a/plugins/discourse-post-voting/assets/javascripts/discourse/api-initializers/post-voting-reviewables.js b/plugins/discourse-post-voting/assets/javascripts/discourse/api-initializers/post-voting-reviewables.jsnew file mode 100644index 00000000000..72f3b9ed0c4--- /dev/null+++ b/plugins/discourse-post-voting/assets/javascripts/discourse/api-initializers/post-voting-reviewables.js@@ -0,0 +1,9 @@+import { apiInitializer } from "discourse/lib/api";++export default apiInitializer((api) => {+ api.registerReviewableComponent(+ "ReviewablePostVotingComment",+ async () =>+ (await import("../components/reviewable/post-voting-comment")).default+ );+});