Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Add full-text search for chat messages (#34704)

Joffrey JAFFEUX7ecb945ec466
diff --git a/app/assets/javascripts/discourse/app/modifiers/tab-to-sibling.js b/app/assets/javascripts/discourse/app/modifiers/tab-to-sibling.js
new file mode 100644
index 00000000000..e26211e1faf
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/modifiers/tab-to-sibling.js
@@ -0,0 +1,130 @@
+import { registerDestructor } from "@ember/destroyable";
+import Modifier from "ember-modifier";
+import { bind } from "discourse/lib/decorators";
+
+/**
+ * Modifier that redirects tab navigation to focus sibling elements
+ * instead of children within the element.
+ *
+ * Usage: {{tabToSibling}}
+ *
+ * When Tab is pressed on the element, it will focus the next sibling.
+ * When Shift+Tab is pressed, it will focus the previous sibling.
+ * If no focusable sibling is found, falls back to default behavior.
+ *
+ * @example
+ * // Use on list items to navigate between them instead of focusing children
+ * <div class="search-results">
+ * {{#each items as |item|}}
+ * <div class="search-result" {{tabToSibling}} tabindex="0">
+ * <h3>{{item.title}}</h3>
+ * <button>Action</button> <!-- Tab won't focus this -->
+ * </div>
+ * {{/each}}
+ * </div>
+ *
+ * @component TabToSiblingModifier
+ */
+export default class TabToSiblingModifier extends Modifier {
+ /**
+ * @param {object} owner - The owner object
+ * @param {Array} args - Arguments passed to the modifier
+ */
+ constructor(owner, args) {
+ super(owner, args);
+ registerDestructor(this, (instance) => instance.cleanup());
+ }
+
+ /**
+ * Applies the modifier to the element
+ * @param {Element} element - The DOM element to apply the modifier to
+ */
+ modify(element) {
+ this.element = element;
+ this.element.addEventListener("keydown", this.handleKeydown);
+ }
+
+ /**
+ * Handles keydown events to manage tab navigation
+ * @param {KeyboardEvent} event - The keyboard event
+ */
+ @bind
+ handleKeydown(event) {
+ if (event.key !== "Tab") {
+ return;
+ }
+
+ let targetSibling = null;
+ if (event.shiftKey) {
+ targetSibling = this.findFocusableSibling(this.element, "previous");
+ } else {
+ targetSibling = this.findFocusableSibling(this.element, "next");
+ }
+
+ if (targetSibling) {
+ event.preventDefault();
+ targetSibling.focus();
+ }
+ }
+
+ /**
+ * Finds the next or previous focusable sibling element
+ * @param {Element} element - The current element
+ * @param {string} direction - "next" or "previous"
+ * @returns {Element|null} - The focusable sibling element or null
+ */
+ findFocusableSibling(element, direction) {
+ const siblingProperty =
+ direction === "next" ? "nextElementSibling" : "previousElementSibling";
+ let sibling = element[siblingProperty];
+
+ while (sibling) {
+ if (this.isFocusable(sibling)) {
+ return sibling;
+ }
+ sibling = sibling[siblingProperty];
+ }
+
+ return null;
+ }
+
+ /**
+ * Checks if an element is focusable
+ * @param {Element} element - The element to check
+ * @returns {boolean} - True if the element is focusable
+ */
+ isFocusable(element) {
+ const tabindex = element.getAttribute("tabindex");
+ if (tabindex === "-1") {
+ return false;
+ }
+
+ if (!element.offsetParent) {
+ return;
+ }
+
+ if (element.disabled) {
+ return;
+ }
+
+ const focusable = [
+ "A",
+ "BUTTON",
+ "INPUT",
+ "SELECT",
+ "TEXTAREA",
+ "SUMMARY",
+ ].includes(element.tagName);
+
+ const hasTabindex = tabindex !== null && tabindex !== "-1";
+
+ return focusable || hasTabindex;
+ }
+
+ /**
+ * Cleanup method called when the modifier is destroyed
+ */
+ cleanup() {
+ this.element?.removeEventListener("keydown", this.handleKeydown);
+ }
+}
diff --git a/app/assets/javascripts/discourse/tests/integration/modifiers/tab-to-sibling-test.gjs b/app/assets/javascripts/discourse/tests/integration/modifiers/tab-to-sibling-test.gjs
new file mode 100644
index 00000000000..01f944cc682
--- /dev/null
+++ b/app/assets/javascripts/discourse/tests/integration/modifiers/tab-to-sibling-test.gjs
@@ -0,0 +1,113 @@
+import { focus, render, triggerKeyEvent } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import tabToSibling from "discourse/modifiers/tab-to-sibling";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+
+module("Integration | Modifier | tabToSibling", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("focuses next sibling when Tab is pressed", async function (assert) {
+ await render(
+ <template>
+ <div class="container">
+ <div class="first-item" {{tabToSibling}} tabindex="0">First</div>
+ <div class="second-item" tabindex="0">Second</div>
+ <div class="third-item" tabindex="0">Third</div>
+ </div>
+ </template>
+ );
+
+ await focus(".first-item");
+
+ assert
+ .dom(".first-item")
+ .isFocused("First item should be focused initially");
+
+ await triggerKeyEvent(".first-item", "keydown", "Tab");
+
+ assert
+ .dom(".second-item")
+ .isFocused("Second item should be focused after Tab");
+ });
+
+ test("focuses previous sibling when Shift+Tab is pressed", async function (assert) {
+ await render(
+ <template>
+ <div class="container">
+ <div class="first-item" tabindex="0">First</div>
+ <div class="second-item" {{tabToSibling}} tabindex="0">Second</div>
+ <div class="third-item" tabindex="0">Third</div>
+ </div>
+ </template>
+ );
+
+ await focus(".second-item");
+
+ assert
+ .dom(".second-item")
+ .isFocused("Second item should be focused initially");
+
+ await triggerKeyEvent(".second-item", "keydown", "Tab", { shiftKey: true });
+
+ assert
+ .dom(".first-item")
+ .isFocused("First item should be focused after Shift+Tab");
+ });
+
+ test("skips non-focusable siblings", async function (assert) {
+ await render(
+ <template>
+ <div class="container">
+ <div class="first-item" {{tabToSibling}} tabindex="0">First</div>
+ <div class="non-focusable">Non-focusable</div>
+ <div class="disabled-item" tabindex="-1">Disabled</div>
+ <div class="third-item" tabindex="0">Third</div>
+ </div>
+ </template>
+ );
+
+ await focus(".first-item");
+ await triggerKeyEvent(".first-item", "keydown", "Tab");
+
+ assert
+ .dom(".third-item")
+ .isFocused("Should skip non-focusable siblings and focus third item");
+ });
+
+ test("works with buttons and other naturally focusable elements", async function (assert) {
+ await render(
+ <template>
+ <div class="container">
+ <button class="first-button" {{tabToSibling}}>First Button</button>
+ <input class="input-field" type="text" />
+ <a href="#" class="link-element">Link</a>
+ </div>
+ </template>
+ );
+
+ await focus(".first-button");
+ await triggerKeyEvent(".first-button", "keydown", "Tab");
+
+ assert
+ .dom(".input-field")
+ .isFocused("Should focus input field after Tab from button");
+ });
+
+ test("ignores non-Tab key events", async function (assert) {
+ await render(
+ <template>
+ <div class="container">
+ <div class="first-item" {{tabToSibling}} tabindex="0">First</div>
+ <div class="second-item" tabindex="0">Second</div>
+ </div>
+ </template>
+ );
+
+ await focus(".first-item");
+ await triggerKeyEvent(".first-item", "keydown", "Enter");
+
+ assert
+ .dom(".first-item")
+ .isFocused("Focus should not change on non-Tab keys");
+ });
+});
diff --git a/app/jobs/scheduled/reindex_search.rb b/app/jobs/scheduled/reindex_search.rb
index db54093bad5..c2c750d1453 100644
--- a/app/jobs/scheduled/reindex_search.rb
+++ b/app/jobs/scheduled/reindex_search.rb
@@ -13,6 +13,7 @@ module Jobs
rebuild_topics
rebuild_posts
rebuild_users
+ rebuild_registered_search_handlers
clean_topics
clean_posts
@@ -73,6 +74,28 @@ module Jobs
end
end
+ def rebuild_registered_search_handlers(limit: 10_000, indexer: SearchIndexer)
+ DiscoursePluginRegistry.search_handlers.each do |handler|
+ next unless handler[:enabled]&.call
+
+ unindexed_record_ids =
+ handler[:load_unindexed_record_ids].call(limit:, index_version: handler[:index_version])
+
+ if @verbose
+ puts "rebuilding #{unindexed_record_ids.size} records for #{handler[:table_name]}"
+ end
+
+ unindexed_record_ids.each do |id|
+ record = handler[:model_class].find_by(id: id)
+ if record
+ indexer.index(record, force: true)
+ else
+ puts "↪ record #{id} not found" if @verbose
+ end
+ end
+ end
+ end
+
def clean_topics
puts "cleaning up topic search data" if @verbose
diff --git a/app/services/search_indexer.rb b/app/services/search_indexer.rb
index 340fb3919fa..2e2c70582be 100644
--- a/app/services/search_indexer.rb
+++ b/app/services/search_indexer.rb
@@ -144,16 +144,24 @@ class SearchIndexer
search_data.values.select { |d| d.length > 0 }.join(" ")
end
+ handler = DiscoursePluginRegistry.search_handlers.find { |h| h[:table_name] == table }
+ index_version = handler ? handler[:index_version] : const_get("#{table.upcase}_INDEX_VERSION")
+
params = {
"raw_data" => indexed_data,
"#{foreign_key}" => id,
"locale" => SiteSetting.default_locale,
- "version" => const_get("#{table.upcase}_INDEX_VERSION"),
+ "version" => index_version,
"search_data" => tsvector,
}
yield params if block_given?
- table_name.camelize.constantize.upsert(params)
+
+ if handler
+ handler[:search_data_class].upsert(params)
+ else
+ table_name.camelize.constantize.upsert(params)
+ end
rescue => e
if Rails.env.test?
raise
@@ -261,6 +269,16 @@ class SearchIndexer
def self.index(obj, force: false)
return if @disabled
+ # Check registered search handlers for this object type
+ handler = DiscoursePluginRegistry.search_handlers.find { |h| obj.is_a?(h[:model_class]) }
+
+ if handler
+ indexer_helper = IndexerHelper.new
+ search_weights = handler[:search_data].call(obj, indexer_helper)
+ update_index(table: handler[:table_name], id: obj.id, **search_weights)
+ return
+ end
+
category_name = nil
tag_names = nil
topic = nil
@@ -423,4 +441,10 @@ class SearchIndexer
scrubbed << " #{str} "
end
end
+
+ class IndexerHelper
+ def scrub_html(html)
+ HtmlScrubber.scrub(html)
+ end
+ end
end
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index b05440ff065..175fbb72475 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -647,6 +647,7 @@ en:
preview: "preview"
cancel: "Cancel"
+ done: "Done"
deleting: "Deleting…"
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index 69fecdd3445..fae33bae6c5 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -302,6 +302,7 @@ en:
greater_than: must be greater than %{count}
greater_than_or_equal_to: must be greater than or equal to %{count}
has_already_been_used: "has already been used"
+ in: must be in %{count}
inclusion: is not included in the list
invalid: is invalid
is_invalid: "seems unclear, is it a complete sentence?"
diff --git a/lib/discourse_plugin_registry.rb b/lib/discourse_plugin_registry.rb
index ba42f80a176..5ac22fc414a 100644
--- a/lib/discourse_plugin_registry.rb
+++ b/lib/discourse_plugin_registry.rb
@@ -116,6 +116,7 @@ class DiscoursePluginRegistry
define_filtered_register :hashtag_autocomplete_contextual_type_priorities
define_filtered_register :search_groups_set_query_callbacks
+ define_filtered_register :search_handlers
define_filtered_register :stats
define_filtered_register :bookmarkables
diff --git a/lib/plugin/instance.rb b/lib/plugin/instance.rb
index be57b618ff3..0acfe07ca23 100644
--- a/lib/plugin/instance.rb
+++ b/lib/plugin/instance.rb
@@ -1309,6 +1309,64 @@ class Plugin::Instance
DiscoursePluginRegistry.register_search_groups_set_query_callback(callback, self)
end
+ # Register a search index for a custom content type
+ #
+ # @param model_class [Class] The ActiveRecord model class
+ # @param search_data_class [Class] The search data class (e.g., Chat::MessageSearchData)
+ # @param index_version [Integer] The version number for this search index
+ # @param search_data [Proc] Block that extracts search data from an object, receives (object, indexer_helper)
+ # Should return hash with :a_weight, :b_weight, :c_weight, :d_weight keys
+ # @param load_unindexed_record_ids [Proc] Block that loads record IDs needing reindexing, receives (limit:, index_version:)
+ # @param enabled [Proc] Optional block that returns true/false to enable/disable the search index (default: -> { true })
+ #
+ # Example:
+ # register_search_index(
+ # enabled: -> { SiteSetting.chat_search_enabled },
+ # model_class: Chat::Message,
+ # search_data_class: Chat::MessageSearchData,
+ # index_version: 1,
+ # search_data: proc { |message, indexer_helper|
+ # {
+ # a_weight: message.message,
+ # d_weight: indexer_helper.scrub_html(message.cooked)[0..600_000]
+ # }
+ # },
+ # load_unindexed_record_ids: proc { |limit:, index_version:|
+ # Chat::Message
+ # .joins("LEFT JOIN chat_message_search_data ON chat_message_id = chat_messages.id")
+ # .where(
+ # "chat_message_search_data.locale IS NULL OR chat_message_search_data.locale != ? OR chat_message_search_data.version != ?",
+ # SiteSetting.default_locale,
+ # index_version,
+ # )
+ # .order("chat_messages.id ASC")
+ # .limit(limit)
+ # .pluck(:id)
+ # }
+ # )
+ def register_search_index(
+ model_class:,
+ search_data_class:,
+ index_version:,
+ search_data:,
+ load_unindexed_record_ids:,
+ enabled: -> { true }
+ )
+ table_name = model_class.table_name.singularize
+
+ handler = {
+ table_name:,
+ model_class:,
+ search_data_class:,
+ index_version:,
+ search_data:,
+ load_unindexed_record_ids: load_unindexed_record_ids,
+ enabled:,
+ }
+
+ DiscoursePluginRegistry.register_search_handler(handler, self)
+ end
+
# This is an experimental API and may be changed or removed in the future without deprecation.
#
# Adds a custom rate limiter to the request rate limiters stack. Only one rate limiter is used per request and the
diff --git a/plugins/chat/app/controllers/chat/api/search_controller.rb b/plugins/chat/app/controllers/chat/api/search_controller.rb
new file mode 100644
index 00000000000..9fd36fac405
--- /dev/null
+++ b/plugins/chat/app/controllers/chat/api/search_controller.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+class Chat::Api::SearchController < Chat::ApiController
+ def index
+ Chat::SearchMessage.call(service_params) do
+ on_success do |messages:, metadata:|
+ render json: {
+ messages:
+ ActiveModel::ArraySerializer.new(
+ messages,
+ each_serializer: ::Chat::MessageSerializer,
+ root: false,
+ scope: guardian,
+ include_channel: true,
+ ).as_json,
+ meta: metadata.slice(:has_more, :limit, :offset),
+ }
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_model_not_found(:channel) { raise Discourse::NotFound }
+ on_failed_policy(:can_view_channel) { raise Discourse::InvalidAccess }
+ on_failed_contract do |contract|
+ render(json: failed_json.merge(errors: contract.errors.full_messages), status: :bad_request)
+ end
+ end
+ end
+end
diff --git a/plugins/chat/app/models/chat/message.rb b/plugins/chat/app/models/chat/message.rb
index 529b9a4d562..8016a5508d7 100644
--- a/plugins/chat/app/models/chat/message.rb
+++ b/plugins/chat/app/models/chat/message.rb
@@ -73,6 +73,7 @@ module Chat
dependent: :destroy,
class_name: "Chat::HereMention",
foreign_key: :chat_message_id
+ has_one :message_search_data, dependent: :destroy, foreign_key: :chat_message_id
scope :in_public_channel,
-> do
diff --git a/plugins/chat/app/models/chat/message_search_data.rb b/plugins/chat/app/models/chat/message_search_data.rb
new file mode 100644
index 00000000000..d451f60dc36
--- /dev/null
+++ b/plugins/chat/app/models/chat/message_search_data.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+
+module Chat
+ class MessageSearchData < ActiveRecord::Base
+ self.table_name = "chat_message_search_data"
+ self.primary_key = :chat_message_id
+ belongs_to :chat_message
+ validates :search_data, presence: true
+ end
+end
+
+# == Schema Information
+#
+# Table name: chat_message_search_data
+#
+# locale :text
+# raw_data :text
+# search_data :tsvector
+# version :integer default(0)
+# chat_message_id :bigint not null, primary key
+#
+# Indexes
+#
+# idx_search_chat_message (search_data) USING gin
+#
diff --git a/plugins/chat/app/serializers/chat/message_serializer.rb b/plugins/chat/app/serializers/chat/message_serializer.rb
index f3e095dc1d8..29ffb05ca1c 100644
--- a/plugins/chat/app/serializers/chat/message_serializer.rb
+++ b/plugins/chat/app/serializers/chat/message_serializer.rb
@@ -28,6 +28,8 @@ module Chat
edited
thread
blocks
+ channel
+ thread_title
]
),
)
@@ -48,8 +50,8 @@ module Chat
.as_json
end
- def channel
- @channel ||= @options.dig(:chat_channel) || object.chat_channel
+ def channel_object
+ @channel_object ||= @options.dig(:chat_channel) || object.chat_channel
end
def user
@@ -178,7 +180,9 @@ module Chat
return [] if reviewable_id.present? && user_flag_status == ReviewableScore.statuses[:pending]
PostActionType.flag_types.map do |sym, id|
- next if channel.direct_message_channel? && %i[notify_moderators notify_user].include?(sym)
+ if channel_object.direct_message_channel? && %i[notify_moderators notify_user].include?(sym)
+ next
+ end
if sym == :notify_user &&
(
@@ -192,14 +196,30 @@ module Chat
end
end
+ def include_channel?
+ @options[:include_channel]
+ end
+
+ def channel
+ ::Chat::ChannelSerializer.new(channel_object, scope:, root: false)
+ end
+
def include_thread_id?
- channel.threading_enabled || object.thread&.force
+ channel_object.threading_enabled || object.thread&.force
end
def include_thread?
include_thread_id? && object.thread_om? && object.thread.present?
end
+ def include_thread_title?
+ include_thread_id? && !object.thread_om? && object.thread.present?
+ end
+
+ def thread_title
+ object.thread&.title
+ end
+
def thread
Chat::ThreadSerializer.new(
object.thread,
diff --git a/plugins/chat/app/services/chat/action/search_for_messages.rb b/plugins/chat/app/services/chat/action/search_for_messages.rb
new file mode 100644
index 00000000000..bd8ae22f96e
--- /dev/null
+++ b/plugins/chat/app/services/chat/action/search_for_messages.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+class Chat::Action::SearchForMessages < Service::ActionBase
+ option :guardian
+ option :params
+ option :channel
+
+ delegate :offset, :limit, :query, :exclude_threads, :sort, to: :params, private: true
+ delegate :processed_query, :filters, to: :search_query_result, private: true
+
+ def call
+ return default_metadata if processed_query.blank? && filters.blank?
+
+ # Fetch one extra to check if there are more results
+ messages = sorted_and_filtered_messages.offset(offset).limit(limit + 1).to_a
+ default_metadata.merge(messages: messages.take(limit), has_more: messages.size > limit)
+ end
+
+ private
+
+ def default_metadata
+ { limit:, offset:, has_more: false, messages: [] }
+ end
+
+ def search_query_result
+ @search_query_result ||=
+ Chat::Action::SearchMessage::ProcessSearchQuery.call(
+ query:,
+ guardian:,
+ messages:
+ Chat::Message.joins(:chat_channel).where(
+ chat_channels: {
+ id: channel || Chat::ChannelFetcher.all_secured_channel_ids(guardian),
+ },
+ ),
+ )
+ end
+
+ def sorted_and_filtered_messages
+ @sorted_and_filtered_messages ||=
+ Chat::Action::SearchMessage::ApplyFiltersAndSorting.call(
+ exclude_threads:,
+ sort:,
+ messages: search_query_result.messages,
+ )
+ end
+end
diff --git a/plugins/chat/app/services/chat/action/search_message/apply_filters_and_sorting.rb b/plugins/chat/app/services/chat/action/search_message/apply_filters_and_sorting.rb
new file mode 100644
index 00000000000..ab1a49de4ae
--- /dev/null
+++ b/plugins/chat/app/services/chat/action/search_message/apply_filters_and_sorting.rb
@@ -0,0 +1,72 @@
+# frozen_string_literal: true
+
+module Chat
+ module Action
+ module SearchMessage
+ # Applies filtering and sorting to chat messages search results.
+ #
+ # Handles two types of operations:
+ # 1. Thread exclusion - Filters out thread reply messages while preserving
+ # messages that are not part of threads and original thread starter messages
+ # 2. Sorting - Orders messages by relevance (default) or latest (created_at desc)
+ #
+ # Returns the modified ActiveRecord::Relation with filters and sorting applied.
+ class ApplyFiltersAndSorting < Service::ActionBase
+ # @param [ActiveRecord::Relation] messages The messages relation to filter and sort
+ # @param [Boolean] exclude_threads Whether to exclude thread reply messages
+ # @param [String] sort The sort option ("relevance" or "latest")
+ option :messages
+ option :exclude_threads
+ option :sort
+
+ def call
+ filtered_messages = apply_thread_exclusion(messages, exclude_threads)
+ apply_sorting(filtered_messages, sort)
+ end
+
+ private
+
+ # Applies thread exclusion filtering to messages when requested.
+ #
+ # When exclude_threads is true, this method filters out thread reply messages
+ # while preserving:
+ # 1. Messages that are not part of any thread (thread_id IS NULL)
+ # 2. Original messages that started threads (these have thread_id but are
+ # referenced as original_message_id in the chat_threads table)
+ #
+ # This allows searching in channel messages and thread starters without
+ # getting overwhelmed by thread replies.
+ #
+ # @param [ActiveRecord::Relation] messages The messages query to filter
+ # @param [Boolean] exclude_threads Whether to apply thread exclusion
+ # @return [ActiveRecord::Relation] The filtered messages query
+ def apply_thread_exclusion(messages, exclude_threads)
+ return messages unless exclude_threads
+
+ # Exclude messages that have a thread_id unless they are the original message of the thread
+ messages.where(
+ "chat_messages.thread_id IS NULL OR chat_messages.id IN (
+ SELECT ct.original_message_id
+ FROM chat_threads ct
+ WHERE ct.id = chat_messages.thread_id
+ )",
+ )
+ end
+
+ # Applies sorting to messages based on the specified sort option.
+ #
+ # @param [ActiveRecord::Relation] messages The messages query to sort
+ # @param [String] sort The sort option ("relevance" or "latest")
+ # @return [ActiveRecord::Relation] The sorted messages query
+ def apply_sorting(messages, sort)
+ case sort
+ when "latest"
+ messages.order(created_at: :desc)
+ else
+ messages
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/chat/app/services/chat/action/search_message/process_search_query.rb b/plugins/chat/app/services/chat/action/search_message/process_search_query.rb
new file mode 100644
index 00000000000..138ca5ce049
--- /dev/null
+++ b/plugins/chat/app/services/chat/action/search_message/process_search_query.rb
@@ -0,0 +1,145 @@
+# frozen_string_literal: true
+
+module Chat
+ module Action
+ module SearchMessage
+ # Processes a search query to extract advanced filters, apply them to messages,
+ # and return cleaned query text.
+ #
+ # Parses query strings to identify special filter syntax:
+ # - @username filters (e.g., "@alice" or "@me")
+ # - #channel filters (e.g., "#general")
+ #
+ # Then applies those filters to the provided messages relation.
+ #
+ # Returns a result object containing:
+ # - processed_query: The query text with filter terms removed
+ # - filters: Array of [filter_type, match] tuples
+ # - messages: The filtered messages ActiveRecord::Relation
+ class ProcessSearchQuery < Service::ActionBase
+ # @param [String] query The search query to process
+ # @param [ActiveRecord::Relation] messages The messages relation to filter
+ # @param [Guardian] guardian The current user's guardian for permission checks
+ option :query
+ option :messages
+ option :guardian
+
+ Result = Struct.new(:processed_query, :filters, :messages)
+
+ MAX_FILTERS = 10
+
+ def call
+ set_filters_and_query_words
+ Result.new(processed_query, filters, filtered_messages)
+ end
+
+ private
+
+ def filters
+ @filters ||= []
+ end
+
+ def query_words
+ @query_words ||= []
+ end
+
+ def usernames
+ @usernames ||= filters.select { |type, _| type == :username }.map(&:last)
+ end
+
+ def channel_slugs
+ @channel_slugs ||= filters.select { |type, _| type == :channel }.map(&:last)
+ end
+
+ def set_filters_and_query_words
+ query
+ .to_s
+ .split(/\s+/)
+ .each do |word|
+ next if word.blank?
+
+ # Check for @username filter
+ if word =~ /\A\@(\S+)\z/i
+ filters << [:username, $1]
+ # Check for #channel filter
+ elsif word =~ /\A\#(\S+)\z/i
+ filters << [:channel, $1]
+ else
+ query_words << word
+ end
+ end
+
+ @filters = filters.first(MAX_FILTERS)
+ end
+
+ def processed_query
+ @processed_query ||= query_words.join(" ")
+ end
+
+ def user_id_lookup
+ @user_id_lookup ||=
+ begin
+ return {} if usernames.empty?
+
+ normalized_usernames = usernames.map(&User.method(:normalize_username))
+ me_index = normalized_usernames.index("me")
+ normalized_usernames[me_index] = guardian.user&.username_lower if me_index
+
+ User
+ .not_staged
+ .where(username_lower: normalized_usernames.compact)
+ .pluck(:username_lower, :id)
+ .to_h
+ end
+ end
+
+ def channel_lookup
+ @channel_lookup ||=
+ begin
+ return {} if channel_slugs.empty?
+
+ Chat::Channel.where(slug: channel_slugs.map(&:downcase)).index_by(&:slug)
+ end
+ end
+
+ def filtered_messages
+ messages
+ .then { apply_username_filters(_1) }
+ .then { apply_channel_filters(_1) }
+ .then { apply_ts_query(_1) }
+ end
+
+ def apply_ts_query(messages)
+ return messages if processed_query.blank?
+ ts_query =
+ Search.ts_query(term: Search.prepare_data(processed_query), ts_config: Search.ts_config)
+ messages.joins(:message_search_data).where(
+ "chat_message_search_data.search_data @@ #{ts_query}",
+ )
+ end
+
+ def apply_username_filters(messages)
+ usernames.reduce(messages) do |filtered, username|
+ normalized_username = User.normalize_username(username)
+ normalized_username = guardian.user&.username_lower if normalized_username == "me"
+
+ user_id = user_id_lookup[normalized_username]
+ user_id ? filtered.where(user_id:) : filtered.where("1 = 0")
+ end
+ end
+
+ def apply_channel_filters(messages)
+ channel_slugs.reduce(messages) do |filtered, slug|
+ channel = channel_lookup[slug.downcase]
+
+ if channel.present? && guardian.can_preview_chat_channel?(channel)
+ filtered.where("chat_channels.id = ?", channel.id)
+ else
+ filtered.where("1 = 0")
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/chat/app/services/chat/create_message.rb b/plugins/chat/app/services/chat/create_message.rb
index 97d817fff00..44ffae5a33d 100644
--- a/plugins/chat/app/services/chat/create_message.rb
+++ b/plugins/chat/app/services/chat/create_message.rb
@@ -89,6 +89,7 @@ module Chat
step :publish_new_thread
step :process
step :publish_user_tracking_state
+ step :index_message
private
@@ -273,5 +274,11 @@ module Chat
membership.last_read_message || message_instance if message_instance.in_thread?
Chat::Publisher.publish_user_tracking_state!(guardian.user, channel, message_to_publish)
end
+
+ def index_message(message_instance:)
+ Scheduler::Defer.later "Index chat message for search" do
+ SearchIndexer.index(message_instance)
+ end
+ end
end
end
diff --git a/plugins/chat/app/services/chat/search_message.rb b/plugins/chat/app/services/chat/search_message.rb
new file mode 100644
index 00000000000..6b92cd4c314
--- /dev/null
+++ b/plugins/chat/app/services/chat/search_message.rb
@@ -0,0 +1,76 @@
+# frozen_string_literal: true
+
+module Chat
+ # Service responsible to search messages in channels.
+ #
+ # @example
+ # ::Chat::SearchMessage.call(
+ # guardian: guardian,
+ # params: {
+ # query: "foo",
+ # channel_id: 1,
+ # sort: "latest",
+ # }
+ # )
+ #
+ class SearchMessage
+ include Service::Base
+
+ # @!method self.call(guardian:, params:)
+ # @param [Guardian] guardian
+ # @param [Hash] params
+ # @option params [String] :query The query used to query the results
+ # @option params [Integer] :channel_id ID of the channel to scope the search
+ # @option params [Integer] :limit Maximum number of results to return (1-40, defaults to 20)
+ # @option params [Integer] :offset Number of results to skip for pagination (defaults to 0)
+ # @option params [Boolean] :exclude_threads Whether to exclude thread messages (keeps original thread messages)
+ # @option params [String] :sort Sort order for results ("relevance" or "latest", defaults to "relevance")
+ # @return [Service::Base::Context]
+
+ params do
+ attribute :query, :string
+ attribute :channel_id, :integer
+ attribute :limit, :integer, default: 20
+ attribute :offset, :integer, default: 0
+ attribute :exclude_threads, :boolean, default: false
+ attribute :sort, :string, default: "relevance"
+
+ validates :query, presence: true
+ validates :limit, numericality: { in: 1..40 }
+ validates :offset, numericality: { greater_than_or_equal_to: 0 }
+ validates :sort, inclusion: { in: %w[relevance latest] }
+
+ after_validation { self.query = Search.clean_term(query) }
+ end
+
+ only_if(:provided_channel_id) do
+ model :channel
+ policy :can_view_channel
+ end
+
+ model :metadata
+ model :messages, optional: true
+
+ private
+
+ def provided_channel_id(params:)
+ params.channel_id.present?
+ end
+
+ def fetch_channel(params:)
+ Chat::Channel.find_by(id: params.channel_id)
+ end
+
+ def can_view_channel(guardian:, channel:)
+ guardian.can_preview_chat_channel?(channel)
+ end
+
+ def fetch_metadata(params:, guardian:)
+ Chat::Action::SearchForMessages.call(params:, guardian:, channel: context[:channel])
+ end
+
+ def fetch_messages(metadata:)
+ metadata[:messages]
+ end
+ end
+end
diff --git a/plugins/chat/app/services/chat/update_message.rb b/plugins/chat/app/services/chat/update_message.rb
index c64495e744c..a3ec04d0d0b 100644
--- a/plugins/chat/app/services/chat/update_message.rb
+++ b/plugins/chat/app/services/chat/update_message.rb
@@ -60,6 +60,8 @@ module Chat
step :publish
end
+ step :index_message
+
private
def enforce_membership(guardian:, message:)
@@ -184,5 +186,11 @@ module Chat
::Chat::Publisher.publish_thread_original_message_metadata!(message.thread)
end
end
+
+ def index_message(message:)
+ Scheduler::Defer.later "Index chat message for search" do
+ SearchIndexer.index(message)
+ end
+ end
end
end
diff --git a/plugins/chat/assets/javascripts/discourse/chat-route-map.js b/plugins/chat/assets/javascripts/discourse/chat-route-map.js
index 9e63f4962e1..a9f437145bd 100644
--- a/plugins/chat/assets/javascripts/discourse/chat-route-map.js
+++ b/plugins/chat/assets/javascripts/discourse/chat-route-map.js
@@ -1,5 +1,7 @@
export default function () {
this.route("chat", function () {
+ this.route("search");
+
this.route("channel", { path: "/c/:channelTitle/:channelId" }, function () {
this.route("near-message", { path: "/:messageId" });
this.route("near-message-with-thread", {
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-filter.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-channel-filter.gjs
new file mode 100644
index 00000000000..4c39529f7c2
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-filter.gjs
@@ -0,0 +1,203 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { cancel } from "@ember/runloop";
+import { service } from "@ember/service";
+import { isBlank } from "@ember/utils";
+import { gt } from "truth-helpers";
+import DButton from "discourse/components/d-button";
+import FilterInput from "discourse/components/filter-input";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import discourseDebounce from "discourse/lib/debounce";
+import { INPUT_DELAY } from "discourse/lib/environment";
+import autoFocus from "discourse/modifiers/auto-focus";
+import { i18n } from "discourse-i18n";
+
+export default class ChatChannelFilter extends Component {
+ @service capabilities;
+ @service loadingSlider;
+
+ @tracked channelFilterResults;
+ @tracked currentChannelFilter = "";
+ @tracked currentChannelFilterResult;
+ @tracked currentChannelFilterResultIndex = 0;
+ @tracked noResults = false;
+
+ get currentFilterResultPosition() {
+ return this.currentChannelFilterResultIndex + 1;
+ }
+
+ @action
+ navigateToPreviousResult() {
+ if (!this.channelFilterResults?.length) {
+ return;
+ }
+
+ const newIndex =
+ this.currentChannelFilterResultIndex <
+ this.channelFilterResults.length - 1
+ ? this.currentChannelFilterResultIndex + 1
+ : 0;
+
+ this.currentChannelFilterResultIndex = newIndex;
+ this.navigateToResult(this.channelFilterResults[newIndex]);
+ }
+
+ @action
+ navigateToNextResult() {
+ if (!this.channelFilterResults?.length) {
+ return;
+ }
+
+ const newIndex =
+ this.currentChannelFilterResultIndex > 0
+ ? this.currentChannelFilterResultIndex - 1
+ : this.channelFilterResults.length - 1;
+
+ this.currentChannelFilterResultIndex = newIndex;
+ this.navigateToResult(this.channelFilterResults[newIndex]);
+ }
+
+ @action
+ navigateToResult(result) {
+ this.currentChannelFilterResult = result;
+
+ if (this.capabilities.isIOS) {
+ document.activeElement.blur(); // prevents a bug on iOS where the body would scroll unexpectedly
+ }
+
+ this.args.onLoadTargetMessageId(this.currentChannelFilterResult.id);
+ }
+
+ @action
+ clearFilteringState() {
+ this.noResults = false;
+ this.currentChannelFilter = "";
+ this.channelFilterResults = null;
+ this.currentChannelFilterResult = null;
+ this.currentChannelFilterResultIndex = 0;
+ }
+
+ @action
+ loadSearchResults(event) {
+ this.currentChannelFilter = event.target.value;
+
+ if (isBlank(this.currentChannelFilter)) {
+ cancel(this, this.performSearch);
+ this.searchRequest?.abort?.();
+ this.clearFilteringState();
+ cancel(this.debouncedSearch);
+ return;
+ }
+
+ this.debouncedSearch = discourseDebounce(
+ this,
+ this.performSearch,
+ this.currentChannelFilter,
+ // given we have to blur on iOS, we give more time to the user
+ // to avoid bluring in the middle of a query
+ this.capabilities.isIOS ? INPUT_DELAY * 2 : INPUT_DELAY
+ );
+ }
+
+ async performSearch(query) {
+ this.searchRequest?.abort?.();
+
+ try {
+ this.noResults = false;
+ this.loadingSlider.transitionStarted();
+
+ this.searchRequest = ajax("/chat/api/search", {
+ data: {
+ query,
+ channel_id: this.args.channel.id,
+ exclude_threads: true,
+ sort: "latest",
+ },
+ });
+
+ const response = await this.searchRequest;
+
+ this.channelFilterResults = response.messages;
+ this.currentChannelFilterResultIndex = 0;
+
+ if (!this.channelFilterResults?.length) {
+ this.noResults = true;
+ return;
+ }
+
+ this.navigateToResult(this.channelFilterResults[0]);
+ } catch (error) {
+ popupAjaxError(error);
+ } finally {
+ this.loadingSlider.transitionEnded();
+ }
+ }
+
+ <template>
+ {{#if @isFiltering}}
+ <div
+ class="chat-channel__filter-bar"
+ {{didInsert this.clearFilteringState}}
+ >
+ <div>
+ <FilterInput
+ {{autoFocus}}
+ @value={{this.currentChannelFilter}}
+ placeholder={{i18n "chat.search.title"}}
+ @filterAction={{this.loadSearchResults}}
+ class="no-blur"
+ />
+
+ {{#if this.channelFilterResults.length}}
+ <span class="chat-channel__filter-position">
+ <span
+ class="chat-channel__filter-position-index"
+ >{{this.currentFilterResultPosition}}</span>
+ <span class="chat-channel__filter-position-separator">/</span>
+ <span
+ class="chat-channel__filter-position-total"
+ >{{this.channelFilterResults.length}}</span>
+ </span>
+
+ {{#if (gt this.channelFilterResults.length 1)}}
+ <DButton
+ @action={{this.navigateToPreviousResult}}
+ @icon="chevron-up"
+ class="btn-small chat-channel__prev-result"
+ />
+ <DButton
+ @action={{this.navigateToNextResult}}
+ @icon="chevron-down"
+ class="btn-small chat-channel__next-result"
+ />
+ {{/if}}
+ {{/if}}
+
+ {{#if this.currentChannelFilter.length}}
+ <DButton
+ @icon="xmark"
+ class="btn-small"
+ @action={{this.clearFilteringState}}
+ />
+ {{/if}}
+
+ <DButton
+ @action={{fn @onToggleFilter false}}
+ class="btn-primary btn-small"
+ @label="done"
+ />
+ </div>
+
+ {{#if this.noResults}}
+ <div class="alert alert-info">
+ {{i18n "chat.search.no_results"}}
+ </div>
+ {{/if}}
+ </div>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs
index 0eba05f0155..a8b3593038d 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs
@@ -38,6 +38,7 @@ import ChatMessage from "discourse/plugins/chat/discourse/models/chat-message";
import ChatComposerChannel from "./chat/composer/channel";
import ChatScrollToBottomArrow from "./chat/scroll-to-bottom-arrow";
import ChatSelectionManager from "./chat/selection-manager";
+import ChatChannelFilter from "./chat-channel-filter";
import ChatChannelPreviewCard from "./chat-channel-preview-card";
import ChatMentionWarnings from "./chat-mention-warnings";
import Message from "./chat-message";
@@ -84,7 +85,7 @@ export default class ChatChannel extends Component {
}
get currentUserMembership() {
- return this.args.channel.currentUserMembership;
+ return this.args.channel?.currentUserMembership;
}
get hasSavedScrollPosition() {
@@ -103,6 +104,11 @@ export default class ChatChannel extends Component {
removeOnPresenceChange(this.onPresenceChangeCallback);
this.subscriptionManager.teardown();
this.updateLastReadMessage();
+
+ // Cancel any pending search request and debounced calls
+ cancel(this, this._performSearch);
+ this.searchRequest?.abort?.();
+ this.searchRequest = null;
}
@action
@@ -142,7 +148,14 @@ export default class ChatChannel extends Component {
}
@action
- loadMessages() {
+ onLoadTargetMessageId(targetMessageId) {
+ this.loadMessages(null, targetMessageId);
+ }
+
+ @action
+ loadMessages(_element, targetMessageId) {
+ targetMessageId ??= this.args.targetMessageId;
+
if (!this.args.channel?.id) {
return;
}
@@ -153,8 +166,8 @@ export default class ChatChannel extends Component {
{ onNewMessage: this.onNewMessage }
);
- if (this.args.targetMessageId) {
- this.debounceHighlightOrFetchMessage(this.args.targetMessageId);
+ if (targetMessageId) {
+ this.debounceHighlightOrFetchMessage(targetMessageId);
} else if (this.chatChannelScrollPositions.get(this.args.channel.id)) {
this.debounceHighlightOrFetchMessage(
this.chatChannelScrollPositions.get(this.args.channel.id)
@@ -697,6 +710,12 @@ export default class ChatChannel extends Component {
<ChatChannelStatus @channel={{@channel}} />
<ChatNotices @channel={{@channel}} />
<ChatMentionWarnings />
+ <ChatChannelFilter
+ @isFiltering={{@isFiltering}}
+ @onToggleFilter={{@onToggleFilter}}
+ @channel={{@channel}}
+ @onLoadTargetMessageId={{this.onLoadTargetMessageId}}
+ />
<ChatMessagesScroller
@onRegisterScroller={{this.registerScroller}}
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-message-reaction.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-message-reaction.gjs
index beb39b12ded..68b2f57c031 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat-message-reaction.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat-message-reaction.gjs
@@ -73,7 +73,7 @@ export default class ChatMessageReaction extends Component {
type="button"
title={{this.emojiString}}
data-emoji-name={{@reaction.emoji}}
- tabindex="0"
+ tabindex={{if @interactive "0" "-1"}}
class={{concatClass
"chat-message-reaction"
(if @reaction.reacted "reacted")
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-message.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-message.gjs
index 77a8ba8d872..96537b5d82f 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat-message.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat-message.gjs
@@ -92,6 +92,10 @@ export default class ChatMessage extends Component {
return this.threadContext ? this.chatThreadPane : this.chatChannelPane;
}
+ get includeSeparator() {
+ return this.args.includeSeparator ?? true;
+ }
+
get messageInteractor() {
return new ChatMessageInteractor(
getOwner(this),
@@ -527,10 +531,12 @@ export default class ChatMessage extends Component {
<template>
{{! template-lint-disable no-invalid-interactive }}
{{#if this.shouldRender}}
- <ChatMessageSeparator
- @fetchMessagesByDate={{@fetchMessagesByDate}}
- @message={{@message}}
- />
+ {{#if this.includeSeparator}}
+ <ChatMessageSeparator
+ @fetchMessagesByDate={{@fetchMessagesByDate}}
+ @message={{@message}}
+ />
+ {{/if}}
<div
class={{concatClass
@@ -611,7 +617,10 @@ export default class ChatMessage extends Component {
@threadContext={{this.threadContext}}
/>
{{else}}
- <ChatMessageAvatar @message={{@message}} />
+ <ChatMessageAvatar
+ @message={{@message}}
+ @interactive={{@interactive}}
+ />
{{/if}}
<div class="chat-message-content">
@@ -619,6 +628,7 @@ export default class ChatMessage extends Component {
@message={{@message}}
@show={{not this.hideUserInfo}}
@threadContext={{this.threadContext}}
+ @dateMode={{@dateMode}}
/>
<ChatMessageText
@@ -635,6 +645,7 @@ export default class ChatMessage extends Component {
@onReaction={{this.messageInteractor.react}}
@message={{@message}}
@showTooltip={{true}}
+ @interactive={{@interactive}}
/>
{{/each}}
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-search.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-search.gjs
new file mode 100644
index 00000000000..2efc154fac0
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/components/chat-search.gjs
@@ -0,0 +1,284 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn, hash } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import didUpdate from "@ember/render-modifiers/modifiers/did-update";
+import { service } from "@ember/service";
+import { isBlank } from "@ember/utils";
+import { not } from "truth-helpers";
+import ConditionalLoadingSpinner from "discourse/components/conditional-loading-spinner";
+import DButton from "discourse/components/d-button";
+import DropdownMenu from "discourse/components/dropdown-menu";
+import FilterInput from "discourse/components/filter-input";
+import LoadMore from "discourse/components/load-more";
+import { ajax } from "discourse/lib/ajax";
+import discourseDebounce from "discourse/lib/debounce";
+import { bind } from "discourse/lib/decorators";
+import { INPUT_DELAY } from "discourse/lib/environment";
+import DiscourseURL from "discourse/lib/url";
+import autoFocus from "discourse/modifiers/auto-focus";
+import tabToSibling from "discourse/modifiers/tab-to-sibling";
+import { i18n } from "discourse-i18n";
+import DMenu from "float-kit/components/d-menu";
+import ChatChannelTitle from "discourse/plugins/chat/discourse/components/chat-channel-title";
+import ChatMessageComponent from "discourse/plugins/chat/discourse/components/chat-message";
+import ChatThreadHeading from "discourse/plugins/chat/discourse/components/chat-thread-heading";
+import ChatChannel from "discourse/plugins/chat/discourse/models/chat-channel";
+import ChatMessage from "discourse/plugins/chat/discourse/models/chat-message";
+
+const LIMIT = 20;
+
+export default class ChatSearch extends Component {
+ @service chatSearchQuery;
+ @service router;
+
+ @tracked currentSort = "relevance";
+ @tracked messages = [];
+ @tracked isLoading = false;
+ @tracked offset = 0;
+ @tracked hasMoreResults = false;
+ @tracked lastQuery = null;
+
+ get enableQueryParams() {
+ return this.args.enableQueryParams ?? true;
+ }
+
+ @bind
+ async searchMessages(resetResults = true) {
+ this.searchPromise?.abort();
+
+ if (isBlank(this.args.query)) {
+ this.messages = [];
+ this.offset = 0;
+ this.hasMoreResults = false;
+ return;
+ }
+
+ this.isLoading = true;
+
+ if (resetResults) {
+ this.offset = 0;
+ this.messages = [];
+ }
+
+ try {
+ this.searchPromise = ajax("/chat/api/search", {
+ data: {
+ query: this.args.query,
+ channel_id: this.args.scopedChannelId,
+ sort: this.currentSort,
+ offset: this.offset,
+ limit: LIMIT,
+ },
+ });
+
+ const response = await this.searchPromise;
+
+ const newMessages = (response.messages || []).map((messageObject) => {
+ return ChatMessage.create(
+ ChatChannel.create(messageObject.channel),
+ messageObject
+ );
+ });
+
+ if (resetResults) {
+ this.messages = newMessages;
+ } else {
+ this.messages = [...this.messages, ...newMessages];
+ }
+
+ this.offset += newMessages.length;
+ this.hasMoreResults = response.meta?.has_more || false;
+
+ return this.messages;
+ } finally {
+ this.isLoading = false;
+ }
+ }
+
+ @action
+ sortLabel(sort) {
+ return i18n(`chat.search.sort.${sort}`);
+ }
+
+ @action
+ setCurrentSorting(sort, closeMenu) {
+ this.currentSort = sort;
+ closeMenu();
+ this.searchMessages(true);
+ }
+
+ @action
+ onFilterChange(element) {
+ const value = element.target.value;
+ this.debouncedHandler = discourseDebounce(
+ this.debounceFilterChange,
+ value === "" ? null : value,
+ INPUT_DELAY
+ );
+ }
+
+ @action
+ async loadMore() {
+ if (!this.hasMoreResults || this.isLoading) {
+ return;
+ }
+
+ await this.searchMessages(false);
+ }
+
+ @action
+ debounceFilterChange(query) {
+ this.chatSearchQuery.query = query;
+
+ if (this.enableQueryParams) {
+ this.router.replaceWith({ queryParams: { q: query } });
+ }
+ }
+
+ @action
+ checkQueryChange() {
+ if (this.lastQuery !== this.args.query) {
+ this.lastQuery = this.args.query;
+ this.searchMessages(true);
+ }
+ }
+
+ @action
+ visitMessage(message) {
+ DiscourseURL.routeTo(message.url);
+ }
+
+ @action
+ handleKeypress(message, event) {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ this.visitMessage(message);
+ }
+ }
+
+ accessibleMessageLabel(message) {
+ const username = message.user?.username || i18n("chat.deleted_user");
+ const messagePreview =
+ message.excerpt ||
+ (message.message ? message.message.substring(0, 100) + "..." : "");
+ const threadInfo = message.threadTitle
+ ? i18n("chat.search_view.in_thread", { title: message.threadTitle })
+ : "";
+
+ return i18n("chat.search_view.message_result_label", {
+ username,
+ preview: messagePreview,
+ threadInfo,
+ }).trim();
+ }
+
+ <template>
+ <div
+ class="c-search"
+ {{didInsert this.checkQueryChange}}
+ {{didUpdate this.checkQueryChange @query}}
+ >
+ <div class="chat-search__filters">
+ <FilterInput
+ {{autoFocus}}
+ @filterAction={{this.onFilterChange}}
+ @value={{@query}}
+ @icons={{hash left="magnifying-glass"}}
+ placeholder={{i18n "chat.search_view.filter_placeholder"}}
+ class="no-blur"
+ />
+
+ {{#if @query}}
+ <DButton @icon="xmark" @action={{fn this.debounceFilterChange ""}} />
+ {{/if}}
+
+ <DMenu
+ @identifier="search-sort-options"
+ @label={{this.sortLabel this.currentSort}}
+ @icon="sort"
+ >
+ <:content as |menu|>
+ <DropdownMenu as |dropdown|>
+ <dropdown.item>
+ <DButton
+ @translatedLabel={{this.sortLabel "relevance"}}
+ class="btn-transparent"
+ @action={{fn this.setCurrentSorting "relevance" menu.close}}
+ />
+ </dropdown.item>
+ <dropdown.item>
+ <DButton
+ @translatedLabel={{this.sortLabel "latest"}}
+ class="btn-transparent"
+ @action={{fn this.setCurrentSorting "latest" menu.close}}
+ />
+ </dropdown.item>
+ </DropdownMenu>
+ </:content>
+ </DMenu>
+ </div>
+
+ {{#if @query.length}}
+ {{#if this.messages.length}}
+ <div id="chat-search-instructions" class="sr-only">
+ {{i18n "chat.search_view.sr_instructions"}}
+ </div>
+
+ <ul
+ class="chat-message-search-entries"
+ role="listbox"
+ aria-label={{i18n "chat.search_view.results_list_label"}}
+ >
+ {{#each this.messages key="id" as |message|}}
+ <li
+ class="chat-message-search-entry"
+ role="option"
+ {{on "click" (fn this.visitMessage message)}}
+ {{on "keydown" (fn this.handleKeypress message)}}
+ {{tabToSibling}}
+ tabindex="0"
+ aria-label={{this.accessibleMessageLabel message}}
+ aria-describedby="chat-search-instructions"
+ >
+ <div class="chat-message-search-entry__info">
+ {{#unless @scopedChannelId}}
+ <ChatChannelTitle @channel={{message.channel}} />
+ {{/unless}}
+
+ <ChatThreadHeading
+ @thread={{hash title=message.threadTitle}}
+ />
+ </div>
+
+ <ChatMessageComponent
+ @message={{message}}
+ @disableMouseEvents={{true}}
+ @includeSeparator={{false}}
+ @interactive={{false}}
+ @dateMode="long"
+ />
+ </li>
+ {{/each}}
+ </ul>
+
+ <div class="chat-search-loading">
+ <ConditionalLoadingSpinner @condition={{this.isLoading}} />
+ </div>
+
+ {{#if this.hasMoreResults}}
+ <LoadMore @action={{this.loadMore}} />
+ {{/if}}
+
+ <br />
+ {{else if (not this.isLoading)}}
+ <div class="alert alert-info">
+ {{i18n "chat.search.no_results"}}
+ </div>
+ {{/if}}
+ {{/if}}
+ </div>
+ </template>
+}
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/drawer-routes/channel.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/drawer-routes/channel.gjs
index 9ca5009752b..f2667820df1 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat/drawer-routes/channel.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/drawer-routes/channel.gjs
@@ -1,5 +1,7 @@
import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
import { array } from "@ember/helper";
+import { action } from "@ember/object";
import { service } from "@ember/service";
import Navbar from "discourse/plugins/chat/discourse/components/chat/navbar";
import ChatChannel from "discourse/plugins/chat/discourse/components/chat-channel";
@@ -8,6 +10,14 @@ export default class ChatDrawerRoutesChannel extends Component {
@service chat;
@service chatStateManager;
@service chatHistory;
+ @service siteSettings;
+
+ @tracked isFiltering = false;
+
+ @action
+ toggleIsFiltering() {
+ this.isFiltering = !this.isFiltering;
+ }
get backBtnRoute() {
if (this.chatHistory.previousRoute?.name === "chat.browse") {
@@ -26,6 +36,14 @@ export default class ChatDrawerRoutesChannel extends Component {
<navbar.BackButton @route={{this.backBtnRoute}} />
<navbar.ChannelTitle @channel={{@model.channel}} />
<navbar.Actions as |a|>
+ {{#if this.siteSettings.chat_search_enabled}}
+ <a.Filter
+ @channel={{@model.channel}}
+ @onToggleFilter={{this.toggleIsFiltering}}
+ @isFiltering={{this.isFiltering}}
+ />
+ {{/if}}
+
<a.ThreadsListButton @channel={{@model.channel}} />
<a.ToggleDrawerButton />
<a.FullPageButton />
@@ -39,6 +57,8 @@ export default class ChatDrawerRoutesChannel extends Component {
<ChatChannel
@targetMessageId={{readonly @params.messageId}}
@channel={{channel}}
+ @isFiltering={{this.isFiltering}}
+ @onToggleFilter={{this.toggleIsFiltering}}
/>
{{/each}}
</div>
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/drawer-routes/search.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/drawer-routes/search.gjs
new file mode 100644
index 00000000000..8484cdcd104
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/drawer-routes/search.gjs
@@ -0,0 +1,37 @@
+import Component from "@glimmer/component";
+import { service } from "@ember/service";
+import { i18n } from "discourse-i18n";
+import Navbar from "discourse/plugins/chat/discourse/components/chat/navbar";
+import ChatFooter from "discourse/plugins/chat/discourse/components/chat-footer";
+import ChatSearch from "discourse/plugins/chat/discourse/components/chat-search";
+
+export default class ChatDrawerRoutesSearch extends Component {
+ @service chat;
+ @service chatStateManager;
+ @service chatSearchQuery;
+
+ <template>
+ <div class="c-drawer-routes --search">
+ <Navbar @onClick={{this.chat.toggleDrawer}} as |navbar|>
+ <navbar.BackButton />
+ <navbar.Title @title={{i18n "chat.search.title"}} />
+ <navbar.Actions as |action|>
+ <action.ToggleDrawerButton />
+ <action.FullPageButton />
+ <action.CloseDrawerButton />
+ </navbar.Actions>
+ </Navbar>
+
+ {{#if this.chatStateManager.isDrawerExpanded}}
+ <div class="chat-drawer-content">
+ <ChatSearch
+ @query={{this.chatSearchQuery.query}}
+ @enableQueryParams={{false}}
+ />
+ </div>
+ {{/if}}
+
+ <ChatFooter />
+ </div>
+ </template>
+}
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message/avatar.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/message/avatar.gjs
index 0202a691e0d..fa6603b2c48 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat/message/avatar.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/message/avatar.gjs
@@ -6,7 +6,11 @@ const Avatar = <template>
{{#if @message.chatWebhookEvent.emoji}}
<ChatEmojiAvatar @emoji={{@message.chatWebhookEvent.emoji}} />
{{else}}
- <ChatUserAvatar @user={{@message.user}} @avatarSize="medium" />
+ <ChatUserAvatar
+ @user={{@message.user}}
+ @avatarSize="medium"
+ @interactive={{@interactive}}
+ />
{{/if}}
</div>
</template>;
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message/info.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/message/info.gjs
index c3349fa3c18..83dab52a9b8 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat/message/info.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/message/info.gjs
@@ -143,7 +143,10 @@ export default class ChatMessageInfo extends Component {
{{/if}}
<span class="chat-message-info__date">
- {{formatChatDate @message (hash threadContext=@threadContext)}}
+ {{formatChatDate
+ @message
+ (hash threadContext=@threadContext mode=@dateMode)
+ }}
</span>
{{#if @message.bookmark}}
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/navbar/actions.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/actions.gjs
index 255e2e3cac0..908d4e2a46a 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat/navbar/actions.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/actions.gjs
@@ -3,10 +3,12 @@ import BrowseChannelsButton from "./browse-channels-button";
import CloseDrawerButton from "./close-drawer-button";
import CloseThreadButton from "./close-thread-button";
import CloseThreadsButton from "./close-threads-button";
+import Filter from "./filter";
import FullPageButton from "./full-page-button";
import NewChannelButton from "./new-channel-button";
import NewDirectMessageButton from "./new-direct-message-button";
import OpenDrawerButton from "./open-drawer-button";
+import SearchButton from "./search-button";
import ThreadSettingsButton from "./thread-settings-button";
import ThreadTrackingDropdown from "./thread-tracking-dropdown";
import ThreadsListButton from "./threads-list-button";
@@ -28,6 +30,8 @@ const ChatNavbarActions = <template>
CloseDrawerButton=CloseDrawerButton
ToggleDrawerButton=ToggleDrawerButton
FullPageButton=FullPageButton
+ Filter=Filter
+ SearchButton=SearchButton
)
}}
</nav>
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/navbar/filter.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/filter.gjs
new file mode 100644
index 00000000000..fe4d0640985
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/filter.gjs
@@ -0,0 +1,11 @@
+import DButton from "discourse/components/d-button";
+
+const ChatNavbarFilter = <template>
+ <DButton
+ @icon={{if @isFiltering "filter-circle-xmark" "filter"}}
+ @action={{@onToggleFilter}}
+ class="btn-transparent c-navbar__filter"
+ />
+</template>;
+
+export default ChatNavbarFilter;
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/navbar/search-button.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/search-button.gjs
new file mode 100644
index 00000000000..5b292ad4287
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/search-button.gjs
@@ -0,0 +1,11 @@
+import DButton from "discourse/components/d-button";
+
+const SearchButton = <template>
+ <DButton
+ @icon="magnifying-glass"
+ @route="chat.search"
+ class="btn-transparent"
+ />
+</template>;
+
+export default SearchButton;
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/routes/channel.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/routes/channel.gjs
index 9c617cefe96..5f5c1b34a07 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat/routes/channel.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/routes/channel.gjs
@@ -1,4 +1,6 @@
import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
import { service } from "@ember/service";
import Navbar from "discourse/plugins/chat/discourse/components/chat/navbar";
import ChatSidePanel from "discourse/plugins/chat/discourse/components/chat-side-panel";
@@ -6,6 +8,16 @@ import FullPageChat from "discourse/plugins/chat/discourse/components/full-page-
export default class ChatRoutesChannel extends Component {
@service site;
+ @service siteSettings;
+ @service chat;
+
+ @tracked isFiltering = false;
+
+ @action
+ toggleIsFiltering() {
+ this.isFiltering = !this.isFiltering;
+ this.chat.activeMessage = null;
+ }
get getChannelsRoute() {
return this.args.channel.isDirectMessageChannel
@@ -20,15 +32,25 @@ export default class ChatRoutesChannel extends Component {
<navbar.BackButton @route={{this.getChannelsRoute}} />
{{/if}}
<navbar.ChannelTitle @channel={{@channel}} />
- <navbar.Actions as |action|>
- <action.OpenDrawerButton />
- <action.ThreadsListButton @channel={{@channel}} />
+ <navbar.Actions as |a|>
+ {{#if this.siteSettings.chat_search_enabled}}
+ <a.Filter
+ @channel={{@channel}}
+ @isFiltering={{this.isFiltering}}
+ @onToggleFilter={{this.toggleIsFiltering}}
+ />
+ {{/if}}
+
+ <a.OpenDrawerButton />
+ <a.ThreadsListButton @channel={{@channel}} />
</navbar.Actions>
</Navbar>
<FullPageChat
+ @isFiltering={{this.isFiltering}}
@channel={{@channel}}
@targetMessageId={{@targetMessageId}}
+ @onToggleFilter={{this.toggleIsFiltering}}
/>
</div>
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/routes/channels.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/routes/channels.gjs
index df4eb3c57bc..5cae75ce93b 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat/routes/channels.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/routes/channels.gjs
@@ -1,19 +1,27 @@
+import Component from "@glimmer/component";
+import { service } from "@ember/service";
import { i18n } from "discourse-i18n";
import ChannelsListPublic from "../../channels-list-public";
import Navbar from "../navbar";
-const ChatRoutesChannels = <template>
- <div class="c-routes --channels">
- <Navbar as |navbar|>
- <navbar.Title @title={{i18n "chat.chat_channels"}} />
- <navbar.Actions as |action|>
- <action.OpenDrawerButton />
- <action.BrowseChannelsButton />
- </navbar.Actions>
- </Navbar>
+export default class ChatRoutesChannels extends Component {
+ @service site;
- <ChannelsListPublic />
- </div>
-</template>;
+ <template>
+ <div class="c-routes --channels">
+ <Navbar as |navbar|>
+ <navbar.Title @title={{i18n "chat.chat_channels"}} />
+ <navbar.Actions as |action|>
+ {{#if this.site.mobileView}}
+ <action.SearchButton />
+ {{/if}}
-export default ChatRoutesChannels;
+ <action.OpenDrawerButton />
+ <action.BrowseChannelsButton />
+ </navbar.Actions>
+ </Navbar>
+
+ <ChannelsListPublic />
+ </div>
+ </template>
+}
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/routes/search.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/routes/search.gjs
new file mode 100644
index 00000000000..104bda3c376
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/routes/search.gjs
@@ -0,0 +1,18 @@
+import { i18n } from "discourse-i18n";
+import ChatSearch from "../../chat-search";
+import Navbar from "../navbar";
+
+const ChatRoutesSearch = <template>
+ <div class="c-routes --search">
+ <Navbar as |navbar|>
+ <navbar.BackButton />
+ <navbar.Title @title={{i18n "chat.search.title"}} />
+ <navbar.Actions as |action|>
+ <action.OpenDrawerButton />
+ </navbar.Actions>
+ </Navbar>
+ <ChatSearch @query={{@query}} />
+ </div>
+</template>;
+
+export default ChatRoutesSearch;
diff --git a/plugins/chat/assets/javascripts/discourse/components/full-page-chat.gjs b/plugins/chat/assets/javascripts/discourse/components/full-page-chat.gjs
index 3946f59e94f..9923fdc449e 100644
--- a/plugins/chat/assets/javascripts/discourse/components/full-page-chat.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/full-page-chat.gjs
@@ -3,7 +3,12 @@ import ChatChannel from "./chat-channel";
const FullPageChat = <template>
{{#each (array @channel) as |channel|}}
- <ChatChannel @channel={{channel}} @targetMessageId={{@targetMessageId}} />
+ <ChatChannel
+ @channel={{channel}}
+ @targetMessageId={{@targetMessageId}}
+ @isFiltering={{@isFiltering}}
+ @onToggleFilter={{@onToggleFilter}}
+ />
{{/each}}
</template>;
diff --git a/plugins/chat/assets/javascripts/discourse/helpers/format-chat-date.js b/plugins/chat/assets/javascripts/discourse/helpers/format-chat-date.js
index 88085b2ac7e..2ecc95d3634 100644
--- a/plugins/chat/assets/javascripts/discourse/helpers/format-chat-date.js
+++ b/plugins/chat/assets/javascripts/discourse/helpers/format-chat-date.js
@@ -9,10 +9,16 @@ export default function formatChatDate(message, options = {}) {
const date = moment(new Date(message.createdAt), tz);
const title = date.format(i18n("dates.long_with_year"));
- const display =
- options.mode === "tiny"
- ? date.format(i18n("dates.time_short"))
- : date.format(i18n("dates.time"));
+ let display;
+ if (options.mode === "tiny") {
+ display = date.format(i18n("dates.time_short"));
+ } else if (options.mode === "short") {
+ display = date.format(i18n("dates.time_short_day"));
+ } else if (options.mode === "long") {
+ display = date.format(i18n("dates.long_no_year"));
+ } else {
+ display = date.format(i18n("dates.time"));
+ }
if (message.staged) {
return htmlSafe(
diff --git a/plugins/chat/assets/javascripts/discourse/initializers/chat-sidebar.js b/plugins/chat/assets/javascripts/discourse/initializers/chat-sidebar.js
index ce5117c81ce..c941c00831e 100644
--- a/plugins/chat/assets/javascripts/discourse/initializers/chat-sidebar.js
+++ b/plugins/chat/assets/javascripts/discourse/initializers/chat-sidebar.js
@@ -54,6 +54,38 @@ export default {
);
const chatStateManager = container.lookup("service:chat-state-manager");
+ if (this.siteSettings.chat_search_enabled) {
+ api.addSidebarSection(
+ (BaseCustomSidebarSection, BaseCustomSidebarSectionLink) => {
+ const SidebarChatSearchSectionLink = class extends BaseCustomSidebarSectionLink {
+ route = "chat.search";
+ text = i18n("chat.search.title");
+ title = i18n("chat.search.title");
+ name = "chat-search";
+ prefixType = "icon";
+ prefixValue = "magnifying-glass";
+ };
+
+ const SidebarChatSearchSection = class extends BaseCustomSidebarSection {
+ hideSectionHeader = true;
+ name = "chat-search";
+ title = "";
+
+ get links() {
+ return [new SidebarChatSearchSectionLink()];
+ }
+
+ get text() {
+ return null;
+ }
+ };
+
+ return SidebarChatSearchSection;
+ },
+ CHAT_PANEL
+ );
+ }
+
api.addSidebarSection(
(BaseCustomSidebarSection, BaseCustomSidebarSectionLink) => {
const SidebarChatMyThreadsSectionLink = class extends BaseCustomSidebarSectionLink {
diff --git a/plugins/chat/assets/javascripts/discourse/lib/dates-separators-positioner.js b/plugins/chat/assets/javascripts/discourse/lib/dates-separators-positioner.js
index 79d22d23fb5..6503c57c0b4 100644
--- a/plugins/chat/assets/javascripts/discourse/lib/dates-separators-positioner.js
+++ b/plugins/chat/assets/javascripts/discourse/lib/dates-separators-positioner.js
@@ -3,12 +3,20 @@ import { schedule } from "@ember/runloop";
export default class DatesSeparatorsPositioner {
static apply(list) {
schedule("afterRender", () => {
+ if (!list) {
+ return;
+ }
+
const dates = [
...list.querySelectorAll(".chat-message-separator-date"),
].reverse();
- const height = list.querySelector(
- ".chat-messages-container"
- ).clientHeight;
+ const container = list.querySelector(".chat-messages-container");
+
+ if (!container) {
+ return;
+ }
+
+ const height = container.clientHeight;
dates
.map((date, index) => {
diff --git a/plugins/chat/assets/javascripts/discourse/lib/scroll-helpers.js b/plugins/chat/assets/javascripts/discourse/lib/scroll-helpers.js
index 72df8a99817..30179374ddd 100644
--- a/plugins/chat/assets/javascripts/discourse/lib/scroll-helpers.js
+++ b/plugins/chat/assets/javascripts/discourse/lib/scroll-helpers.js
@@ -27,22 +27,24 @@ export function scrollListToMessage(
message.expanded = true;
}
- schedule("afterRender", () => {
- const messageEl = list.querySelector(
- `.chat-message-container[data-id='${message.id}']`
- );
-
- if (!messageEl) {
- return;
- }
-
- if (opts.highlight) {
- message.highlight();
- }
-
- messageEl.scrollIntoView({
- behavior: "auto",
- block: opts.position || "center",
+ next(() => {
+ schedule("afterRender", () => {
+ const messageEl = list.querySelector(
+ `.chat-message-container[data-id='${message.id}']`
+ );
+
+ if (!messageEl) {
+ return;
+ }
+
+ if (opts.highlight) {
+ message.highlight();
+ }
+
+ messageEl.scrollIntoView({
+ behavior: "auto",
+ block: opts.position || "center",
+ });
});
});
}
diff --git a/plugins/chat/assets/javascripts/discourse/models/chat-channel.js b/plugins/chat/assets/javascripts/discourse/models/chat-channel.js
index 524168ce775..e90b691ce0a 100644
--- a/plugins/chat/assets/javascripts/discourse/models/chat-channel.js
+++ b/plugins/chat/assets/javascripts/discourse/models/chat-channel.js
@@ -141,27 +141,27 @@ export default class ChatChannel {
}
get canDeleteSelf() {
- return this.meta.can_delete_self;
+ return this.meta?.can_delete_self;
}
get canDeleteOthers() {
- return this.meta.can_delete_others;
+ return this.meta?.can_delete_others;
}
get canFlag() {
- return this.meta.can_flag;
+ return this.meta?.can_flag;
}
get userSilenced() {
- return this.meta.user_silenced;
+ return this.meta?.user_silenced;
}
get canModerate() {
- return this.meta.can_moderate;
+ return this.meta?.can_moderate;
}
get canRemoveMembers() {
- return this.meta.can_remove_members;
+ return this.meta?.can_remove_members;
}
get escapedTitle() {
diff --git a/plugins/chat/assets/javascripts/discourse/models/chat-message.js b/plugins/chat/assets/javascripts/discourse/models/chat-message.js
index a1a3cadfbda..3168a2190d9 100644
--- a/plugins/chat/assets/javascripts/discourse/models/chat-message.js
+++ b/plugins/chat/assets/javascripts/discourse/models/chat-message.js
@@ -1,6 +1,7 @@
import { cached, tracked } from "@glimmer/tracking";
import { TrackedArray } from "@ember-compat/tracked-built-ins";
import { getOwnerWithFallback } from "discourse/lib/get-owner";
+import getURL from "discourse/lib/get-url";
import discourseLater from "discourse/lib/later";
import { generateCookFunction, parseMentions } from "discourse/lib/text";
import Bookmark from "discourse/models/bookmark";
@@ -94,12 +95,24 @@ export default class ChatMessage {
this.bookmark = args.bookmark ? Bookmark.create(args.bookmark) : null;
this.mentionedUsers = this.#initMentionedUsers(args.mentioned_users);
this.blocks = args.blocks;
+ this.threadTitle = args.thread_title;
+ this.threadId = args.thread_id;
if (args.thread) {
this.thread = args.thread;
}
}
+ get url() {
+ if (this.threadId) {
+ return getURL(
+ `/chat/c/-/${this.channel.id}/t/${this.threadId}/${this.id}`
+ );
+ }
+
+ return getURL(`/chat/c/-/${this.channel.id}/${this.id}`);
+ }
+
get persisted() {
return !!this.id && !this.staged;
}
diff --git a/plugins/chat/assets/javascripts/discourse/routes/chat/channel/info/search.js b/plugins/chat/assets/javascripts/discourse/routes/chat/channel/info/search.js
new file mode 100644
index 00000000000..8596761a869
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/routes/chat/channel/info/search.js
@@ -0,0 +1,5 @@
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class ChatChannelInfoSearchRoute extends DiscourseRoute {
+ queryParams = { q: { replace: true } };
+}
diff --git a/plugins/chat/assets/javascripts/discourse/routes/chat/search.js b/plugins/chat/assets/javascripts/discourse/routes/chat/search.js
new file mode 100644
index 00000000000..1197592f55a
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/routes/chat/search.js
@@ -0,0 +1,20 @@
+import { service } from "@ember/service";
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class ChatSearchRoute extends DiscourseRoute {
+ @service chat;
+ @service router;
+ @service siteSettings;
+
+ queryParams = { q: { replace: true } };
+
+ activate() {
+ this.chat.activeChannel = null;
+ }
+
+ redirect() {
+ if (!this.siteSettings.chat_search_enabled) {
+ this.router.transitionTo("chat");
+ }
+ }
+}
diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-drawer-router.js b/plugins/chat/assets/javascripts/discourse/services/chat-drawer-router.js
index 136b794ab6c..21ffd439955 100644
--- a/plugins/chat/assets/javascripts/discourse/services/chat-drawer-router.js
+++ b/plugins/chat/assets/javascripts/discourse/services/chat-drawer-router.js
@@ -9,6 +9,7 @@ import ChatDrawerRoutesChannelThread from "discourse/plugins/chat/discourse/comp
import ChatDrawerRoutesChannelThreads from "discourse/plugins/chat/discourse/components/chat/drawer-routes/channel-threads";
import ChatDrawerRoutesChannels from "discourse/plugins/chat/discourse/components/chat/drawer-routes/channels";
import ChatDrawerRoutesDirectMessages from "discourse/plugins/chat/discourse/components/chat/drawer-routes/direct-messages";
+import ChatDrawerRoutesSearch from "discourse/plugins/chat/discourse/components/chat/drawer-routes/search";
import ChatDrawerRoutesThreads from "discourse/plugins/chat/discourse/components/chat/drawer-routes/threads";
const ROUTES = {
@@ -159,6 +160,9 @@ const ROUTES = {
"chat.threads": {
name: ChatDrawerRoutesThreads,
},
+ "chat.search": {
+ name: ChatDrawerRoutesSearch,
+ },
"chat.channel.near-message": {
name: ChatDrawerRoutesChannel,
diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-search-query.js b/plugins/chat/assets/javascripts/discourse/services/chat-search-query.js
new file mode 100644
index 00000000000..e1ebf2ed1aa
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/services/chat-search-query.js
@@ -0,0 +1,6 @@
+import { tracked } from "@glimmer/tracking";
+import Service from "@ember/service";
+
+export default class ChatSearchQuery extends Service {
+ @tracked query = "";
+}
diff --git a/plugins/chat/assets/javascripts/discourse/templates/chat/search.gjs b/plugins/chat/assets/javascripts/discourse/templates/chat/search.gjs
new file mode 100644
index 00000000000..23ff3729617
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/templates/chat/search.gjs
@@ -0,0 +1,6 @@
+import RouteTemplate from "ember-route-template";
+import Search from "discourse/plugins/chat/discourse/components/chat/routes/search";
+
+export default RouteTemplate(
+ <template><Search @query={{@controller.q}} /></template>
+);
diff --git a/plugins/chat/assets/stylesheets/common/chat-channel-filter-bar.scss b/plugins/chat/assets/stylesheets/common/chat-channel-filter-bar.scss
new file mode 100644
index 00000000000..4c64ca8992e
--- /dev/null
+++ b/plugins/chat/assets/stylesheets/common/chat-channel-filter-bar.scss
@@ -0,0 +1,31 @@
+.chat-channel__filter-bar {
+ display: flex;
+ width: 100%;
+ gap: 0.5rem;
+ border-bottom: 1px solid var(--content-border-color);
+ background: var(--secondary);
+ padding: 0.25rem 0.67em;
+ box-sizing: border-box;
+ flex-direction: column;
+
+ > div {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 0.25rem;
+ }
+
+ .filter-input-container {
+ margin-right: auto;
+ border-color: var(--primary-low);
+ width: 100%;
+ max-width: 320px;
+ }
+
+ .chat-channel__filter-position {
+ white-space: nowrap;
+ min-width: 40px;
+ text-align: center;
+ font-size: var(--font-down-1);
+ }
+}
diff --git a/plugins/chat/assets/stylesheets/common/chat-drawer.scss b/plugins/chat/assets/stylesheets/common/chat-drawer.scss
index 1efadb2181a..1834ab0ebb2 100644
--- a/plugins/chat/assets/stylesheets/common/chat-drawer.scss
+++ b/plugins/chat/assets/stylesheets/common/chat-drawer.scss
@@ -60,6 +60,10 @@ html.rtl {
max-width: calc(100% - var(--composer-right));
min-height: 300px !important; // important to override inline styles
+ .chat-search__filters .filter-input-container {
+ max-width: 250px;
+ }
+
.chat-drawer-container {
background: var(--secondary);
border: 1px solid var(--content-border-color);
diff --git a/plugins/chat/assets/stylesheets/common/chat-message-search-entry.scss b/plugins/chat/assets/stylesheets/common/chat-message-search-entry.scss
new file mode 100644
index 00000000000..91c49d32d90
--- /dev/null
+++ b/plugins/chat/assets/stylesheets/common/chat-message-search-entry.scss
@@ -0,0 +1,44 @@
+.chat-message-search-entries {
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+ padding: 0.5rem 0;
+ list-style: none;
+ margin: 0;
+}
+
+.chat-message-search-entry {
+ border: 1px solid var(--content-border-color);
+ border-radius: var(--d-border-radius);
+ padding: 0;
+ cursor: pointer;
+
+ &__info {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ padding: 0.65rem 1rem 0.15rem;
+ }
+
+ &:hover,
+ &:focus {
+ box-shadow: var(--shadow-card);
+ }
+
+ > * {
+ pointer-events: none;
+ }
+
+ .chat-message-container {
+ background: none;
+ }
+
+ .chat-thread__heading {
+ padding: 0;
+ align-items: center;
+
+ h2 {
+ font-size: var(--font-0);
+ }
+ }
+}
diff --git a/plugins/chat/assets/stylesheets/common/chat-message.scss b/plugins/chat/assets/stylesheets/common/chat-message.scss
index 77b8037f662..9fc875a6d55 100644
--- a/plugins/chat/assets/stylesheets/common/chat-message.scss
+++ b/plugins/chat/assets/stylesheets/common/chat-message.scss
@@ -42,6 +42,10 @@
display: flex;
min-width: 0;
+ .search-highlight {
+ background: var(--highlight-medium);
+ }
+
.chat-message-reaction {
@include chat-reaction;
will-change: scale;
diff --git a/plugins/chat/assets/stylesheets/common/chat-search.scss b/plugins/chat/assets/stylesheets/common/chat-search.scss
new file mode 100644
index 00000000000..4793a08ff29
--- /dev/null
+++ b/plugins/chat/assets/stylesheets/common/chat-search.scss
@@ -0,0 +1,23 @@
+.c-routes.--search .c-search {
+ padding-block: 1.25rem;
+ margin-inline: 1rem;
+}
+
+.c-routes.--search .c-search,
+.c-drawer-routes.--search {
+ .alert {
+ margin-top: 0.5rem;
+ }
+}
+
+.chat-search__filters {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ flex-wrap: wrap;
+
+ .filter-input-container {
+ width: 100%;
+ max-width: 500px;
+ }
+}
diff --git a/plugins/chat/assets/stylesheets/common/index.scss b/plugins/chat/assets/stylesheets/common/index.scss
index 9d38abf2752..49e7216ccf8 100644
--- a/plugins/chat/assets/stylesheets/common/index.scss
+++ b/plugins/chat/assets/stylesheets/common/index.scss
@@ -69,3 +69,6 @@
@import "chat-message-text";
@import "chat-messages-scroller";
@import "chat-footer";
+@import "chat-message-search-entry";
+@import "chat-channel-filter-bar";
+@import "chat-search";
diff --git a/plugins/chat/assets/stylesheets/desktop/chat-index-drawer.scss b/plugins/chat/assets/stylesheets/desktop/chat-index-drawer.scss
index 3377dae8622..d51f9b2e2a7 100644
--- a/plugins/chat/assets/stylesheets/desktop/chat-index-drawer.scss
+++ b/plugins/chat/assets/stylesheets/desktop/chat-index-drawer.scss
@@ -48,6 +48,7 @@
.chat-drawer-container .c-channel-settings,
.chat-drawer-container .c-channel-info__nav,
.chat-drawer-container .c-channel-members,
+.chat-drawer-container .c-search,
.chat-drawer-container .chat-message-creator-container {
padding: 1rem;
width: auto;
diff --git a/plugins/chat/assets/stylesheets/mobile/chat-channel-search.scss b/plugins/chat/assets/stylesheets/mobile/chat-channel-search.scss
new file mode 100644
index 00000000000..fdb31c0ccb8
--- /dev/null
+++ b/plugins/chat/assets/stylesheets/mobile/chat-channel-search.scss
@@ -0,0 +1,8 @@
+.c-channel-search {
+ html.footer-nav-ipad &,
+ html.footer-nav-visible & {
+ padding-bottom: calc(
+ env(safe-area-inset-bottom) + var(--footer-nav-height, 0px)
+ );
+ }
+}
diff --git a/plugins/chat/assets/stylesheets/mobile/index.scss b/plugins/chat/assets/stylesheets/mobile/index.scss
index 5e2eab04656..32ccf06e3f1 100644
--- a/plugins/chat/assets/stylesheets/mobile/index.scss
+++ b/plugins/chat/assets/stylesheets/mobile/index.scss
@@ -12,6 +12,7 @@
@import "chat-channel-row";
@import "chat-channel-members";
@import "chat-channel-settings";
+@import "chat-channel-search";
@import "chat-form";
@import "chat-modal-thread-settings";
@import "chat-navbar";
diff --git a/plugins/chat/config/locales/client.en.yml b/plugins/chat/config/locales/client.en.yml
index ad1ff821d16..c6407acbff9 100644
--- a/plugins/chat/config/locales/client.en.yml
+++ b/plugins/chat/config/locales/client.en.yml
@@ -330,6 +330,13 @@ en:
today: Today
yesterday: Yesterday
+ search_view:
+ filter_placeholder: Search messages
+ message_result_label: "Chat message from %{username}: %{preview} %{threadInfo}"
+ in_thread: "in thread %{title}"
+ sr_instructions: "Press Enter or Space to open message. Use Tab to navigate between results."
+ results_list_label: "Chat message search results"
+
members_view:
filter_placeholder: Find members
add_member: Add Member
@@ -348,6 +355,7 @@ en:
tabs:
members: Members
settings: Settings
+ search: Search
remove_member: "Remove"
new_message_modal:
@@ -515,6 +523,14 @@ en:
confirm_export: "This exports all messages from all channels and sends the result to you in a personal message. Are you sure you want to export?"
export_has_started: "The export has started. You'll receive a PM when it's ready."
+ search:
+ title: Search chat
+ aria_label: "Switch to chat search"
+ no_results: "No results found"
+ sort:
+ relevance: "Relevance"
+ latest: "Latest"
+
my_threads:
title: My Threads
aria_label: "Switch to my threads list"
diff --git a/plugins/chat/config/locales/server.en.yml b/plugins/chat/config/locales/server.en.yml
index 1e1b910cb0a..577e519ab65 100644
--- a/plugins/chat/config/locales/server.en.yml
+++ b/plugins/chat/config/locales/server.en.yml
@@ -25,6 +25,7 @@ en:
chat_editing_grace_period_max_diff_high_trust: "Maximum number of character changes allowed in chat editing grace period, if more changed display the (edited) tag by the chat message (trust level 2 and up)."
chat_preferred_index: "Preferred tab when loading /chat."
allow_chat_in_anonymous_mode: "Enable this setting to allow users who are browsing your site anonymously to use chat. This setting requires the `allow anonymous mode` setting to be enabled."
+ chat_search_enabled: "Enable this setting to allow users to search chat messages."
errors:
chat_default_channel: "The default chat channel must be a public channel."
direct_message_enabled_groups_invalid: "You must specify at least one group for this setting. If you do not want anyone except staff to send direct messages, choose the staff group."
diff --git a/plugins/chat/config/routes.rb b/plugins/chat/config/routes.rb
index 4076fa416ca..9bb582a0cf2 100644
--- a/plugins/chat/config/routes.rb
+++ b/plugins/chat/config/routes.rb
@@ -18,6 +18,7 @@ Chat::Engine.routes.draw do
get "/channels/:channel_id" => "channels#show"
put "/channels/:channel_id/status" => "channels_status#update"
get "/channels/:channel_id/messages" => "channel_messages#index"
+ get "/search" => "search#index"
put "/channels/:channel_id/messages/:message_id" => "channel_messages#update"
post "/channels/:channel_id/messages/moves" => "channels_messages_moves#create"
delete "/channels/:channel_id/messages/:message_id/streaming" =>
@@ -88,6 +89,7 @@ Chat::Engine.routes.draw do
# chat_controller routes
get "/" => "chat#respond"
+ get "/search" => "chat#respond"
get "/new-message" => "chat#respond"
get "/direct-messages" => "chat#respond"
get "/channels" => "chat#respond"
@@ -108,7 +110,7 @@ Chat::Engine.routes.draw do
get base_c_route => "chat#respond", :as => "channel"
get "#{base_c_route}/:message_id" => "chat#respond"
- %w[info info/about info/members info/settings].each do |route|
+ %w[info info/about info/members info/settings info/search].each do |route|
get "#{base_c_route}/#{route}" => "chat#respond"
end
@@ -123,7 +125,7 @@ Chat::Engine.routes.draw do
get base_channel_route, to: redirect(redirect_base)
- %w[info info/about info/members info/settings].each do |route|
+ %w[info info/about info/members info/settings info/search].each do |route|
get "#{base_channel_route}/#{route}", to: redirect("#{redirect_base}/#{route}")
end
end
diff --git a/plugins/chat/config/settings.yml b/plugins/chat/config/settings.yml
index 1e3f77b01f3..adf008cf075 100644
--- a/plugins/chat/config/settings.yml
+++ b/plugins/chat/config/settings.yml
@@ -17,6 +17,10 @@ chat:
client: true
default: false
hidden: true
+ chat_search_enabled:
+ client: true
+ default: false
+ hidden: true
needs_chat_seeded:
default: true
hidden: true
diff --git a/plugins/chat/db/migrate/20250903091723_create_chat_message_search_data.rb b/plugins/chat/db/migrate/20250903091723_create_chat_message_search_data.rb
new file mode 100644
index 00000000000..b7df2812c2a
--- /dev/null
+++ b/plugins/chat/db/migrate/20250903091723_create_chat_message_search_data.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+class CreateChatMessageSearchData < ActiveRecord::Migration[7.1]
+ def change
+ create_table :chat_message_search_data, id: false do |t|
+ t.bigint :chat_message_id, null: false, primary_key: true
+ t.tsvector :search_data
+ t.text :raw_data
+ t.text :locale
+ t.integer :version, default: 0
+ end
+
+ add_index :chat_message_search_data, :search_data, using: :gin, name: "idx_search_chat_message"
+ end
+end
diff --git a/plugins/chat/plugin.rb b/plugins/chat/plugin.rb
index 8697f666b23..dd69a89e988 100644
--- a/plugins/chat/plugin.rb
+++ b/plugins/chat/plugin.rb
@@ -25,6 +25,9 @@ register_svg_icon "file-audio"
register_svg_icon "file-video"
register_svg_icon "file-image"
register_svg_icon "circle-stop"
+register_svg_icon "filter"
+register_svg_icon "filter-circle-xmark"
+register_svg_icon "sort"
# route: /admin/plugins/chat
add_admin_route "chat.admin.title", "chat", use_new_show_route: true
@@ -49,6 +52,32 @@ after_initialize do
register_category_custom_field_type(Chat::HAS_CHAT_ENABLED, :boolean)
+ register_search_index(
+ model_class: Chat::Message,
+ search_data_class: Chat::MessageSearchData,
+ index_version: 1,
+ search_data:
+ proc do |message, indexer_helper|
+ {
+ a_weight: message.message,
+ d_weight: indexer_helper.scrub_html(message.cooked)[0..600_000],
+ }
+ end,
+ load_unindexed_record_ids:
+ proc do |limit:, index_version:|
+ Chat::Message
+ .joins("LEFT JOIN chat_message_search_data ON chat_message_id = chat_messages.id")
+ .where(
+ "chat_message_search_data.locale IS NULL OR chat_message_search_data.locale != ? OR chat_message_search_data.version != ?",
+ SiteSetting.default_locale,
+ index_version,
+ )
+ .order("chat_messages.id ASC")
+ .limit(limit)
+ .pluck(:id)
+ end,
+ )
+
register_user_custom_field_type(Chat::LAST_CHAT_CHANNEL_ID, :integer)
DiscoursePluginRegistry.serialized_current_user_fields << Chat::LAST_CHAT_CHANNEL_ID
DiscoursePluginRegistry.register_flag_applies_to_type("Chat::Message", self)
diff --git a/plugins/chat/spec/models/chat/message_spec.rb b/plugins/chat/spec/models/chat/message_spec.rb
index b5effc5fede..08b610bd161 100644
--- a/plugins/chat/spec/models/chat/message_spec.rb
+++ b/plugins/chat/spec/models/chat/message_spec.rb
@@ -4,6 +4,7 @@ describe Chat::Message do
fab!(:message) { Fabricate(:chat_message, message: "hey friend, what's up?!") }
it { is_expected.to have_many(:chat_mentions).dependent(:destroy) }
+ it { is_expected.to have_one(:message_search_data).dependent(:destroy) }
it "supports custom fields" do
message.custom_fields["test"] = "test"
@@ -751,6 +752,20 @@ describe Chat::Message do
expect { upload_reference_1.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
+ it "destroys message_search_data" do
+ message_1 = Fabricate(:chat_message)
+ search_data_1 =
+ Chat::MessageSearchData.create!(
+ chat_message_id: message_1.id,
+ search_data: "test search data",
+ raw_data: "test",
+ )
+
+ message_1.destroy!
+
+ expect { search_data_1.reload }.to raise_error(ActiveRecord::RecordNotFound)
+ end
+
describe "bookmarks" do
before { register_test_bookmarkable(Chat::MessageBookmarkable) }
diff --git a/plugins/chat/spec/services/actions/search_for_messages_spec.rb b/plugins/chat/spec/services/actions/search_for_messages_spec.rb
new file mode 100644
index 00000000000..af27c1870b2
--- /dev/null
+++ b/plugins/chat/spec/services/actions/search_for_messages_spec.rb
@@ -0,0 +1,275 @@
+# frozen_string_literal: true
+
+RSpec.describe Chat::Action::SearchForMessages do
+ describe ".call" do
+ subject(:action) { described_class.call(guardian:, params:, channel:) }
+
+ fab!(:current_user, :user)
+ fab!(:channel, :chat_channel)
+ fab!(:message_1) { Fabricate(:chat_message, chat_channel: channel, message: "hello world") }
+ fab!(:message_2) { Fabricate(:chat_message, chat_channel: channel, message: "test message") }
+ fab!(:message_3) { Fabricate(:chat_message, chat_channel: channel, message: "another test") }
+
+ let(:guardian) { current_user.guardian }
+ let(:params) { Chat::SearchMessage::Contract.new(args) }
+ let(:args) { { limit: 20, offset: 0, query: } }
+ let(:query) { "test" }
+ let(:messages) { action[:messages] }
+
+ before do
+ SearchIndexer.enable
+ SiteSetting.chat_enabled = true
+ channel.add(current_user)
+ [message_1, message_2, message_3].each { SearchIndexer.index(_1, force: true) }
+ end
+
+ it "returns matching messages" do
+ expect(messages).to contain_exactly(message_2, message_3)
+ end
+
+ context "when no messages match" do
+ let(:query) { "nonexistent" }
+
+ it "returns no messages" do
+ expect(messages).to be_empty
+ end
+ end
+
+ context "with @username filter" do
+ fab!(:alice) { Fabricate(:user, username: "alice") }
+ fab!(:bob) { Fabricate(:user, username: "bob") }
+ fab!(:alice_message_1) do
+ Fabricate(:chat_message, chat_channel: channel, user: alice, message: "hello from alice")
+ end
+ fab!(:alice_message_2) do
+ Fabricate(:chat_message, chat_channel: channel, user: alice, message: "testing something")
+ end
+ fab!(:bob_message) do
+ Fabricate(:chat_message, chat_channel: channel, user: bob, message: "hello from bob")
+ end
+
+ before do
+ [alice_message_1, alice_message_2, bob_message].each do
+ SearchIndexer.index(_1, force: true)
+ end
+ end
+
+ context "when searching with @username and term" do
+ let(:query) { "@alice hello" }
+
+ it "returns only messages from that user matching the term" do
+ expect(messages).to contain_exactly(alice_message_1)
+ end
+ end
+
+ context "when searching with @username only" do
+ let(:query) { "@alice" }
+
+ it "returns all messages from that user" do
+ expect(messages).to contain_exactly(alice_message_1, alice_message_2)
+ end
+ end
+
+ context "when searching with @me" do
+ fab!(:current_user_message) do
+ Fabricate(:chat_message, chat_channel: channel, user: current_user, message: "my message")
+ end
+
+ let(:query) { "@me" }
+
+ before { SearchIndexer.index(current_user_message, force: true) }
+
+ it "returns messages from the current user" do
+ expect(messages).to contain_exactly(current_user_message)
+ end
+ end
+
+ context "when username doesn't exist" do
+ let(:query) { "@nonexistent hello" }
+
+ it "searches for the literal @nonexistent text" do
+ expect(messages).to be_empty
+ end
+ end
+
+ context "when username is upcase" do
+ let(:query) { "@ALICE hello" }
+
+ it "returns messages from alice regardless of case" do
+ expect(messages).to contain_exactly(alice_message_1)
+ end
+ end
+
+ context "with multiple @username filters" do
+ let(:query) { "@alice @bob hello" }
+
+ it "returns no results since no message can be from both users" do
+ expect(messages).to be_empty
+ end
+ end
+ end
+
+ context "with limit parameter" do
+ fab!(:message_4) { Fabricate(:chat_message, chat_channel: channel, message: "test four") }
+ fab!(:message_5) { Fabricate(:chat_message, chat_channel: channel, message: "test five") }
+
+ before do
+ args[:limit] = 2
+ [message_4, message_5].each { SearchIndexer.index(_1, force: true) }
+ end
+
+ it "limits the number of results" do
+ expect(messages.size).to eq(2)
+ end
+ end
+
+ context "with pagination" do
+ fab!(:message_4) { Fabricate(:chat_message, chat_channel: channel, message: "test four") }
+ fab!(:message_5) { Fabricate(:chat_message, chat_channel: channel, message: "test five") }
+ fab!(:message_6) { Fabricate(:chat_message, chat_channel: channel, message: "test six") }
+
+ before { [message_4, message_5, message_6].each { SearchIndexer.index(_1, force: true) } }
+
+ context "with offset parameter" do
+ let(:all_results) do
+ described_class.call(
+ guardian:,
+ channel:,
+ params: Chat::SearchMessage::Contract.new(query:),
+ )[
+ :messages
+ ]
+ end
+
+ before { args[:offset] = 2 }
+
+ it "skips the specified number of results" do
+ expect(messages).to eq(all_results.drop(2))
+ end
+ end
+
+ context "with has_more indicator" do
+ context "when there are more results" do
+ before { args[:limit] = 2 }
+
+ it "sets has_more to true" do
+ expect(action).to include(has_more: true, limit: 2)
+ end
+ end
+
+ context "when there are no more results" do
+ before { args[:limit] = 10 }
+
+ it "sets has_more to false" do
+ expect(action).to include(has_more: false, limit: 10)
+ end
+ end
+
+ context "when offset is used" do
+ before do
+ args[:limit] = 2
+ args[:offset] = 3
+ end
+
+ it "sets has_more correctly based on remaining results" do
+ expect(action).to include(has_more: false, limit: 2, offset: 3)
+ end
+ end
+ end
+
+ context "with combined offset and limit" do
+ let(:all_results) do
+ described_class.call(
+ guardian:,
+ channel:,
+ params: Chat::SearchMessage::Contract.new(query:),
+ )[
+ :messages
+ ]
+ end
+
+ before do
+ args[:offset] = 1
+ args[:limit] = 2
+ end
+
+ it "returns the correct page of results" do
+ expect(messages).to eq(all_results[1..2])
+ end
+ end
+ end
+
+ context "with exclude_threads parameter" do
+ fab!(:original_message) do
+ Fabricate(:chat_message, chat_channel: channel, message: "original test message")
+ end
+ fab!(:thread) { Fabricate(:chat_thread, channel:, original_message: original_message) }
+ fab!(:thread_reply) do
+ Fabricate(:chat_message, chat_channel: channel, thread:, message: "thread reply test")
+ end
+ fab!(:regular_message) do
+ Fabricate(:chat_message, chat_channel: channel, message: "regular test message")
+ end
+
+ before do
+ [original_message, thread_reply, regular_message].each do
+ SearchIndexer.index(_1, force: true)
+ end
+ end
+
+ context "when exclude_threads is false (default)" do
+ before { args[:exclude_threads] = false }
+
+ it "includes all matching messages including thread replies" do
+ expect(messages).to include(original_message, thread_reply, regular_message)
+ end
+ end
+
+ context "when exclude_threads is true" do
+ before { args[:exclude_threads] = true }
+
+ it "excludes thread replies but keeps original thread messages and regular messages" do
+ expect(messages).to include(original_message, regular_message)
+ expect(messages).not_to include(thread_reply)
+ end
+ end
+ end
+
+ context "when channel is not provided (global search)" do
+ subject(:action) { described_class.call(guardian:, params:, channel: nil) }
+
+ fab!(:channel_2, :chat_channel)
+ fab!(:private_channel, :private_category_channel)
+ fab!(:channel_1_message) do
+ Fabricate(:chat_message, chat_channel: channel, message: "global search test")
+ end
+ fab!(:channel_2_message) do
+ Fabricate(:chat_message, chat_channel: channel_2, message: "another global test")
+ end
+ fab!(:private_channel_message) do
+ Fabricate(:chat_message, chat_channel: private_channel, message: "private global test")
+ end
+
+ let(:query) { "global" }
+
+ before do
+ channel_2.add(current_user)
+ [channel_1_message, channel_2_message, private_channel_message].each do
+ SearchIndexer.index(_1, force: true)
+ end
+ end
+
+ it "returns messages from multiple accessible channels" do
+ expect(messages).to contain_exactly(channel_1_message, channel_2_message)
+ end
+
+ it "excludes messages from inaccessible channels" do
+ expect(messages).not_to include(private_channel_message)
+ end
+
+ it "searches across all accessible channels" do
+ expect(messages.map(&:chat_channel)).to contain_exactly(channel, channel_2)
+ end
+ end
+ end
+end
diff --git a/plugins/chat/spec/services/chat/action/search_message/apply_filters_and_sorting_spec.rb b/plugins/chat/spec/services/chat/action/search_message/apply_filters_and_sorting_spec.rb
new file mode 100644
index 00000000000..d9f79130752
--- /dev/null
+++ b/plugins/chat/spec/services/chat/action/search_message/apply_filters_and_sorting_spec.rb
@@ -0,0 +1,143 @@
+# frozen_string_literal: true
+
+RSpec.describe Chat::Action::SearchMessage::ApplyFiltersAndSorting do
+ subject(:result) do
+ described_class.call(messages: messages, exclude_threads: exclude_threads, sort: sort)
+ end
+
+ fab!(:current_user, :user)
+ fab!(:channel, :chat_channel)
+
+ let(:messages) { Chat::Message.where(chat_channel: channel) }
+ let(:exclude_threads) { false }
+ let(:sort) { "relevance" }
+
+ before do
+ channel.add(current_user)
+ SiteSetting.chat_enabled = true
+ end
+
+ context "with thread exclusion" do
+ fab!(:regular_message) do
+ Fabricate(:chat_message, chat_channel: channel, message: "regular message")
+ end
+ fab!(:original_message) do
+ Fabricate(:chat_message, chat_channel: channel, message: "original message")
+ end
+ fab!(:thread) { Fabricate(:chat_thread, channel: channel, original_message: original_message) }
+ fab!(:thread_reply) do
+ Fabricate(:chat_message, chat_channel: channel, thread: thread, message: "thread reply")
+ end
+
+ context "when exclude_threads is true" do
+ let(:exclude_threads) { true }
+
+ it "excludes thread replies" do
+ expect(result).not_to include(thread_reply)
+ end
+
+ it "includes original thread messages" do
+ expect(result).to include(original_message)
+ end
+
+ it "includes regular messages" do
+ expect(result).to include(regular_message)
+ end
+ end
+
+ context "when exclude_threads is false" do
+ let(:exclude_threads) { false }
+
+ it "includes all messages" do
+ expect(result).to contain_exactly(regular_message, original_message, thread_reply)
+ end
+ end
+ end
+
+ context "with sorting" do
+ fab!(:message_1) do
+ Fabricate(:chat_message, chat_channel: channel, created_at: 3.days.ago, message: "oldest")
+ end
+ fab!(:message_2) do
+ Fabricate(:chat_message, chat_channel: channel, created_at: 2.days.ago, message: "middle")
+ end
+ fab!(:message_3) do
+ Fabricate(:chat_message, chat_channel: channel, created_at: 1.day.ago, message: "newest")
+ end
+
+ context "when sort is 'latest'" do
+ let(:sort) { "latest" }
+
+ it "orders messages by created_at descending" do
+ expect(result.to_a).to eq([message_3, message_2, message_1])
+ end
+ end
+
+ context "when sort is 'relevance'" do
+ let(:sort) { "relevance" }
+
+ it "returns all messages without specific ordering" do
+ expect(result).to contain_exactly(message_1, message_2, message_3)
+ end
+ end
+
+ context "when sort is nil" do
+ let(:sort) { nil }
+
+ it "returns all messages without specific ordering" do
+ expect(result).to contain_exactly(message_1, message_2, message_3)
+ end
+ end
+ end
+
+ context "with both thread exclusion and sorting" do
+ fab!(:regular_message) do
+ Fabricate(:chat_message, chat_channel: channel, created_at: 2.days.ago, message: "regular")
+ end
+ fab!(:original_message) do
+ Fabricate(:chat_message, chat_channel: channel, created_at: 3.days.ago, message: "original")
+ end
+ fab!(:thread) { Fabricate(:chat_thread, channel: channel, original_message: original_message) }
+ fab!(:thread_reply) do
+ Fabricate(
+ :chat_message,
+ chat_channel: channel,
+ thread: thread,
+ created_at: 1.day.ago,
+ message: "reply",
+ )
+ end
+
+ let(:exclude_threads) { true }
+ let(:sort) { "latest" }
+
+ it "applies both filters and sorting" do
+ expect(result.to_a).to eq([regular_message, original_message])
+ end
+
+ it "excludes thread replies" do
+ expect(result).not_to include(thread_reply)
+ end
+ end
+
+ context "with multiple threads" do
+ fab!(:thread_1) { Fabricate(:chat_thread, channel: channel) }
+ fab!(:thread_2) { Fabricate(:chat_thread, channel: channel) }
+ fab!(:thread_1_reply) do
+ Fabricate(:chat_message, chat_channel: channel, thread: thread_1, message: "reply 1")
+ end
+ fab!(:thread_2_reply) do
+ Fabricate(:chat_message, chat_channel: channel, thread: thread_2, message: "reply 2")
+ end
+
+ let(:exclude_threads) { true }
+
+ it "includes both original messages" do
+ expect(result).to include(thread_1.original_message, thread_2.original_message)
+ end
+
+ it "excludes all thread replies" do
+ expect(result).not_to include(thread_1_reply, thread_2_reply)
+ end
+ end
+end
diff --git a/plugins/chat/spec/services/chat/action/search_message/process_search_query_spec.rb b/plugins/chat/spec/services/chat/action/search_message/process_search_query_spec.rb
new file mode 100644
index 00000000000..b56015256aa
--- /dev/null
+++ b/plugins/chat/spec/services/chat/action/search_message/process_search_query_spec.rb
@@ -0,0 +1,498 @@
+# frozen_string_literal: true
+
+RSpec.describe Chat::Action::SearchMessage::ProcessSearchQuery do
+ subject(:result) { described_class.call(query:, messages:, guardian:) }
+
+ fab!(:current_user, :user)
+ fab!(:channel, :chat_channel)
+ fab!(:alice) { Fabricate(:user, username: "alice") }
+ fab!(:bob) { Fabricate(:user, username: "bob") }
+
+ let(:guardian) { Guardian.new(current_user) }
+ let(:messages) { Chat::Message.joins(:chat_channel).where(chat_channel: channel) }
+ let(:query) { "hello world" }
+
+ before do
+ channel.add(current_user)
+ SearchIndexer.enable
+ SiteSetting.chat_enabled = true
+ Chat::Message.all.each { SearchIndexer.index(_1, force: true) }
+ end
+
+ context "with no filters" do
+ let(:query) { "hello world" }
+ let(:ts_query) do
+ Search.ts_query(term: Search.prepare_data(query), ts_config: Search.ts_config)
+ end
+
+ it "returns the original query as processed_query" do
+ expect(result.processed_query).to eq("hello world")
+ end
+
+ it "returns empty filters array" do
+ expect(result.filters).to be_empty
+ end
+
+ it "returns the proper messages relation" do
+ expect(result.messages).to eq(
+ messages.joins(:message_search_data).where(
+ "chat_message_search_data.search_data @@ #{ts_query}",
+ ),
+ )
+ end
+ end
+
+ context "with @username filter" do
+ fab!(:alice_message) do
+ Fabricate(:chat_message, chat_channel: channel, user: alice, message: "hello from alice")
+ end
+ fab!(:bob_message) do
+ Fabricate(:chat_message, chat_channel: channel, user: bob, message: "hello from bob")
+ end
+
+ let(:query) { "@alice hello" }
+
+ it "extracts username filter" do
+ expect(result.filters).to contain_exactly([:username, "alice"])
+ end
+
+ it "removes @username from processed_query" do
+ expect(result.processed_query).to eq("hello")
+ end
+
+ it "filters messages by username" do
+ expect(result.messages).to contain_exactly(alice_message)
+ end
+
+ context "when username is case insensitive" do
+ let(:query) { "@ALICE hello" }
+
+ it "extracts username as-is from query" do
+ expect(result.filters).to contain_exactly([:username, "ALICE"])
+ end
+
+ it "filters messages correctly regardless of case" do
+ expect(result.messages).to contain_exactly(alice_message)
+ end
+ end
+
+ context "when username is @me" do
+ fab!(:current_user_message) do
+ Fabricate(:chat_message, chat_channel: channel, user: current_user, message: "my message")
+ end
+
+ let(:query) { "@me message" }
+
+ it "extracts me filter" do
+ expect(result.filters).to contain_exactly([:username, "me"])
+ end
+
+ it "filters messages by current user" do
+ expect(result.messages).to contain_exactly(current_user_message)
+ end
+ end
+
+ context "when username doesn't exist" do
+ let(:query) { "@nonexistent hello" }
+
+ it "extracts the filter" do
+ expect(result.filters).to contain_exactly([:username, "nonexistent"])
+ end
+
+ it "returns no messages" do
+ expect(result.messages).to be_empty
+ end
+ end
+
+ context "with multiple @username filters" do
+ let(:query) { "@alice @bob hello" }
+
+ it "extracts both username filters" do
+ expect(result.filters).to contain_exactly([:username, "alice"], [:username, "bob"])
+ end
+
+ it "removes both @usernames from processed_query" do
+ expect(result.processed_query).to eq("hello")
+ end
+
+ it "returns no messages since one message can't be from both users" do
+ expect(result.messages).to be_empty
+ end
+ end
+
+ context "with staged user" do
+ fab!(:staged_user) { Fabricate(:user, username: "staged", staged: true) }
+ fab!(:staged_message) do
+ Fabricate(
+ :chat_message,
+ chat_channel: channel,
+ user: staged_user,
+ message: "staged message",
+ )
+ end
+
+ let(:query) { "@staged hello" }
+
+ it "excludes messages from staged users" do
+ expect(result.messages).to be_empty
+ end
+ end
+
+ context "when guardian user is nil and using @me" do
+ let(:guardian) { Guardian.new(nil) }
+ let(:query) { "@me hello" }
+
+ it "returns no messages" do
+ expect(result.messages).to be_empty
+ end
+ end
+
+ context "with username containing special characters" do
+ fab!(:user_underscore) { Fabricate(:user, username: "user_underscore") }
+ fab!(:message) do
+ Fabricate(:chat_message, chat_channel: channel, user: user_underscore, message: "message")
+ end
+
+ let(:query) { "@user_underscore message" }
+
+ it "normalizes and filters correctly" do
+ expect(result.messages).to contain_exactly(message)
+ end
+ end
+ end
+
+ context "with #channel filter" do
+ fab!(:other_channel) { Fabricate(:chat_channel, slug: "other-channel") }
+ fab!(:channel_message) do
+ Fabricate(:chat_message, chat_channel: channel, message: "message in main channel")
+ end
+ fab!(:other_channel_message) do
+ Fabricate(:chat_message, chat_channel: other_channel, message: "message in other channel")
+ end
+
+ let(:messages) { Chat::Message.joins(:chat_channel) }
+ let(:query) { "##{channel.slug} message" }
+
+ before { other_channel.add(current_user) }
+
+ it "extracts channel filter" do
+ expect(result.filters).to contain_exactly([:channel, channel.slug])
+ end
+
+ it "removes #channel from processed_query" do
+ expect(result.processed_query).to eq("message")
+ end
+
+ it "filters messages by channel" do
+ expect(result.messages).to contain_exactly(channel_message)
+ end
+
+ context "when channel slug is case insensitive" do
+ let(:query) { "##{channel.slug.upcase} message" }
+
+ it "extracts slug as-is from query" do
+ expect(result.filters).to contain_exactly([:channel, channel.slug.upcase])
+ end
+
+ it "filters messages correctly regardless of case" do
+ expect(result.messages).to contain_exactly(channel_message)
+ end
+ end
+
+ context "when channel doesn't exist" do
+ let(:query) { "#nonexistent hello" }
+
+ it "extracts the filter" do
+ expect(result.filters).to contain_exactly([:channel, "nonexistent"])
+ end
+
+ it "returns no messages" do
+ expect(result.messages).to be_empty
+ end
+ end
+
+ context "when user cannot view the channel" do
+ fab!(:private_channel, :private_category_channel)
+ fab!(:private_message) do
+ Fabricate(:chat_message, chat_channel: private_channel, message: "private message")
+ end
+
+ let(:query) { "##{private_channel.slug} hello" }
+
+ it "returns no messages" do
+ expect(result.messages).to be_empty
+ end
+ end
+
+ context "when guardian user is nil for private channel" do
+ let(:guardian) { Guardian.new(nil) }
+
+ fab!(:private_channel, :private_category_channel)
+ fab!(:private_message) do
+ Fabricate(:chat_message, chat_channel: private_channel, message: "private message")
+ end
+
+ let(:query) { "##{private_channel.slug} hello" }
+
+ it "returns no messages" do
+ expect(result.messages).to be_empty
+ end
+ end
+
+ context "with channel slug containing special characters" do
+ fab!(:special_channel) { Fabricate(:chat_channel, slug: "my-special-channel") }
+ fab!(:message) { Fabricate(:chat_message, chat_channel: special_channel, message: "message") }
+
+ before { special_channel.add(current_user) }
+
+ let(:messages) { Chat::Message.joins(:chat_channel) }
+ let(:query) { "#my-special-channel message" }
+
+ it "filters correctly with special characters" do
+ expect(result.messages).to contain_exactly(message)
+ end
+ end
+ end
+
+ context "with mixed filters and terms" do
+ fab!(:alice_message) do
+ Fabricate(:chat_message, chat_channel: channel, user: alice, message: "hello world")
+ end
+
+ let(:query) { "hello @alice world ##{channel.slug}" }
+
+ it "extracts all filters" do
+ expect(result.filters).to contain_exactly([:username, "alice"], [:channel, channel.slug])
+ end
+
+ it "removes all filter terms from processed_query" do
+ expect(result.processed_query).to eq("hello world")
+ end
+ end
+
+ context "with empty query" do
+ let(:query) { "" }
+
+ it "returns empty processed_query" do
+ expect(result.processed_query).to eq("")
+ end
+
+ it "returns empty filters" do
+ expect(result.filters).to be_empty
+ end
+ end
+
+ context "with blank query" do
+ let(:query) { " " }
+
+ it "returns empty processed_query" do
+ expect(result.processed_query).to eq("")
+ end
+
+ it "returns empty filters" do
+ expect(result.filters).to be_empty
+ end
+ end
+
+ context "with filter only query" do
+ fab!(:alice_message) do
+ Fabricate(:chat_message, chat_channel: channel, user: alice, message: "anything")
+ end
+
+ let(:query) { "@alice" }
+
+ it "returns empty processed_query" do
+ expect(result.processed_query).to eq("")
+ end
+
+ it "extracts the filter" do
+ expect(result.filters).to contain_exactly([:username, "alice"])
+ end
+
+ it "filters messages correctly" do
+ expect(result.messages).to contain_exactly(alice_message)
+ end
+ end
+
+ context "with extra whitespace" do
+ fab!(:alice_message) do
+ Fabricate(:chat_message, chat_channel: channel, user: alice, message: "hello world")
+ end
+
+ let(:query) { " hello @alice world " }
+
+ it "normalizes whitespace in processed_query" do
+ expect(result.processed_query).to eq("hello world")
+ end
+
+ it "extracts filters correctly" do
+ expect(result.filters).to contain_exactly([:username, "alice"])
+ end
+ end
+
+ context "for SQL query performance" do
+ fab!(:user1) { Fabricate(:user, username: "user1") }
+ fab!(:user2) { Fabricate(:user, username: "user2") }
+ fab!(:user3) { Fabricate(:user, username: "user3") }
+ fab!(:user4) { Fabricate(:user, username: "user4") }
+ fab!(:user5) { Fabricate(:user, username: "user5") }
+ fab!(:channel2) { Fabricate(:chat_channel, slug: "channel2") }
+ fab!(:channel3) { Fabricate(:chat_channel, slug: "channel3") }
+
+ it "executes constant number of queries regardless of filter count" do
+ queries_with_no_filters =
+ track_sql_queries do
+ described_class.call(query: "hello", messages: messages, guardian: guardian)
+ end
+
+ queries_with_one_username =
+ track_sql_queries do
+ described_class.call(query: "@alice hello", messages: messages, guardian: guardian)
+ end
+
+ queries_with_three_usernames =
+ track_sql_queries do
+ described_class.call(
+ query: "@alice @bob @user1 hello",
+ messages: messages,
+ guardian: guardian,
+ )
+ end
+
+ queries_with_five_usernames =
+ track_sql_queries do
+ described_class.call(
+ query: "@alice @bob @user1 @user2 @user3 hello",
+ messages: messages,
+ guardian: guardian,
+ )
+ end
+
+ queries_with_one_channel =
+ track_sql_queries do
+ described_class.call(
+ query: "##{channel.slug} hello",
+ messages: messages,
+ guardian: guardian,
+ )
+ end
+
+ queries_with_three_channels =
+ track_sql_queries do
+ described_class.call(
+ query: "##{channel.slug} #channel2 #channel3 hello",
+ messages: messages,
+ guardian: guardian,
+ )
+ end
+
+ # No filters should not query users or channels
+ expect(queries_with_no_filters.count).to eq(0)
+
+ # Count user-related queries (excluding SCHEMA and CACHE)
+ user_queries_one = queries_with_one_username.count { |q| q.include?('"users"') }
+ user_queries_three = queries_with_three_usernames.count { |q| q.include?('"users"') }
+ user_queries_five = queries_with_five_usernames.count { |q| q.include?('"users"') }
+
+ # Count channel-related queries
+ channel_queries_one = queries_with_one_channel.count { |q| q.include?('"chat_channels"') }
+ channel_queries_three =
+ queries_with_three_channels.count { |q| q.include?('"chat_channels"') }
+
+ # Verify no N+1: query count should be constant regardless of number of filters
+ expect(user_queries_one).to be > 0
+ expect(user_queries_one).to eq(user_queries_three)
+ expect(user_queries_three).to eq(user_queries_five)
+
+ expect(channel_queries_one).to be > 0
+ expect(channel_queries_one).to eq(channel_queries_three)
+ end
+ end
+
+ context "with filter limit protection" do
+ it "silently limits to 10 filters when more than 10 are provided" do
+ query_with_11_filters =
+ "@user1 @user2 @user3 @user4 @user5 @user6 #chan1 #chan2 #chan3 #chan4 #chan5 hello"
+
+ result =
+ described_class.call(query: query_with_11_filters, messages: messages, guardian: guardian)
+
+ expect(result.filters.size).to eq(10)
+ expect(result.processed_query).to eq("hello")
+ end
+
+ it "processes exactly 10 filters without truncation" do
+ query_with_10_filters =
+ "@user1 @user2 @user3 @user4 @user5 #chan1 #chan2 #chan3 #chan4 #chan5 hello"
+
+ result =
+ described_class.call(query: query_with_10_filters, messages: messages, guardian: guardian)
+
+ expect(result.filters.size).to eq(10)
+ expect(result.processed_query).to eq("hello")
+ end
+
+ it "preserves the first 10 filters when limit is exceeded" do
+ query_with_12_filters =
+ "@user1 @user2 @user3 @user4 @user5 @user6 @user7 #chan1 #chan2 #chan3 #chan4 #chan5 hello"
+
+ result =
+ described_class.call(query: query_with_12_filters, messages: messages, guardian: guardian)
+
+ expect(result.filters.size).to eq(10)
+ expect(result.filters.first).to eq([:username, "user1"])
+ expect(result.filters.last).to eq([:channel, "chan3"])
+ expect(result.processed_query).to eq("hello")
+ end
+ end
+
+ context "with batch filtering" do
+ fab!(:charlie) { Fabricate(:user, username: "charlie") }
+ fab!(:david) { Fabricate(:user, username: "david") }
+ fab!(:channel2) { Fabricate(:chat_channel, slug: "channel2") }
+ fab!(:channel3) { Fabricate(:chat_channel, slug: "channel3") }
+
+ fab!(:alice_msg) do
+ Fabricate(:chat_message, chat_channel: channel, user: alice, message: "hello")
+ end
+ fab!(:bob_msg) { Fabricate(:chat_message, chat_channel: channel, user: bob) }
+ fab!(:charlie_msg) { Fabricate(:chat_message, chat_channel: channel2, user: charlie) }
+ fab!(:david_msg) { Fabricate(:chat_message, chat_channel: channel3, user: david) }
+
+ before do
+ channel2.add(current_user)
+ channel3.add(current_user)
+ end
+
+ let(:messages) { Chat::Message.joins(:chat_channel) }
+
+ it "correctly filters with multiple usernames" do
+ result =
+ described_class.call(query: "@alice @bob hello", messages: messages, guardian: guardian)
+
+ expect(result.messages).to be_empty
+ end
+
+ it "correctly filters with multiple channels" do
+ result =
+ described_class.call(
+ query: "##{channel.slug} #channel2 hello",
+ messages: messages,
+ guardian: guardian,
+ )
+
+ expect(result.messages).to be_empty
+ end
+
+ it "correctly filters with mixed username and channel filters" do
+ result =
+ described_class.call(
+ query: "@alice ##{channel.slug} hello",
+ messages: messages,
+ guardian: guardian,
+ )
+
+ expect(result.messages).to contain_exactly(alice_msg)
+ end
+ end
+end
diff --git a/plugins/chat/spec/services/chat/search_message_spec.rb b/plugins/chat/spec/services/chat/search_message_spec.rb
new file mode 100644
index 00000000000..93a7e0fda2f
--- /dev/null
+++ b/plugins/chat/spec/services/chat/search_message_spec.rb
@@ -0,0 +1,83 @@
+# frozen_string_literal: true
+
+RSpec.describe Chat::SearchMessage do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:query) }
+ it { is_expected.to allow_values(1, 40).for(:limit) }
+ it { is_expected.not_to allow_values(0, 41, nil).for(:limit) }
+ it { is_expected.to allow_values(0).for(:offset) }
+ it { is_expected.not_to allow_values(-1).for(:offset) }
+ it { is_expected.to validate_inclusion_of(:sort).in_array(%w[relevance latest]) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:current_user, :user)
+ fab!(:channel, :chat_channel)
+
+ let(:guardian) { Guardian.new(current_user) }
+ let(:params) { { channel_id: channel.id, query: } }
+ let(:dependencies) { { guardian: } }
+ let(:query) { "test" }
+
+ before do
+ SearchIndexer.enable
+ SiteSetting.chat_enabled = true
+ end
+
+ context "when contract is not valid" do
+ let(:query) {}
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when `channel_id` has been provided" do
+ context "when the channel does not exist" do
+ before { params[:channel_id] = 0 }
+
+ it { is_expected.to fail_to_find_a_model(:channel) }
+ end
+
+ context "when the user cannot view the channel" do
+ fab!(:channel, :direct_message_channel)
+
+ it { is_expected.to fail_a_policy(:can_view_channel) }
+ end
+ end
+
+ context "when everything is ok" do
+ fab!(:message) { Fabricate(:chat_message, chat_channel: channel, message: "test message") }
+
+ before do
+ channel.add(current_user)
+ SearchIndexer.index(message, force: true)
+ allow(Chat::Action::SearchForMessages).to receive(:call).and_call_original
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "searches for messages" do
+ result
+ expect(Chat::Action::SearchForMessages).to have_received(:call).with(
+ params: an_instance_of(described_class::Contract),
+ guardian:,
+ channel:,
+ )
+ end
+
+ it "returns metadata" do
+ expect(result.metadata).to include(
+ has_more: false,
+ limit: 20,
+ offset: 0,
+ messages: [message],
+ )
+ end
+
+ it "returns messages" do
+ expect(result.messages).to contain_exactly(message)
+ end
+ end
+ end
+end
diff --git a/plugins/chat/spec/system/chat_channel_search/drawer_spec.rb b/plugins/chat/spec/system/chat_channel_search/drawer_spec.rb
new file mode 100644
index 00000000000..2c0cb6e36e2
--- /dev/null
+++ b/plugins/chat/spec/system/chat_channel_search/drawer_spec.rb
@@ -0,0 +1,71 @@
+# frozen_string_literal: true
+
+RSpec.describe "Chat channel search - drawer", type: :system do
+ before do
+ SearchIndexer.enable
+ SiteSetting.chat_search_enabled = true
+ chat_system_bootstrap
+ channel_1.add(current_user)
+ sign_in(current_user)
+ end
+
+ after { SearchIndexer.disable }
+
+ fab!(:current_user, :user)
+ fab!(:channel_1, :chat_channel)
+
+ let(:chat_page) { PageObjects::Pages::Chat.new }
+ let(:channel_page) { PageObjects::Pages::ChatChannel.new }
+ let(:drawer_page) { PageObjects::Pages::ChatDrawer.new }
+
+ context "when searching for messages" do
+ it "shows search results and allows navigation" do
+ message_1 =
+ Fabricate(:chat_message, chat_channel: channel_1, message: "test 1", use_service: true)
+ message_2 =
+ Fabricate(:chat_message, chat_channel: channel_1, message: "test 2", use_service: true)
+
+ drawer_page.visit_channel(channel_1)
+ channel_page.filter.toggle.fill_in("test")
+
+ expect(channel_page.messages).to have_message(id: message_2.id, highlighted: true)
+ expect(channel_page.filter).to have_state(results: 2, position: 1)
+
+ channel_page.filter.navigate_to_next_result
+
+ expect(channel_page.messages).to have_message(id: message_1.id, highlighted: true)
+ expect(channel_page.filter).to have_state(results: 2, position: 2)
+
+ channel_page.filter.navigate_to_previous_result
+
+ expect(channel_page.messages).to have_message(id: message_2.id, highlighted: true)
+ expect(channel_page.filter).to have_state(results: 2, position: 1)
+ end
+
+ it "shows no results message when no matches found" do
+ drawer_page.visit_channel(channel_1)
+
+ channel_page.filter.toggle.fill_in("aaaaaaaaa")
+
+ expect(channel_page.filter).to have_no_results
+ end
+ end
+
+ context "when filter is not toggled" do
+ it "does not show search functionality" do
+ drawer_page.visit_channel(channel_1)
+
+ expect(channel_page.filter).to be_not_visible
+ end
+ end
+
+ context "when search is not enabled" do
+ before { SiteSetting.chat_search_enabled = false }
+
+ it "does not show the filter button" do
+ drawer_page.visit_channel(channel_1)
+
+ expect(channel_page.filter).to be_not_available
+ end
+ end
+end
diff --git a/plugins/chat/spec/system/chat_channel_search/full_page_spec.rb b/plugins/chat/spec/system/chat_channel_search/full_page_spec.rb
new file mode 100644
index 00000000000..98716760a05
--- /dev/null
+++ b/plugins/chat/spec/system/chat_channel_search/full_page_spec.rb
@@ -0,0 +1,70 @@
+# frozen_string_literal: true
+
+RSpec.describe "Chat channel search - full page", type: :system do
+ before do
+ SearchIndexer.enable
+ SiteSetting.chat_search_enabled = true
+ chat_system_bootstrap
+ channel_1.add(current_user)
+ sign_in(current_user)
+ end
+
+ after { SearchIndexer.disable }
+
+ fab!(:current_user, :user)
+ fab!(:channel_1, :chat_channel)
+
+ let(:chat_page) { PageObjects::Pages::Chat.new }
+ let(:channel_page) { PageObjects::Pages::ChatChannel.new }
+
+ context "when searching for messages" do
+ it "shows search results and allows navigation" do
+ message_1 =
+ Fabricate(:chat_message, chat_channel: channel_1, message: "test 1", use_service: true)
+ message_2 =
+ Fabricate(:chat_message, chat_channel: channel_1, message: "test 2", use_service: true)
+
+ chat_page.visit_channel(channel_1)
+ channel_page.filter.toggle.fill_in("test")
+
+ expect(channel_page.messages).to have_message(id: message_2.id, highlighted: true)
+ expect(channel_page.filter).to have_state(results: 2, position: 1)
+
+ channel_page.filter.navigate_to_next_result
+
+ expect(channel_page.messages).to have_message(id: message_1.id, highlighted: true)
+ expect(channel_page.filter).to have_state(results: 2, position: 2)
+
+ channel_page.filter.navigate_to_previous_result
+
+ expect(channel_page.messages).to have_message(id: message_2.id, highlighted: true)
+ expect(channel_page.filter).to have_state(results: 2, position: 1)
+ end
+
+ it "shows no results message when no matches found" do
+ chat_page.visit_channel(channel_1)
+
+ channel_page.filter.toggle.fill_in("aaaaaaaaa")
+
+ expect(channel_page.filter).to have_no_results
+ end
+ end
+
+ context "when filter is not toggled" do
+ it "does not show search functionality" do
+ chat_page.visit_channel(channel_1)
+
+ expect(channel_page.filter).to be_not_visible
+ end
+ end
+
+ context "when search is not enabled" do
+ before { SiteSetting.chat_search_enabled = false }
+
+ it "does not show the filter button" do
+ chat_page.visit_channel(channel_1)
+
+ expect(channel_page.filter).to be_not_available
+ end
+ end
+end
diff --git a/plugins/chat/spec/system/chat_search_spec.rb b/plugins/chat/spec/system/chat_search_spec.rb
new file mode 100644
index 00000000000..55c6782481a
--- /dev/null
+++ b/plugins/chat/spec/system/chat_search_spec.rb
@@ -0,0 +1,95 @@
+# frozen_string_literal: true
+
+RSpec.describe "Chat search", type: :system do
+ before do
+ SearchIndexer.enable
+ SiteSetting.chat_search_enabled = true
+ chat_system_bootstrap
+ channel_1.add(current_user)
+ channel_2.add(current_user)
+ sign_in(current_user)
+ end
+
+ after { SearchIndexer.disable }
+
+ fab!(:current_user, :user)
+ fab!(:channel_1, :chat_channel)
+ fab!(:channel_2, :chat_channel)
+
+ let(:chat_page) { PageObjects::Pages::Chat.new }
+ let(:chat_search_page) { PageObjects::Pages::ChatSearch.new }
+
+ context "when searching for messages" do
+ it "shows search results for multiple channels" do
+ message_1_channel_1 =
+ Fabricate(
+ :chat_message,
+ chat_channel: channel_1,
+ message: "message 1 channel 1",
+ use_service: true,
+ )
+ message_1_channel_2 =
+ Fabricate(
+ :chat_message,
+ chat_channel: channel_2,
+ message: "message 1 channel 2",
+ use_service: true,
+ )
+
+ chat_search_page.visit
+
+ chat_search_page.fill_in("message 1")
+
+ expect(chat_search_page).to have_results(message_1_channel_1, message_1_channel_2)
+
+ chat_search_page.fill_in("channel 1")
+
+ expect(chat_search_page).to have_results(message_1_channel_1)
+ end
+
+ it "can click on a result" do
+ message =
+ Fabricate(:chat_message, chat_channel: channel_1, message: "test", use_service: true)
+
+ chat_search_page.visit.fill_in("test").click_result(message)
+
+ expect(page).to have_current_path(
+ "/chat/c/#{message.chat_channel.slug}/#{message.chat_channel.id}",
+ )
+ end
+
+ it "shows no results message when no matches found" do
+ chat_search_page.visit.fill_in("aaaaaaaa")
+
+ expect(chat_search_page).to have_no_results
+ end
+
+ it "can load more results" do
+ Fabricate.times(
+ 21,
+ :chat_message,
+ chat_channel: channel_1,
+ message: "test",
+ use_service: true,
+ )
+
+ chat_search_page.visit.fill_in("test")
+
+ expect(chat_search_page).to have_x_results(20)
+
+ chat_search_page.scroll_to_bottom
+
+ expect(chat_search_page).to have_x_results(21)
+ end
+ end
+
+ context "with search disabled" do
+ before { SiteSetting.chat_search_enabled = false }
+
+ it "can't access search" do
+ chat_search_page.visit
+
+ expect(page).to have_current_path("/chat/browse/open")
+ end
+ end
+end
diff --git a/plugins/chat/spec/system/page_objects/chat/chat_channel.rb b/plugins/chat/spec/system/page_objects/chat/chat_channel.rb
index b900286d3bd..738290f113b 100644
--- a/plugins/chat/spec/system/page_objects/chat/chat_channel.rb
+++ b/plugins/chat/spec/system/page_objects/chat/chat_channel.rb
@@ -11,6 +11,10 @@ module PageObjects
@messages ||= PageObjects::Components::Chat::Messages.new(".chat-channel")
end
+ def filter
+ @filter ||= PageObjects::Components::Chat::Filter.new
+ end
+
def selection_management
@selection_management ||=
PageObjects::Components::Chat::SelectionManagement.new(".chat-channel")
diff --git a/plugins/chat/spec/system/page_objects/chat/components/filter.rb b/plugins/chat/spec/system/page_objects/chat/components/filter.rb
new file mode 100644
index 00000000000..34a45109a36
--- /dev/null
+++ b/plugins/chat/spec/system/page_objects/chat/components/filter.rb
@@ -0,0 +1,58 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Components
+ module Chat
+ class Filter < PageObjects::Components::Base
+ def filter_bar
+ @filter_bar ||= locator(".chat-channel__filter-bar")
+ end
+
+ def available?
+ expect(locator(".c-navbar__filter")).to be_visible
+ end
+
+ def not_available?
+ expect(locator(".c-navbar__filter")).to be_hidden
+ end
+
+ def toggle
+ locator(".c-navbar__filter").click
+ self
+ end
+
+ def not_visible?
+ expect(filter_bar).to be_hidden
+ end
+
+ def visible?
+ expect(filter_bar).to be_visible
+ end
+
+ def fill_in(query)
+ filter_bar.locator("input").fill(query)
+ self
+ end
+
+ def has_no_results?
+ has_css?(".alert.alert-info", text: I18n.t("js.chat.search.no_results"))
+ end
+
+ def has_state?(results: nil, position: nil)
+ filter_bar.locator(".chat-channel__filter-position-total", hasText: results) &&
+ filter_bar.locator(".chat-channel__filter-position-index", hasText: position)
+ end
+
+ def navigate_to_previous_result
+ filter_bar.locator(".chat-channel__prev-result").click
+ self
+ end
+
+ def navigate_to_next_result
+ filter_bar.locator(".chat-channel__next-result").click
+ self
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/chat/spec/system/page_objects/pages/chat_search.rb b/plugins/chat/spec/system/page_objects/pages/chat_search.rb
new file mode 100644
index 00000000000..60a9553368b
--- /dev/null
+++ b/plugins/chat/spec/system/page_objects/pages/chat_search.rb
@@ -0,0 +1,66 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Pages
+ class ChatSearch < PageObjects::Pages::Base
+ SELECTOR = ".c-routes.--search"
+
+ def visit
+ page.visit("/chat/search")
+ self
+ end
+
+ def fill_in(query)
+ page_locator.locator(".filter-input").fill(query)
+
+ # Wait for search to complete - either results or no results message
+ page_locator.locator(".chat-message-search-entries, .alert.alert-info").wait_for(
+ state: "visible",
+ )
+
+ self
+ end
+
+ def has_x_results?(count)
+ has_selector?(".chat-message-container", count:)
+ end
+
+ def has_results?(*messages)
+ messages.each do |message|
+ expect(
+ page_locator.locator(".chat-message-container[data-id=\"#{message.id}\"]"),
+ ).to be_visible
+ end
+ end
+
+ def has_no_results?
+ expect(page_locator.locator(".alert.alert-info")).to be_visible
+ end
+
+ def click_result(message)
+ page_locator.locator(
+ ".chat-message-search-entry:has(.chat-message-container[data-id=\"#{message.id}\"])",
+ ).click
+ self
+ end
+
+ def scroll_to_bottom
+ page.execute_script("window.scrollTo(0, document.body.scrollHeight)")
+ wait_for_loading
+ self
+ end
+
+ def wait_for_loading
+ has_selector?(".chat-search-loading .spinner")
+ has_no_selector?(".chat-search-loading .spinner")
+ self
+ end
+
+ private
+
+ def page_locator
+ locator(SELECTOR)
+ end
+ end
+ end
+end
diff --git a/plugins/chat/spec/system/shortcuts/full_page_spec.rb b/plugins/chat/spec/system/shortcuts/full_page_spec.rb
index 4de162e79bb..df32ae4f0c0 100644
--- a/plugins/chat/spec/system/shortcuts/full_page_spec.rb
+++ b/plugins/chat/spec/system/shortcuts/full_page_spec.rb
@@ -23,4 +23,26 @@ RSpec.describe "Shortcuts | full page", type: :system do
expect(channel_page.composer).to have_value("e")
end
end
+
+ context "with chat search" do
+ context "when disabled" do
+ before { SiteSetting.chat_search_enabled = false }
+
+ it "doesn't show the link to /chat/search" do
+ visit("/")
+
+ expect(page).to have_no_selector(".sidebar-section[data-section-name=\"chat-search\"]")
+ end
+ end
+
+ context "when enabled" do
+ before { SiteSetting.chat_search_enabled = true }
+
+ it "shows the link the /chat/search" do
+ visit("/")
+
+ expect(page).to have_selector(".sidebar-section[data-section-name=\"chat-search\"]")
+ end
+ end
+ end
end
diff --git a/plugins/chat/test/javascripts/unit/models/chat-message-test.js b/plugins/chat/test/javascripts/unit/models/chat-message-test.js
index ca651a3d1e3..dd6fb51adf6 100644
--- a/plugins/chat/test/javascripts/unit/models/chat-message-test.js
+++ b/plugins/chat/test/javascripts/unit/models/chat-message-test.js
@@ -24,4 +24,14 @@ module("Discourse Chat | Unit | Models | chat-message", function (hooks) {
});
assert.true(message.persisted);
});
+
+ test(".url", function (assert) {
+ const channel = new ChatFabricators(getOwner(this)).channel({ id: 123 });
+
+ let message = ChatMessage.create(channel, { id: 1 });
+ assert.strictEqual(message.url, "/chat/c/-/123/1");
+
+ message = ChatMessage.create(channel, { id: 1, thread_id: 456 });
+ assert.strictEqual(message.url, "/chat/c/-/123/t/456/1");
+ });
});
diff --git a/spec/jobs/reindex_search_spec.rb b/spec/jobs/reindex_search_spec.rb
index 0aefc88afbb..2e3ee9653ad 100644
--- a/spec/jobs/reindex_search_spec.rb
+++ b/spec/jobs/reindex_search_spec.rb
@@ -94,6 +94,104 @@ RSpec.describe Jobs::ReindexSearch do
end
end
+ describe "rebuild_registered_search_handlers" do
+ let(:plugin) { Plugin::Instance.new }
+ let(:mock_model_class) do
+ Class.new do
+ def self.name
+ "TestModel"
+ end
+
+ def self.table_name
+ "test_models"
+ end
+
+ def self.find_by(id:)
+ return nil unless id == 1
+ new(id: id)
+ end
+
+ def initialize(id:)
+ @id = id
+ end
+
+ attr_reader :id
+ end
+ end
+
+ let(:mock_search_data_class) { double }
+
+ after { DiscoursePluginRegistry.reset! }
+
+ it "rebuilds records for registered search handlers" do
+ indexer = mock("SearchIndexer")
+ indexer.expects(:index).once
+
+ plugin.register_search_index(
+ model_class: mock_model_class,
+ search_data_class: mock_search_data_class,
+ index_version: 1,
+ search_data: ->(record, indexer_helper) { { a_weight: "test" } },
+ load_unindexed_record_ids: ->(**_args) { [1] },
+ )
+
+ job.rebuild_registered_search_handlers(indexer: indexer)
+ end
+
+ it "skips disabled handlers" do
+ indexer = mock("SearchIndexer")
+ indexer.expects(:index).never
+
+ plugin.register_search_index(
+ model_class: mock_model_class,
+ search_data_class: mock_search_data_class,
+ index_version: 1,
+ search_data: ->(record, indexer_helper) { { a_weight: "test" } },
+ load_unindexed_record_ids: ->(**_args) { [1] },
+ enabled: -> { false },
+ )
+
+ job.rebuild_registered_search_handlers(indexer: indexer)
+ end
+
+ it "passes limit and index_version to load_unindexed_record_ids" do
+ indexer = mock("SearchIndexer")
+ received_args = nil
+
+ plugin.register_search_index(
+ model_class: mock_model_class,
+ search_data_class: mock_search_data_class,
+ index_version: 2,
+ search_data: ->(record, indexer_helper) { { a_weight: "test" } },
+ load_unindexed_record_ids:
+ lambda do |**args|
+ received_args = args
+ []
+ end,
+ )
+
+ job.rebuild_registered_search_handlers(limit: 5000, indexer: indexer)
+
+ expect(received_args[:limit]).to eq(5000)
+ expect(received_args[:index_version]).to eq(2)
+ end
+
+ it "handles missing records gracefully" do
+ indexer = mock("SearchIndexer")
+ indexer.expects(:index).never
+
+ plugin.register_search_index(
+ model_class: mock_model_class,
+ search_data_class: mock_search_data_class,
+ index_version: 1,
+ search_data: ->(record, indexer_helper) { { a_weight: "test" } },
+ load_unindexed_record_ids: ->(**_args) { [999] },
+ )
+
+ expect { job.rebuild_registered_search_handlers(indexer: indexer) }.not_to raise_error
+ end
+ end
+
describe "#execute" do
it "should clean up topic_search_data of trashed topics" do
topic = Fabricate(:post).topic
diff --git a/spec/lib/plugin/instance_spec.rb b/spec/lib/plugin/instance_spec.rb
index 53120333195..970d2160434 100644
--- a/spec/lib/plugin/instance_spec.rb
+++ b/spec/lib/plugin/instance_spec.rb
@@ -1227,4 +1227,49 @@ TEXT
expect(DiscoursePluginRegistry.admin_config_login_routes).to include("plugin_route")
end
end
+
+ describe "#register_search_index" do
+ let(:plugin) { Plugin::Instance.new }
+ let(:model_class) { User }
+ let(:search_data_class) { double }
+ let(:search_data) { ->(record, indexer_helper) { { a_weight: "test", d_weight: "content" } } }
+ let(:load_unindexed_record_ids) { -> { [1, 2, 3] } }
+
+ after { DiscoursePluginRegistry.reset! }
+
+ it "registers a search handler with the correct parameters" do
+ plugin.register_search_index(
+ model_class: model_class,
+ search_data_class: search_data_class,
+ index_version: 1,
+ search_data: search_data,
+ load_unindexed_record_ids: load_unindexed_record_ids,
+ )
+
+ expect(DiscoursePluginRegistry.search_handlers.count).to eq(1)
+
+ handler = DiscoursePluginRegistry.search_handlers.first
+ expect(handler[:table_name]).to eq("user")
+ expect(handler[:model_class]).to eq(model_class)
+ expect(handler[:search_data_class]).to eq(search_data_class)
+ expect(handler[:index_version]).to eq(1)
+ expect(handler[:search_data]).to eq(search_data)
+ expect(handler[:load_unindexed_record_ids]).to eq(load_unindexed_record_ids)
+ expect(handler[:enabled].call).to eq(true)
+ end
+
+ it "allows custom enabled callback" do
+ plugin.register_search_index(
+ model_class: model_class,
+ search_data_class: search_data_class,
+ index_version: 1,
+ search_data: search_data,
+ load_unindexed_record_ids: load_unindexed_record_ids,
+ enabled: -> { false },
+ )
+
+ handler = DiscoursePluginRegistry.search_handlers.first
+ expect(handler[:enabled].call).to eq(false)
+ end
+ end
end
diff --git a/spec/services/search_indexer_spec.rb b/spec/services/search_indexer_spec.rb
index 599c98d0088..87ce354046d 100644
--- a/spec/services/search_indexer_spec.rb
+++ b/spec/services/search_indexer_spec.rb
@@ -369,4 +369,122 @@ RSpec.describe SearchIndexer do
expect(user2.reload.user_search_data.version).to eq(SearchIndexer::USER_INDEX_VERSION)
end
end
+
+ describe "registered search handlers" do
+ let(:plugin) { Plugin::Instance.new }
+ let(:mock_model_class) do
+ Class.new do
+ def self.name
+ "TestModel"
+ end
+
+ def self.table_name
+ "test_models"
+ end
+
+ attr_accessor :id
+
+ def initialize(id:)
+ @id = id
+ end
+
+ def is_a?(klass)
+ klass == self.class || super
+ end
+ end
+ end
+
+ let(:mock_search_data_class) do
+ klass =
+ Class.new do
+ @params = nil
+
+ class << self
+ attr_accessor :params
+
+ def upsert(params)
+ @params = params
+ end
+ end
+ end
+ klass
+ end
+
+ before { mock_search_data_class.params = nil }
+
+ after { DiscoursePluginRegistry.reset! }
+
+ it "uses registered search handler in SearchIndexer.index" do
+ plugin.register_search_index(
+ model_class: mock_model_class,
+ search_data_class: mock_search_data_class,
+ index_version: 2,
+ search_data: ->(record, indexer_helper) { { a_weight: "test #{record.id}" } },
+ load_unindexed_record_ids: -> { [] },
+ )
+
+ record = mock_model_class.new(id: 123)
+ SearchIndexer.index(record, force: true)
+
+ params = mock_search_data_class.params
+ expect(params).to be_present
+ expect(params["test_model_id"]).to eq(123)
+ expect(params["version"]).to eq(2)
+ expect(params["raw_data"]).to include("test 123")
+ end
+
+ it "usesregistered search handler in SearchIndexer.update_index" do
+ plugin.register_search_index(
+ model_class: mock_model_class,
+ search_data_class: mock_search_data_class,
+ index_version: 3,
+ search_data: ->(record, indexer_helper) { { a_weight: "content" } },
+ load_unindexed_record_ids: -> { [] },
+ )
+
+ SearchIndexer.update_index(table: "test_model", id: 456, a_weight: "custom data")
+
+ params = mock_search_data_class.params
+ expect(params).to be_present
+ expect(params["test_model_id"]).to eq(456)
+ expect(params["version"]).to eq(3)
+ expect(params["raw_data"]).to include("custom data")
+ end
+
+ it "uses handler's index_version" do
+ plugin.register_search_index(
+ model_class: mock_model_class,
+ search_data_class: mock_search_data_class,
+ index_version: 5,
+ search_data: ->(record, indexer_helper) { { d_weight: "test" } },
+ load_unindexed_record_ids: -> { [] },
+ )
+
+ SearchIndexer.update_index(table: "test_model", id: 789, d_weight: "data")
+
+ params = mock_search_data_class.params
+ expect(params["version"]).to eq(5)
+ end
+
+ it "provides IndexerHelper to search_data callback" do
+ indexer_helper_received = nil
+
+ plugin.register_search_index(
+ model_class: mock_model_class,
+ search_data_class: mock_search_data_class,
+ index_version: 1,
+ search_data:
+ lambda do |record, indexer_helper|
+ indexer_helper_received = indexer_helper
+ { a_weight: "test" }
+ end,
+ load_unindexed_record_ids: -> { [] },
+ )
+
+ record = mock_model_class.new(id: 1)
+ SearchIndexer.index(record, force: true)
+
+ expect(indexer_helper_received).to be_a(SearchIndexer::IndexerHelper)
+ end
+ end
end
diff --git a/spec/support/system_helpers.rb b/spec/support/system_helpers.rb
index 9798ba6372c..ebc465d988d 100644
--- a/spec/support/system_helpers.rb
+++ b/spec/support/system_helpers.rb
@@ -373,4 +373,12 @@ module SystemHelpers
raise e unless e.message.match?(/Element is not attached to the DOM/)
end
end
+
+ def locator(selector, locator = nil)
+ if locator
+ locator.locator(selector)
+ else
+ page.driver.with_playwright_page { |pw_page| pw_page.locator(selector) }
+ end
+ end
end