A platform for community discussion. Free, open, simple.
UX: Move AI category and tag suggestions inline into the composer choosers (#40838)
chapoie8d615b1a22c
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/connectors/after-composer-category-input/ai-category-suggestion.gjs b/plugins/discourse-ai/assets/javascripts/discourse/connectors/after-composer-category-input/ai-category-suggestion.gjsdeleted file mode 100644index 8474895dcaa..00000000000--- a/plugins/discourse-ai/assets/javascripts/discourse/connectors/after-composer-category-input/ai-category-suggestion.gjs+++ /dev/null@@ -1,26 +0,0 @@-import Component from "@glimmer/component";-import { service } from "@ember/service";-import AiCategorySuggester from "../../components/suggestion-menus/ai-category-suggester";-import { showComposerAiHelper } from "../../lib/show-ai-helper";--export default class AiCategorySuggestion extends Component {- static shouldRender(args, context) {- return showComposerAiHelper(- args?.composer,- context.siteSettings,- context.currentUser,- "suggestions"- );- }-- @service composer;-- <template>- {{#unless this.composer.disableCategoryChooser}}- <AiCategorySuggester- @composer={{@outletArgs.composer}}- @topicState="new"- />- {{/unless}}- </template>-}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/connectors/after-composer-tag-input/ai-tag-suggestion.gjs b/plugins/discourse-ai/assets/javascripts/discourse/connectors/after-composer-tag-input/ai-tag-suggestion.gjsdeleted file mode 100644index 69bbb2bbc7d..00000000000--- a/plugins/discourse-ai/assets/javascripts/discourse/connectors/after-composer-tag-input/ai-tag-suggestion.gjs+++ /dev/null@@ -1,18 +0,0 @@-import Component from "@glimmer/component";-import AiTagSuggester from "../../components/suggestion-menus/ai-tag-suggester";-import { showComposerAiHelper } from "../../lib/show-ai-helper";--export default class AiTagSuggestion extends Component {- static shouldRender(args, context) {- return showComposerAiHelper(- args?.composer,- context.siteSettings,- context.currentUser,- "suggestions"- );- }-- <template>- <AiTagSuggester @composer={{@outletArgs.composer}} @topicState="new" />- </template>-}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-category-chooser-inline-suggester.js b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-category-chooser-inline-suggester.jsnew file mode 100644index 00000000000..fd0dbc68f91--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-category-chooser-inline-suggester.js@@ -0,0 +1,144 @@+import { getOwner } from "@ember/owner";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import { withPluginApi } from "discourse/lib/plugin-api";+import { i18n } from "discourse-i18n";+import { MIN_CHARACTER_COUNT } from "../lib/ai-helper-suggestions";+import { showComposerAiHelper } from "../lib/show-ai-helper";++const SUGGEST_ID = "ai-category-suggest";++const STATE = new WeakMap();++function stateFor(component) {+ let state = STATE.get(component);+ if (!state) {+ state = { loading: false };+ STATE.set(component, state);+ }+ return state;+}++function composerFor(component) {+ return getOwner(component).lookup("service:composer");+}++// only attach to the composer's own chooser, not every category-chooser+// elsewhere in the app while a draft happens to be open+function inComposer(component) {+ return !!component.element?.closest("#reply-control");+}++function noSuggestionsToast(component) {+ getOwner(component)+ .lookup("service:toasts")+ .error({+ duration: "short",+ data: {+ message: i18n("discourse_ai.ai_helper.suggest_errors.no_suggestions"),+ },+ });+}++async function applyBestSuggestion(component, selectKit) {+ const composer = composerFor(component);+ const text = composer?.model?.reply;+ const state = stateFor(component);++ if (!text || text.length < MIN_CHARACTER_COUNT) {+ noSuggestionsToast(component);+ return;+ }++ const startCategoryId = composer.model.categoryId;+ state.loading = true;+ selectKit.close();+ selectKit.set("isLoading", true);++ try {+ const { assistant } = await ajax(+ "/discourse-ai/ai-helper/suggest_category",+ { method: "POST", data: { text } }+ );++ if (component.isDestroying || component.isDestroyed) {+ return;+ }++ if (composer.model.categoryId !== startCategoryId) {+ return;+ }++ const best = (assistant || [])[0];+ if (best) {+ selectKit.select(best.id, { id: best.id, name: best.name });+ } else {+ noSuggestionsToast(component);+ }+ } catch (error) {+ popupAjaxError(error);+ } finally {+ state.loading = false;+ if (!component.isDestroying && !component.isDestroyed) {+ selectKit.set("isLoading", false);+ }+ }+}++function triggerRow(component) {+ return {+ id: SUGGEST_ID,+ name: i18n("discourse_ai.ai_helper.choose"),+ icon: "discourse-sparkles",+ classNames: "ai-category-suggest-row",+ onSelect: (selectKit) => applyBestSuggestion(component, selectKit),+ };+}++function enabledFor(component, siteSettings, currentUser) {+ const composer = composerFor(component);+ return (+ siteSettings.ai_embeddings_enabled &&+ composer?.model &&+ !composer.disableCategoryChooser &&+ inComposer(component) &&+ showComposerAiHelper(+ composer.model,+ siteSettings,+ currentUser,+ "suggestions"+ )+ );+}++function hasEnoughContent(component) {+ return (+ (composerFor(component)?.model?.reply?.length ?? 0) > MIN_CHARACTER_COUNT+ );+}++function initInlineCategorySuggester(api) {+ const currentUser = api.getCurrentUser();+ const siteSettings = api.container.lookup("service:site-settings");++ api.modifySelectKit("category-chooser").prependContent((component) => {+ if (!enabledFor(component, siteSettings, currentUser)) {+ return;+ }++ if (component.selectKit.filter) {+ return;+ }++ if (!stateFor(component).loading && hasEnoughContent(component)) {+ return triggerRow(component);+ }+ });+}++export default {+ name: "ai-category-chooser-inline-suggester",+ initialize() {+ withPluginApi(initInlineCategorySuggester);+ },+};diff --git a/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-tag-chooser-inline-suggester.js b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-tag-chooser-inline-suggester.jsnew file mode 100644index 00000000000..8df5edda0d9--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-tag-chooser-inline-suggester.js@@ -0,0 +1,211 @@+import { getOwner } from "@ember/owner";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import { withPluginApi } from "discourse/lib/plugin-api";+import { i18n } from "discourse-i18n";+import {+ MIN_CHARACTER_COUNT,+ tagSuggestionParams,+} from "../lib/ai-helper-suggestions";+import { showComposerAiHelper } from "../lib/show-ai-helper";++const SUGGEST_ID = "ai-tag-suggest";+const EXIT_ID = "ai-tag-exit";++const STATE = new WeakMap();++function stateFor(component) {+ let state = STATE.get(component);+ if (!state) {+ state = { mode: "idle", suggestions: [] };+ STATE.set(component, state);+ }+ return state;+}++function reset(component) {+ const state = stateFor(component);+ state.mode = "idle";+ state.suggestions = [];+}++function composerFor(component) {+ return getOwner(component).lookup("service:composer");+}++// only attach to the composer's own chooser, not every mini-tag-chooser+// elsewhere in the app while a draft happens to be open+function inComposer(component) {+ return !!component.element?.closest("#reply-control");+}++function noSuggestionsToast(component) {+ getOwner(component)+ .lookup("service:toasts")+ .error({+ duration: "short",+ data: {+ message: i18n("discourse_ai.ai_helper.suggest_errors.no_suggestions"),+ },+ });+}++function selectedTagNames(component) {+ const tags = composerFor(component)?.model?.tags ?? [];+ return tags.map((t) => (typeof t === "string" ? t : t.name));+}++async function loadSuggestions(component, selectKit) {+ const composer = composerFor(component);+ const model = composer?.model;+ const text = model?.reply;+ const state = stateFor(component);++ if (!text || text.length < MIN_CHARACTER_COUNT) {+ noSuggestionsToast(component);+ return;+ }++ state.mode = "loading";+ selectKit.triggerSearch();++ try {+ const { assistant } = await ajax("/discourse-ai/ai-helper/suggest_tags", {+ method: "POST",+ data: { text, ...tagSuggestionParams(model.categoryId, model.tags) },+ });++ if (component.isDestroying || component.isDestroyed) {+ return;+ }++ state.suggestions = assistant || [];+ state.mode = state.suggestions.length ? "results" : "idle";++ if (!state.suggestions.length) {+ noSuggestionsToast(component);+ }+ } catch (error) {+ state.mode = "idle";+ popupAjaxError(error);+ } finally {+ if (!component.isDestroying && !component.isDestroyed) {+ selectKit.triggerSearch();+ }+ }+}++function triggerRow(component) {+ return {+ id: SUGGEST_ID,+ name: i18n("discourse_ai.ai_helper.suggest"),+ icon: "discourse-sparkles",+ classNames: "ai-tag-suggest-row",+ onSelect: (selectKit) => loadSuggestions(component, selectKit),+ };+}++function loadingRow() {+ return {+ id: SUGGEST_ID,+ name: i18n("discourse_ai.ai_helper.context_menu.loading"),+ icon: "spinner",+ classNames: "ai-tag-suggest-row",+ onSelect: () => {},+ };+}++function exitRow(component) {+ return {+ id: EXIT_ID,+ name: i18n("discourse_ai.ai_helper.suggestions"),+ icon: "xmark",+ classNames: "ai-tag-exit-row",+ onSelect: (selectKit) => {+ reset(component);+ selectKit.triggerSearch();+ },+ };+}++function enabledFor(component, siteSettings, currentUser) {+ const composer = composerFor(component);+ return (+ siteSettings.ai_embeddings_enabled &&+ composer?.model &&+ !composer.disableTagsChooser &&+ inComposer(component) &&+ showComposerAiHelper(+ composer.model,+ siteSettings,+ currentUser,+ "suggestions"+ )+ );+}++function hasEnoughContent(component) {+ return (+ (composerFor(component)?.model?.reply?.length ?? 0) > MIN_CHARACTER_COUNT+ );+}++function initInlineTagSuggester(api) {+ const currentUser = api.getCurrentUser();+ const siteSettings = api.container.lookup("service:site-settings");++ api.modifySelectKit("mini-tag-chooser").prependContent((component) => {+ if (!enabledFor(component, siteSettings, currentUser)) {+ return;+ }++ if (component.selectKit.filter) {+ reset(component);+ return;+ }++ if (stateFor(component).mode === "idle" && hasEnoughContent(component)) {+ return triggerRow(component);+ }+ });++ api.modifySelectKit("mini-tag-chooser").replaceContent((component) => {+ if (!enabledFor(component, siteSettings, currentUser)) {+ return;+ }++ if (component.selectKit.filter) {+ return;+ }++ const state = stateFor(component);++ if (state.mode === "loading") {+ return [loadingRow()];+ }++ if (state.mode === "results") {+ const taken = selectedTagNames(component);+ const remaining = state.suggestions.filter(+ (s) => !taken.includes(s.name)+ );+ return [+ exitRow(component),+ ...remaining.map((s) => ({ id: s.name, name: s.name, count: s.count })),+ ];+ }+ });++ api.modifySelectKit("mini-tag-chooser").onChange((component) => {+ if (stateFor(component).mode === "results") {+ component.selectKit.triggerSearch();+ }+ });+}++export default {+ name: "ai-tag-chooser-inline-suggester",+ initialize() {+ withPluginApi(initInlineTagSuggester);+ },+};diff --git a/plugins/discourse-ai/assets/stylesheets/modules/ai-helper/common/ai-helper.scss b/plugins/discourse-ai/assets/stylesheets/modules/ai-helper/common/ai-helper.scssindex e73ca484e69..2515cf019e0 100644--- a/plugins/discourse-ai/assets/stylesheets/modules/ai-helper/common/ai-helper.scss+++ b/plugins/discourse-ai/assets/stylesheets/modules/ai-helper/common/ai-helper.scss@@ -243,27 +243,6 @@#edit-title {padding-right: 2em;}-- .category-chooser {- .select-kit-header-wrapper {- padding-right: 1.5em;- }- }-- .mini-tag-chooser {- .multi-select-header {- padding-right: 2em;- }- }-- .select-kit.is-expanded {- // need to raise the z-index so the sibling input buttons don't cover the dropdown- z-index: z("dropdown") + 1;-- + button {- z-index: z("dropdown") + 1;- }- }}.suggestion-button {@@ -291,6 +270,24 @@}}+.suggest-titles-button {+ #reply-control & {+ background: var(--primary-low);+ right: var(--space-1);+ top: 50%;+ transform: translateY(+ calc(-50% - 0.25em)+ ); // .25em = half of input margin-bottom padding+ border-radius: var(--d-input-border-radius); // to match surrounding input+ padding: 0.4em;+ font-size: var(--font-down-1-rem);++ .d-icon {+ color: var(--tertiary);+ }+ }+}+#reply-control {.composer-actions.is-expanded,.composer-popup {@@ -300,34 +297,6 @@z-index: z("composer", "dropdown") + 2;}- .with-category .showing-ai-suggestions .category-input {- flex-wrap: nowrap;- max-width: calc(50% - 0.2em);-- .category-chooser {- min-width: 0;- flex: 1 1 auto;- }- }-- .with-category:not(.with-tags) {- // when tagging is disabled- .showing-ai-suggestions .category-input {- max-width: 40%;- }- }-- .with-tags {- .showing-ai-suggestions .tags-input {- display: flex;- max-width: calc(50% - 0.2em);-- .mini-tag-chooser {- min-width: 0;- }- }- }-.showing-ai-suggestions {#reply-title {padding-right: 2em;@@ -383,10 +352,6 @@}}-.suggest-tags-button + .ai-suggestions-menu {- top: 4.25rem;-}-@keyframes spin {0% {transform: rotate(0deg);@@ -744,3 +709,63 @@}}}++// new inline AI helper+.select-kit.mini-tag-chooser .select-kit-row,+.select-kit.category-chooser .select-kit-row {+ &.ai-category-suggest-row,+ &.ai-tag-suggest-row,+ &.ai-tag-exit-row {+ position: sticky;+ top: 0;+ z-index: z("dropdown") + 1;+ flex-direction: row;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-1);+ font-size: var(--font-down-1-rem);+ border-bottom: 1px solid var(--primary-low);+ background: var(--secondary);++ .name {+ margin: 0;+ font-size: var(--font-0); // unset+ }++ .d-icon {+ color: var(--tertiary);+ }+ }++ &.ai-tag-exit-row {+ font-weight: bold;+ }++ &.ai-category-suggest-row,+ &.ai-tag-suggest-row {+ color: var(--primary-medium);+ font-style: italic;++ .d-icon-spinner {+ animation: spin 1s linear infinite;+ }+ }+}++.select-kit.category-chooser.is-loading:not(.is-expanded) {+ .select-kit-header .angle-icon {+ display: none;+ }++ .select-kit-header-wrapper::after {+ content: "";+ align-self: center;+ margin-left: auto;+ width: 0.9em;+ height: 0.9em;+ border: 2px solid var(--primary-low-mid);+ border-right-color: transparent;+ border-radius: 50%;+ animation: spin 1s linear infinite;+ }+}diff --git a/plugins/discourse-ai/assets/stylesheets/modules/ai-helper/mobile/ai-helper.scss b/plugins/discourse-ai/assets/stylesheets/modules/ai-helper/mobile/ai-helper.scssindex d12bfa27ee1..219abc2115a 100644--- a/plugins/discourse-ai/assets/stylesheets/modules/ai-helper/mobile/ai-helper.scss+++ b/plugins/discourse-ai/assets/stylesheets/modules/ai-helper/mobile/ai-helper.scss@@ -42,33 +42,9 @@}}-#topic-title .edit-topic-title.showing-ai-suggestions {- .category-chooser {- flex: 1 1 90%;- }-- .ai-category-suggester-trigger {- padding: 0.425em;- }-- .ai-tag-suggester-trigger {- padding: 0.45em;- }-}-.ios-device #topic-title .edit-topic-title.showing-ai-suggestions button {&.ai-title-suggester-trigger {padding-top: 0.4em;padding-bottom: 0.4em;}-- &.ai-category-suggester-trigger {- padding-top: 0.4em;- padding-bottom: 0.25em;- }-- &.ai-tag-suggester-trigger {- padding-top: 0.4em;- padding-bottom: 0.3em;- }}diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.ymlindex 2f29362a975..38b7f11cc3b 100644--- a/plugins/discourse-ai/config/locales/client.en.yml+++ b/plugins/discourse-ai/config/locales/client.en.yml@@ -1054,7 +1054,9 @@ en:title: "Suggest changes using AI"description: "Choose one of the options below, and the AI will suggest you a new version of the text."selection_hint: "Hint: You can also select a portion of the text before opening the helper to rewrite only that."- suggest: "Suggest with AI"+ suggest: "Show AI suggestions"+ choose: "Choose for me"+ suggestions: "Suggestions"suggest_errors:too_many_tags:one: "You can only have up to %{count} tag"diff --git a/plugins/discourse-ai/spec/system/ai_helper/ai_composer_helper_spec.rb b/plugins/discourse-ai/spec/system/ai_helper/ai_composer_helper_spec.rbindex 2f2a94c236a..4a86d175fb3 100644--- a/plugins/discourse-ai/spec/system/ai_helper/ai_composer_helper_spec.rb+++ b/plugins/discourse-ai/spec/system/ai_helper/ai_composer_helper_spec.rb@@ -303,81 +303,12 @@ RSpec.describe "AI Composer helper" doendend- context "when suggesting the category with AI category suggester" do- before do- SiteSetting.ai_embeddings_selected_model = embedding_definition.id- SiteSetting.ai_embeddings_enabled = true- end-- it "updates the category with the suggested category" do- response =- Category- .take(3)- .map do |category|- {- id: category.id,- name: category.name,- slug: category.slug,- color: category.color,- score: rand(0.0...45.0),- topicCount: rand(1..3),- }- end- .sort_by { |h| h[:score] }- DiscourseAi::AiHelper::SemanticCategorizer.any_instance.stubs(:categories).returns(response)- visit("/latest")- page.find("#create-topic").click- composer.fill_content(input)- ai_suggestion_dropdown.click_suggest_category_button- wait_for { ai_suggestion_dropdown.has_dropdown? }- suggestion = category_2.name- ai_suggestion_dropdown.select_suggestion_by_name(suggestion)-- expect(page).to have_css(".category-chooser summary[data-name='#{suggestion}']")- end-- it "shows an error toast and closes the dropdown when no suggestions are returned" do- DiscourseAi::AiHelper::SemanticCategorizer.any_instance.stubs(:categories).returns([])- visit("/latest")- page.find("#create-topic").click- composer.fill_content(input)- ai_suggestion_dropdown.click_suggest_category_button-- expect(ai_suggestion_dropdown).to have_no_dropdown- expect(toasts).to have_error(- I18n.t("js.discourse_ai.ai_helper.suggest_errors.no_suggestions"),- )- end- end-context "when suggesting the tags with AI tag suggester" dobefore doSiteSetting.ai_embeddings_selected_model = embedding_definition.idSiteSetting.ai_embeddings_enabled = trueend- it "updates the tag with the suggested tag" do- response =- Tag- .take(7)- .map { |t| { id: t.id, name: t.name, score: rand(0.0...45.0) } }- .sort_by { |h| h[:score] }- DiscourseAi::AiHelper::SemanticCategorizer.any_instance.stubs(:tags).returns(response)-- visit("/latest")- page.find("#create-topic").click- composer.fill_content(input)-- ai_suggestion_dropdown.click_suggest_tags_button-- wait_for { ai_suggestion_dropdown.has_dropdown? }-- suggestion = ai_suggestion_dropdown.suggestion_name(0)- ai_suggestion_dropdown.select_suggestion_by_value(0)-- expect(page).to have_css(".mini-tag-chooser summary[data-name='#{suggestion}']")- end-it "does not suggest tags that already exist" doresponse =Tag@@ -410,32 +341,106 @@ RSpec.describe "AI Composer helper" doexpect(page).to have_no_css(".ai-suggestions-menu button[data-name='#{video.name}']")expect(page).to have_no_css(".ai-suggestions-menu button[data-name='#{music.name}']")end+ end- it "removes applied tag suggestions from the dropdown" do- response = [cloud, feedback, review].map { |t| { id: t.id, name: t.name, score: 1.0 } }- DiscourseAi::AiHelper::SemanticCategorizer.any_instance.stubs(:tags).returns(response)+ context "when suggesting a category inline in the composer" do+ before do+ SiteSetting.ai_embeddings_selected_model = embedding_definition.id+ SiteSetting.ai_embeddings_enabled = true+ end++ it "applies the best suggestion and closes the dropdown" do+ response = [+ {+ id: category.id,+ name: category.name,+ slug: category.slug,+ color: category.color,+ topicCount: 1,+ score: 1.0,+ },+ {+ id: category_2.id,+ name: category_2.name,+ slug: category_2.slug,+ color: category_2.color,+ topicCount: 1,+ score: 0.5,+ },+ ]+ DiscourseAi::AiHelper::SemanticCategorizer.any_instance.stubs(:categories).returns(response)visit("/latest")page.find("#create-topic").clickcomposer.fill_content(input)- ai_suggestion_dropdown.click_suggest_tags_button- wait_for { ai_suggestion_dropdown.has_dropdown? }+ composer.category_chooser.expand+ composer.category_chooser.select_row_by_value("ai-category-suggest")++ expect(composer.category_chooser).to have_selected_name(category.name)+ expect(page).to have_no_css(".category-chooser.is-expanded")+ end++ it "shows a toast when no category suggestions are returned" do+ DiscourseAi::AiHelper::SemanticCategorizer.any_instance.stubs(:categories).returns([])++ visit("/latest")+ page.find("#create-topic").click+ composer.fill_content(input)++ composer.category_chooser.expand+ composer.category_chooser.select_row_by_value("ai-category-suggest")++ expect(toasts).to have_error(+ I18n.t("js.discourse_ai.ai_helper.suggest_errors.no_suggestions"),+ )+ end++ it "does not offer a suggestion without enough content" do+ visit("/latest")+ page.find("#create-topic").click+ composer.fill_content("Too short")++ composer.category_chooser.expand++ expect(page).to have_no_css(+ ".category-chooser .select-kit-row[data-value='ai-category-suggest']",+ )+ end+ end++ context "when suggesting tags inline in the composer" do+ let(:tag_chooser) { PageObjects::Components::SelectKit.new(".mini-tag-chooser") }++ before do+ SiteSetting.ai_embeddings_selected_model = embedding_definition.id+ SiteSetting.ai_embeddings_enabled = true+ end++ it "suggests tags and applies the selected one" do+ response = [{ id: cloud.id, name: cloud.name, count: 1 }]+ DiscourseAi::AiHelper::SemanticCategorizer.any_instance.stubs(:tags).returns(response)++ visit("/latest")+ page.find("#create-topic").click+ composer.fill_content(input)- ai_suggestion_dropdown.select_suggestion_by_name(cloud.name)+ tag_chooser.expand+ tag_chooser.select_row_by_value("ai-tag-suggest")+ tag_chooser.select_row_by_name(cloud.name)- expect(page).to have_css(".mini-tag-chooser summary[data-name='#{cloud.name}']")- expect(page).to have_no_css(".ai-suggestions-menu button[data-name='#{cloud.name}']")+ expect(page).to have_css(".mini-tag-chooser .formatted-selection", text: cloud.name)end- it "shows an error toast when no suggestions are returned" do+ it "shows a toast when no tag suggestions are returned" doDiscourseAi::AiHelper::SemanticCategorizer.any_instance.stubs(:tags).returns([])visit("/latest")page.find("#create-topic").clickcomposer.fill_content(input)- ai_suggestion_dropdown.click_suggest_tags_button+ tag_chooser.expand+ tag_chooser.select_row_by_value("ai-tag-suggest")expect(toasts).to have_error(I18n.t("js.discourse_ai.ai_helper.suggest_errors.no_suggestions"),