Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add search to the settings navigation (#4633)

Ryan Eatonfd95090b6f50
diff --git a/app/components/DS/search_result.html.erb b/app/components/DS/search_result.html.erb
new file mode 100644
index 0000000000..b245f68a2e
--- /dev/null
+++ b/app/components/DS/search_result.html.erb
@@ -0,0 +1,7 @@
+<%= link_to href, class: container_classes, **container_opts do %>
+ <span data-slot="icon" class="flex shrink-0"><%= helpers.icon(icon) if icon %></span>
+ <span class="min-w-0">
+ <span data-slot="title" class="block text-primary font-medium truncate"><%= title %></span>
+ <span data-slot="subtitle" class="block text-secondary text-xs truncate"><%= subtitle %></span>
+ </span>
+<% end %>
diff --git a/app/components/DS/search_result.rb b/app/components/DS/search_result.rb
new file mode 100644
index 0000000000..24e7e5d966
--- /dev/null
+++ b/app/components/DS/search_result.rb
@@ -0,0 +1,36 @@
+class DS::SearchResult < DesignSystemComponent
+ # One option in a list of search results: an icon, a title and a subtitle
+ # naming where the result lives. The settings search lists both pages and
+ # individual settings with it. Its script fills a row in from the
+ # `data-slot` hooks, so a row can be rendered empty and completed later.
+ #
+ # <%= render DS::SearchResult.new(href: path, title: "Security", subtitle: "Account", icon: "shield") %>
+ BASE_CLASSES = "flex items-center gap-3 px-3 py-2 rounded-lg text-sm focus-ring hover:bg-surface-hover aria-selected:bg-surface-hover".freeze
+
+ attr_reader :href, :title, :subtitle, :icon, :opts
+
+ # @param href [String] where the result leads
+ # @param title [String, nil] the result's own name
+ # @param subtitle [String, nil] secondary line, such as the section or page it belongs to
+ # @param icon [String, nil] icon name
+ # @param opts [Hash] forwarded to the link; :class merges with the base classes
+ def initialize(href:, title: nil, subtitle: nil, icon: nil, **opts)
+ @href = href
+ @title = title
+ @subtitle = subtitle
+ @icon = icon
+ @opts = opts
+ end
+
+ # @return [String] classes for the link, merging any class the caller passed
+ def container_classes
+ class_names(BASE_CLASSES, opts[:class])
+ end
+
+ # Caller options minus :class, which container_classes has already merged.
+ #
+ # @return [Hash] attributes forwarded to the link
+ def container_opts
+ opts.except(:class)
+ end
+end
diff --git a/app/javascript/controllers/settings_search_controller.js b/app/javascript/controllers/settings_search_controller.js
new file mode 100644
index 0000000000..de188de9d8
--- /dev/null
+++ b/app/javascript/controllers/settings_search_controller.js
@@ -0,0 +1,312 @@
+import { Controller } from "@hotwired/stimulus";
+
+// Elements whose text names a setting or states it: headings, field labels and
+// primary-colored lines, including the title line of a toggle. Muted
+// description text is not searchable.
+const TEXT_SELECTOR =
+ "h2, h3, h4, legend, label, summary, p.text-primary, p.text-sm:not(.text-secondary, .text-subdued, .text-destructive)";
+// Text inside these is not shown, or is not part of a setting.
+const SKIPPED_SELECTOR =
+ "nav, header, footer, script, style, template, dialog, [hidden], [aria-hidden='true'], .hidden, .sr-only";
+const MAX_SETTING_RESULTS = 8;
+const FRAGMENT_WORDS = 8;
+const INDEX_TTL_MS = 5 * 60 * 1000;
+
+// Shared across Turbo visits so the pages are read once, not on every page.
+let settingsIndex = null;
+
+// Connects to data-controller="settings-search"
+// Searches the settings pages and, once the pages have been read, the text of
+// the settings on them. Nothing is listed by hand: whatever a page shows is
+// searchable, so a new setting turns up as soon as it exists.
+//
+// The server renders every settings page into the results list; this
+// controller decides which are visible and in what order, swaps the results
+// for the regular navigation while a query is present, adds matching settings
+// as extra rows, and moves the keyboard highlight between matches.
+export default class extends Controller {
+ static targets = ["input", "nav", "results", "item", "empty", "template"];
+ static values = { pages: Array, scope: String };
+
+ connect() {
+ this.settingRows = [];
+ this.filter();
+ }
+
+ // Reads the searchable pages the first time the field is used.
+ async load() {
+ if (this.loading || this.isFresh()) return;
+
+ this.loading = true;
+ const scope = this.indexScope;
+ const entries = await this.readPages();
+ settingsIndex = { scope, loadedAt: Date.now(), entries };
+ this.loading = false;
+ this.filter();
+ }
+
+ filter() {
+ const query = this.normalize(this.inputTarget.value);
+ const searching = query.length > 0;
+
+ this.navTarget.classList.toggle("hidden", searching);
+ this.resultsTarget.classList.toggle("hidden", !searching);
+ this.inputTarget.setAttribute("aria-expanded", String(searching));
+
+ this.clearSettingRows();
+
+ const pages = this.rankPages(query);
+ const settings = this.rankSettings(query).map((setting) =>
+ this.buildRow(setting),
+ );
+ const rows = [...pages, ...settings]
+ .map((row, position) => ({ row, position }))
+ .sort((a, b) => a.row.score - b.row.score || a.position - b.position)
+ .map(({ row }) => row.element);
+
+ const shown = new Set(rows);
+ this.itemTargets.forEach((item) => {
+ item.classList.toggle("hidden", !shown.has(item));
+ item.style.order = "";
+ });
+ rows.forEach((element, order) => {
+ element.style.order = order;
+ });
+
+ this.emptyTarget.classList.toggle(
+ "hidden",
+ !searching || rows.length > 0 || this.loading,
+ );
+ this.highlight(rows[0]);
+ }
+
+ keydown(event) {
+ // Enter and Escape finish an IME composition rather than act on the results.
+ if (event.isComposing || event.keyCode === 229) return;
+
+ switch (event.key) {
+ case "ArrowDown":
+ event.preventDefault();
+ this.moveHighlight(1);
+ break;
+ case "ArrowUp":
+ event.preventDefault();
+ this.moveHighlight(-1);
+ break;
+ case "Enter":
+ this.openHighlighted(event);
+ break;
+ case "Escape":
+ this.escape(event);
+ break;
+ }
+ }
+
+ // Pages whose name, section or text matches. A name that starts with the
+ // query beats one that merely contains it, which beats a match elsewhere.
+ rankPages(query) {
+ if (!query) return [];
+
+ return this.itemTargets.flatMap((element) => {
+ const score = this.score(
+ query,
+ this.normalize(element.dataset.searchLabel),
+ this.normalize(element.dataset.searchText),
+ );
+ return score === null ? [] : [{ element, score }];
+ });
+ }
+
+ // Settings found on the pages, best match first.
+ rankSettings(query) {
+ if (!query || settingsIndex?.scope !== this.indexScope) return [];
+
+ return settingsIndex.entries
+ .flatMap((entry) => {
+ const score = this.score(query, entry.text, entry.text);
+ return score === null ? [] : [{ ...entry, score }];
+ })
+ .sort((a, b) => a.score - b.score)
+ .slice(0, MAX_SETTING_RESULTS);
+ }
+
+ score(query, label, text) {
+ const terms = query.split(" ");
+ if (!terms.every((term) => text.includes(term))) return null;
+ if (label.startsWith(query)) return 0;
+ if (label.includes(query)) return 1;
+ if (terms.every((term) => label.includes(term))) return 2;
+ return 3;
+ }
+
+ // The row for one setting: its own text, cut off with an ellipsis, over the
+ // page it lives on.
+ buildRow(setting) {
+ const element =
+ this.templateTarget.content.firstElementChild.cloneNode(true);
+ element.dataset.settingResult = "";
+ const link = element.querySelector("a");
+ const page = this.itemTargets.find(
+ (item) => item.dataset.pagePath === setting.path,
+ );
+
+ link.href = `${setting.path}${this.textFragment(setting.display)}`;
+ link.id = `settings-search-setting-${this.settingRows.length}`;
+ element.querySelector("[data-slot=title]").textContent = setting.display;
+ element.querySelector("[data-slot=subtitle]").textContent = setting.label;
+ const icon = page?.querySelector("svg");
+ if (icon) {
+ element.querySelector("[data-slot=icon]").append(icon.cloneNode(true));
+ }
+
+ this.resultsTarget.querySelector("ul").append(element);
+ this.settingRows.push(element);
+ return { element, score: setting.score };
+ }
+
+ // Rows are found by their marker, not only from the list, so rows restored
+ // from Turbo's page cache are removed too.
+ clearSettingRows() {
+ this.resultsTarget
+ .querySelectorAll("[data-setting-result]")
+ .forEach((row) => row.remove());
+ this.settingRows = [];
+ }
+
+ // Browsers scroll to and highlight the text a fragment names.
+ textFragment(text) {
+ const start = text.split(" ").slice(0, FRAGMENT_WORDS).join(" ");
+ return `#:~:text=${encodeURIComponent(start).replace(/-/g, "%2D")}`;
+ }
+
+ moveHighlight(direction) {
+ const visible = this.visibleRows;
+ if (visible.length === 0) return;
+
+ const current = visible.indexOf(this.highlighted);
+ const next = (current + direction + visible.length) % visible.length;
+ this.highlight(visible[next]);
+ }
+
+ highlight(target) {
+ this.highlighted = target;
+
+ this.visibleRows.forEach((row) => {
+ row
+ .querySelector("a")
+ .setAttribute("aria-selected", String(row === target));
+ });
+
+ if (target) {
+ const link = target.querySelector("a");
+ this.inputTarget.setAttribute("aria-activedescendant", link.id);
+ link.scrollIntoView({ block: "nearest" });
+ } else {
+ this.inputTarget.removeAttribute("aria-activedescendant");
+ }
+ }
+
+ openHighlighted(event) {
+ if (!this.highlighted) return;
+
+ event.preventDefault();
+ this.highlighted.querySelector("a").click();
+ }
+
+ // Escape clears a query first; with nothing left to clear it leaves the field.
+ escape(event) {
+ event.preventDefault();
+
+ if (this.inputTarget.value) {
+ this.inputTarget.value = "";
+ this.filter();
+ } else {
+ this.inputTarget.blur();
+ }
+ }
+
+ get visibleRows() {
+ return [...this.itemTargets, ...this.settingRows]
+ .filter((row) => !row.classList.contains("hidden"))
+ .sort((a, b) => Number(a.style.order) - Number(b.style.order));
+ }
+
+ isFresh() {
+ return (
+ settingsIndex?.scope === this.indexScope &&
+ Date.now() - settingsIndex.loadedAt < INDEX_TTL_MS
+ );
+ }
+
+ // The index holds the text of one user's pages, so it is only reused for the
+ // same user and page list. Turbo keeps this module across sign-in and
+ // impersonation changes.
+ get indexScope() {
+ return `${this.scopeValue}:${this.pagesValue.map((page) => page.path).join("|")}`;
+ }
+
+ async readPages() {
+ const pages = await Promise.all(
+ this.pagesValue.map((page) => this.readPage(page)),
+ );
+ return pages.flat();
+ }
+
+ // Every distinct piece of text a page shows as a setting. A page that cannot
+ // be read is left out rather than breaking the search.
+ async readPage({ path, label }) {
+ try {
+ const response = await fetch(path, {
+ headers: { Accept: "text/html" },
+ credentials: "same-origin",
+ });
+ if (!response.ok) return [];
+
+ const document = new DOMParser().parseFromString(
+ await response.text(),
+ "text/html",
+ );
+ const seen = new Set();
+
+ return [
+ ...(document.querySelector("main")?.querySelectorAll(TEXT_SELECTOR) ??
+ []),
+ ]
+ .filter((element) => !element.closest(SKIPPED_SELECTOR))
+ .filter((element) => !this.collapsed(element))
+ .filter((element) => !element.querySelector(TEXT_SELECTOR))
+ .map((element) => element.textContent.replace(/\s+/g, " ").trim())
+ .filter(
+ (display) =>
+ display.length > 2 && !seen.has(display) && seen.add(display),
+ )
+ .map((display) => ({
+ path,
+ label,
+ display,
+ text: this.normalize(display),
+ }));
+ } catch {
+ return [];
+ }
+ }
+
+ // Text in the body of a closed <details> is not shown; its summary is.
+ collapsed(element) {
+ const details = element.closest("details:not([open])");
+ return (
+ details !== null && element.closest("summary")?.parentElement !== details
+ );
+ }
+
+ // Lowercase, strip diacritics and treat punctuation as a space, so
+ // "two factor" finds "Two-Factor" and "securite" finds "Sécurité".
+ normalize(value) {
+ return (value ?? "")
+ .normalize("NFD")
+ .replace(/\p{M}/gu, "")
+ .toLocaleLowerCase()
+ .replace(/[^\p{L}\p{N}]+/gu, " ")
+ .trim();
+ }
+}
diff --git a/app/views/settings/_settings_nav.html.erb b/app/views/settings/_settings_nav.html.erb
index 5616277599..6a9358acc9 100644
--- a/app/views/settings/_settings_nav.html.erb
+++ b/app/views/settings/_settings_nav.html.erb
@@ -5,11 +5,11 @@ nav_sections = [
items: [
{ label: t(".accounts_label"), path: accounts_path, icon: "layers" },
{ label: t(".bank_sync_label"), path: settings_providers_path, icon: "banknote", if: Current.user&.admin? },
- { label: t(".preferences_label"), path: settings_preferences_path, icon: "bolt" },
- { label: t(".appearance_label"), path: settings_appearance_path, icon: "palette" },
- { label: t(".profile_label"), path: settings_profile_path, icon: "circle-user" },
- { label: t(".security_label"), path: settings_security_path, icon: "shield-check" },
- { label: t(".payment_label"), path: settings_payment_path, icon: "circle-dollar-sign", if: !self_hosted? && Current.family&.can_manage_subscription? }
+ { label: t(".preferences_label"), path: settings_preferences_path, icon: "bolt", searchable: true },
+ { label: t(".appearance_label"), path: settings_appearance_path, icon: "palette", searchable: true },
+ { label: t(".profile_label"), path: settings_profile_path, icon: "circle-user", searchable: true },
+ { label: t(".security_label"), path: settings_security_path, icon: "shield-check", searchable: true },
+ { label: t(".payment_label"), path: settings_payment_path, icon: "circle-dollar-sign", searchable: true, if: !self_hosted? && Current.family&.can_manage_subscription? }
]
},
{
@@ -28,14 +28,14 @@ nav_sections = [
Current.user&.admin? ? {
header: t(".advanced_section_title"),
items: [
- { label: t(".ai_prompts_label"), path: settings_ai_prompts_path, icon: "bot" },
- { label: t(".classifier_label"), path: settings_classifier_path, icon: "sliders-horizontal" },
+ { label: t(".ai_prompts_label"), path: settings_ai_prompts_path, icon: "bot", searchable: true },
+ { label: t(".classifier_label"), path: settings_classifier_path, icon: "sliders-horizontal", searchable: true },
{ label: t(".llm_usage_label"), path: settings_llm_usage_path, icon: "activity" },
- { label: t(".api_keys_label"), path: settings_api_keys_path, icon: "key" },
- { label: t(".mcp_label"), path: settings_mcp_path, icon: "plug" },
+ { label: t(".api_keys_label"), path: settings_api_keys_path, icon: "key", searchable: true },
+ { label: t(".mcp_label"), path: settings_mcp_path, icon: "plug", searchable: true },
{ label: t(".debug_label", default: "Debug"), path: settings_debug_path, icon: "bug", if: Current.user&.super_admin? },
{ label: t(".background_jobs_label"), path: settings_background_jobs_path, icon: "list-checks", if: Current.user&.super_admin? },
- { label: t(".self_hosting_label"), path: settings_hosting_path, icon: "database", if: self_hosted? },
+ { label: t(".self_hosting_label"), path: settings_hosting_path, icon: "database", searchable: true, if: self_hosted? },
{ label: t(".imports_label"), path: imports_path, icon: "download" },
{ label: t(".exports_label"), path: family_exports_path, icon: "upload" },
{ label: t(".sso_providers_label"), path: admin_sso_providers_path, icon: "key-round", if: Current.user&.super_admin? },
@@ -53,9 +53,13 @@ nav_sections = [
]
}
]
+
+search_pages = nav_sections.compact.flat_map { |section| section[:items] }
+ .select { |item| item[:searchable] && item[:if] != false }
+ .map { |item| { path: item[:path], label: item[:label] } }
%>
-<div class="space-y-4">
+<div class="space-y-4" data-controller="settings-search" data-settings-search-pages-value="<%= search_pages.to_json %>" data-settings-search-scope-value="<%= Current.user.id %>:<%= I18n.locale %>">
<div class="hidden lg:flex items-center gap-2 p-1.5">
<%= render DS::Link.new(
text: t("settings.settings_nav_link_large.previous"),
@@ -67,54 +71,57 @@ nav_sections = [
<kbd>esc</kbd>
<% end %>
</div>
- <nav class="space-y-4 hidden md:block">
- <% nav_sections.compact.each do |section| %>
- <section class="space-y-2">
- <div class="flex items-center gap-2 px-3">
- <h3 class="uppercase text-secondary font-medium text-xs"><%= section[:header] %></h3>
- <%= render "shared/ruler", classes: "w-full" %>
- </div>
- <ul class="space-y-1">
+ <%= render "settings/settings_search", nav_sections: nav_sections %>
+ <div class="space-y-4" data-settings-search-target="nav">
+ <nav class="space-y-4 hidden md:block">
+ <% nav_sections.compact.each do |section| %>
+ <section class="space-y-2">
+ <div class="flex items-center gap-2 px-3">
+ <h3 class="uppercase text-secondary font-medium text-xs"><%= section[:header] %></h3>
+ <%= render "shared/ruler", classes: "w-full" %>
+ </div>
+ <ul class="space-y-1">
+ <% section[:items].each do |item| %>
+ <% next if item[:if] == false %>
+ <li>
+ <%= render "settings/settings_nav_item", name: item[:label], path: item[:path], icon: item[:icon] %>
+ </li>
+ <% end %>
+ </ul>
+ </section>
+ <% end %>
+ <section>
+ <%= button_to session_path(Current.session), method: :delete, class: "flex items-center gap-2 px-3 py-2 rounded-lg text-sm text-destructive hover:bg-surface-hover w-full" do %>
+ <%= icon("log-out", color: "current") %>
+ <span><%= t(".logout") %></span>
+ <% end %>
+ </section>
+ </nav>
+ <nav class="space-y-4 overflow-x-auto md:hidden no-scrollbar overscroll-none" id="mobile-settings-nav" data-controller="preserve-scroll scroll-on-connect">
+ <ul class="flex flex-nowrap space-x-1">
+ <li>
+ <%= render DS::Link.new(
+ text: t("settings.settings_nav_link_large.previous"),
+ icon: "chevron-left",
+ href: previous_path,
+ variant: "ghost",
+ ) %>
+ </li>
+ <% nav_sections.compact.each do |section| %>
<% section[:items].each do |item| %>
<% next if item[:if] == false %>
<li>
<%= render "settings/settings_nav_item", name: item[:label], path: item[:path], icon: item[:icon] %>
</li>
<% end %>
- </ul>
- </section>
- <% end %>
- <section>
- <%= button_to session_path(Current.session), method: :delete, class: "flex items-center gap-2 px-3 py-2 rounded-lg text-sm text-destructive hover:bg-surface-hover w-full" do %>
- <%= icon("log-out", color: "current") %>
- <span><%= t(".logout") %></span>
- <% end %>
- </section>
- </nav>
- <nav class="space-y-4 overflow-x-auto md:hidden no-scrollbar overscroll-none" id="mobile-settings-nav" data-controller="preserve-scroll scroll-on-connect">
- <ul class="flex flex-nowrap space-x-1">
- <li>
- <%= render DS::Link.new(
- text: t("settings.settings_nav_link_large.previous"),
- icon: "chevron-left",
- href: previous_path,
- variant: "ghost",
- ) %>
- </li>
- <% nav_sections.compact.each do |section| %>
- <% section[:items].each do |item| %>
- <% next if item[:if] == false %>
- <li>
- <%= render "settings/settings_nav_item", name: item[:label], path: item[:path], icon: item[:icon] %>
- </li>
<% end %>
- <% end %>
- <li>
- <%= button_to session_path(Current.session), method: :delete, class: "flex items-center gap-2 px-3 py-2 rounded-lg text-sm text-destructive hover:bg-surface-hover w-full" do %>
- <%= icon("log-out", color: "current") %>
- <span><%= t(".logout") %></span>
- <% end %>
- </li>
- </ul>
- </nav>
+ <li>
+ <%= button_to session_path(Current.session), method: :delete, class: "flex items-center gap-2 px-3 py-2 rounded-lg text-sm text-destructive hover:bg-surface-hover w-full" do %>
+ <%= icon("log-out", color: "current") %>
+ <span><%= t(".logout") %></span>
+ <% end %>
+ </li>
+ </ul>
+ </nav>
+ </div>
</div>
diff --git a/app/views/settings/_settings_search.html.erb b/app/views/settings/_settings_search.html.erb
new file mode 100644
index 0000000000..022a435be9
--- /dev/null
+++ b/app/views/settings/_settings_search.html.erb
@@ -0,0 +1,63 @@
+<%# locals: (nav_sections:) %>
+
+<%
+ visible_items = nav_sections.compact.flat_map do |section|
+ section[:items].reject { |item| item[:if] == false }.map { |item| item.merge(section: section[:header]) }
+ end
+%>
+
+<div class="space-y-2">
+ <div class="group relative">
+ <%= render DS::SearchInput.new(
+ class: "[&_input]:pr-10",
+ placeholder: t("settings.settings_search.placeholder"),
+ aria_label: t("settings.settings_search.aria_label"),
+ role: "combobox",
+ aria: { expanded: "false", controls: "settings-search-listbox", autocomplete: "list" },
+ data: {
+ controller: "hotkey",
+ hotkey: "/",
+ settings_search_target: "input",
+ action: "input->settings-search#filter keydown->settings-search#keydown focus->settings-search#load"
+ }
+ ) %>
+ <kbd class="hidden md:block group-has-[input:not(:placeholder-shown)]:invisible absolute right-3 top-1/2 -translate-y-1/2 uppercase bg-surface-inset-hover rounded-sm px-1.5 py-0.5 text-xs text-secondary shadow-sm pointer-events-none">/</kbd>
+ </div>
+
+ <div data-settings-search-target="results" class="hidden w-0 min-w-full">
+ <ul id="settings-search-listbox" role="listbox" aria-label="<%= t("settings.settings_search.results_label") %>" class="flex flex-col gap-1">
+ <% visible_items.each_with_index do |item, index| %>
+ <li
+ role="presentation"
+ class="hidden"
+ data-settings-search-target="item"
+ data-page-path="<%= item[:path] %>"
+ data-search-label="<%= item[:label] %>"
+ data-search-text="<%= [ item[:label], item[:section] ].compact_blank.join(" ") %>">
+ <%= render DS::SearchResult.new(
+ href: item[:path],
+ title: item[:label],
+ subtitle: item[:section],
+ icon: item[:icon],
+ id: "settings-search-page-#{index}",
+ role: "option",
+ aria: { selected: "false", current: ("page" if page_active?(item[:path])) }
+ ) %>
+ </li>
+ <% end %>
+ </ul>
+
+ <p data-settings-search-target="empty" class="hidden px-3 py-2 text-sm text-secondary" role="status">
+ <%= t("settings.settings_search.no_results") %>
+ </p>
+
+ <%# Settings found inside the pages are listed beside the pages themselves. The
+ controller fills this row in for each match. A text fragment needs a full
+ page load to scroll to and highlight the setting, so these links opt out of Turbo. %>
+ <template data-settings-search-target="template">
+ <li role="presentation">
+ <%= render DS::SearchResult.new(href: "#", role: "option", data: { turbo: false }, aria: { selected: "false" }) %>
+ </li>
+ </template>
+ </div>
+</div>
diff --git a/app/views/settings/preferences/show.html.erb b/app/views/settings/preferences/show.html.erb
index fe42949e40..61a350beb3 100644
--- a/app/views/settings/preferences/show.html.erb
+++ b/app/views/settings/preferences/show.html.erb
@@ -96,10 +96,10 @@
<% if Current.user.admin? && preview_features_enabled? %>
<div class="flex items-center justify-between">
<div class="space-y-1">
- <p class="text-sm flex items-center gap-1.5">
- <%= t(".personal_budgets") %>
+ <div class="flex items-center gap-1.5">
+ <p class="text-sm"><%= t(".personal_budgets") %></p>
<%= render DS::Pill.new(label: t("shared.preview"), size: :sm) %>
- </p>
+ </div>
<p class="text-secondary text-sm"><%= t(".personal_budgets_hint") %></p>
</div>
<%= family_form.toggle :personal_budgets,
diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.yml
index 9fd46b632e..93e042c2d9 100644
--- a/config/locales/views/settings/en.yml
+++ b/config/locales/views/settings/en.yml
@@ -40,6 +40,11 @@ en:
appearance_label: Appearance
bank_sync_label: Bank sync
debug_label: Debug
+ settings_search:
+ aria_label: Search settings
+ no_results: No settings match your search.
+ placeholder: Search settings
+ results_label: Matching settings
settings_nav_link_large:
next: Next
previous: Back
diff --git a/test/components/DS/search_result_test.rb b/test/components/DS/search_result_test.rb
new file mode 100644
index 0000000000..bd35943df2
--- /dev/null
+++ b/test/components/DS/search_result_test.rb
@@ -0,0 +1,31 @@
+require "test_helper"
+
+class DS::SearchResultTest < ViewComponent::TestCase
+ test "renders the title and subtitle in a link" do
+ render_inline(DS::SearchResult.new(href: "/settings/security", title: "Security", subtitle: "Account"))
+
+ assert_selector "a[href='/settings/security']"
+ assert_selector "a [data-slot=title].text-primary", text: "Security"
+ assert_selector "a [data-slot=subtitle].text-secondary", text: "Account"
+ end
+
+ test "renders the icon when given one" do
+ render_inline(DS::SearchResult.new(href: "/", title: "Security", icon: "shield"))
+
+ assert_selector "[data-slot=icon] svg"
+ end
+
+ test "renders an empty row for a script to fill in" do
+ render_inline(DS::SearchResult.new(href: "#"))
+
+ assert_selector "[data-slot=icon]:empty"
+ assert_selector "[data-slot=title]:empty"
+ assert_selector "[data-slot=subtitle]:empty"
+ end
+
+ test "merges caller classes and forwards other attributes" do
+ render_inline(DS::SearchResult.new(href: "/", title: "A", class: "extra", role: "option", aria: { selected: "false" }, data: { turbo: false }))
+
+ assert_selector "a.extra.rounded-lg[role=option][aria-selected=false][data-turbo=false]"
+ end
+end
diff --git a/test/controllers/settings/search_navigation_test.rb b/test/controllers/settings/search_navigation_test.rb
new file mode 100644
index 0000000000..d8c1a903c9
--- /dev/null
+++ b/test/controllers/settings/search_navigation_test.rb
@@ -0,0 +1,71 @@
+require "test_helper"
+
+class Settings::SearchNavigationTest < ActionDispatch::IntegrationTest
+ test "settings pages render a search field backed by every page the user can open" do
+ sign_in users(:family_admin)
+
+ get settings_profile_path
+
+ assert_response :success
+ assert_select "input[type=search][data-settings-search-target=input][data-hotkey='/']"
+ assert_includes search_labels, I18n.t("settings.settings_nav.security_label")
+ assert_includes search_labels, I18n.t("settings.settings_nav.bank_sync_label")
+ assert_includes search_labels, I18n.t("settings.settings_nav.api_keys_label")
+ end
+
+ test "search results link to the page and name its section" do
+ sign_in users(:family_admin)
+
+ get settings_profile_path
+
+ assert_select "[data-settings-search-target=item] a[href='#{settings_security_path}']", text: /#{I18n.t("settings.settings_nav.security_label")}/ do |links|
+ assert_match I18n.t("settings.settings_nav.general_section_title"), links.first.text
+ end
+ end
+
+ test "members are not offered admin-only pages" do
+ sign_in users(:family_member)
+
+ get settings_profile_path
+
+ assert_response :success
+ assert_includes search_labels, I18n.t("settings.settings_nav.security_label")
+ assert_not_includes search_labels, I18n.t("settings.settings_nav.bank_sync_label")
+ assert_not_includes search_labels, I18n.t("settings.settings_nav.api_keys_label")
+ assert_not_includes search_labels, I18n.t("settings.settings_nav.statement_vault_label")
+ end
+
+ test "pages whose settings can be searched are handed to the controller" do
+ sign_in users(:family_admin)
+
+ get settings_profile_path
+
+ pages = JSON.parse(css_select("[data-controller~=settings-search]").first["data-settings-search-pages-value"])
+ assert_includes pages, { "path" => settings_security_path, "label" => I18n.t("settings.settings_nav.security_label") }
+ assert_includes pages, { "path" => settings_preferences_path, "label" => I18n.t("settings.settings_nav.preferences_label") }
+ assert_not_includes pages.map { |page| page["path"] }, categories_path
+ end
+
+ test "the search index is scoped to the signed-in user" do
+ sign_in users(:family_member)
+
+ get settings_profile_path
+
+ assert_select "[data-controller~=settings-search][data-settings-search-scope-value='#{users(:family_member).id}:#{I18n.locale}']"
+ end
+
+ test "members are not handed admin-only pages to search" do
+ sign_in users(:family_member)
+
+ get settings_profile_path
+
+ pages = JSON.parse(css_select("[data-controller~=settings-search]").first["data-settings-search-pages-value"])
+ assert_not_includes pages.map { |page| page["path"] }, settings_api_keys_path
+ assert_not_includes pages.map { |page| page["path"] }, settings_ai_prompts_path
+ end
+
+ private
+ def search_labels
+ css_select("[data-settings-search-target=item]").map { |item| item["data-search-label"] }
+ end
+end
diff --git a/test/system/rules_test.rb b/test/system/rules_test.rb
index 73e8798124..f3b515df21 100644
--- a/test/system/rules_test.rb
+++ b/test/system/rules_test.rb
@@ -234,7 +234,7 @@ class RulesTest < ApplicationSystemTestCase
rent = create_exclude_rule("Rent", group: group)
visit rules_path
- find("input[type='search']").fill_in(with: "rent")
+ find("input[name='q']").fill_in(with: "rent")
assert_selector "[data-sortable-list-id='#{rent.id}']"
assert_no_selector "[data-sortable-list-id='rule:#{groceries.id}']"
diff --git a/test/system/settings_test.rb b/test/system/settings_test.rb
index 0e7d8ed730..7a28d08dbe 100644
--- a/test/system/settings_test.rb
+++ b/test/system/settings_test.rb
@@ -95,6 +95,95 @@ class SettingsTest < ApplicationSystemTestCase
assert_current_path settings_api_keys_path
end
+ test "searching settings finds a setting by its own text and opens its page with the keyboard" do
+ visit settings_profile_path
+
+ fill_in I18n.t("settings.settings_search.placeholder"), with: "two-fa"
+
+ mfa_title = I18n.t("settings.securities.show.mfa_title")
+ assert_selector "[role=option][aria-selected=true]", text: mfa_title
+ assert_selector "[role=option][aria-selected=true]", text: I18n.t("settings.settings_nav.security_label")
+ assert_selector "[role=option][aria-selected=true][href*='#:~:text='][data-turbo=false]"
+
+ page.send_keys(:enter)
+
+ assert_current_path settings_security_path
+ assert_selector "h2", text: mfa_title
+ end
+
+ test "settings search lists what a setting is called, not the text that describes it" do
+ visit settings_profile_path
+ search = find_field(I18n.t("settings.settings_search.placeholder"))
+
+ search.fill_in with: "two-fa"
+ assert_selector "[data-settings-search-target=results] [role=option]", text: I18n.t("settings.securities.show.mfa_title")
+
+ search.fill_in with: I18n.t("settings.securities.show.mfa_description")
+ assert_selector "[data-settings-search-target=empty]", text: I18n.t("settings.settings_search.no_results")
+ assert_no_selector "[data-settings-search-target=results] [role=option]"
+ end
+
+ test "settings search finds the name of a toggle but not its description" do
+ visit settings_profile_path
+ search = find_field(I18n.t("settings.settings_search.placeholder"))
+
+ search.fill_in with: I18n.t("settings.preferences.show.investment_contributions_as_spending")
+ assert_selector "[data-settings-search-target=results] [role=option]", text: I18n.t("settings.preferences.show.investment_contributions_as_spending")
+
+ search.fill_in with: I18n.t("settings.preferences.show.investment_contributions_as_spending_hint")
+ assert_selector "[data-settings-search-target=empty]"
+ end
+
+ test "settings search names a preview toggle without its badge" do
+ @user.update!(preferences: (@user.preferences || {}).merge("preview_features_enabled" => true))
+ visit settings_profile_path
+ search = find_field(I18n.t("settings.settings_search.placeholder"))
+
+ search.fill_in with: I18n.t("settings.preferences.show.personal_budgets")
+ assert_selector "[data-settings-search-target=results] [data-slot=title]", exact_text: I18n.t("settings.preferences.show.personal_budgets")
+ end
+
+ test "settings search skips the body of a closed disclosure but keeps its summary" do
+ @user.setup_mfa!
+ @user.enable_mfa!
+ visit settings_profile_path
+ search = find_field(I18n.t("settings.settings_search.placeholder"))
+
+ search.fill_in with: I18n.t("settings.securities.show.disable_mfa")
+ assert_selector "[data-settings-search-target=results] [role=option]", text: I18n.t("settings.securities.show.disable_mfa")
+
+ search.fill_in with: I18n.t("settings.securities.show.disable_mfa_password_label")
+ assert_selector "[data-settings-search-target=empty]"
+ end
+
+ test "settings search lists pages first when their name matches and reports when nothing matches" do
+ visit settings_profile_path
+ search = find_field(I18n.t("settings.settings_search.placeholder"))
+
+ search.fill_in with: "sec"
+ assert_selector "[role=option][aria-selected=true]", text: I18n.t("settings.settings_nav.security_label")
+
+ search.fill_in with: "zzzz"
+ assert_selector "[data-settings-search-target=empty]", text: I18n.t("settings.settings_search.no_results")
+ assert_no_selector "[data-settings-search-target=results] [role=option]"
+ end
+
+ test "slash focuses settings search and Escape clears it before leaving the field" do
+ visit settings_profile_path
+
+ # Selenium treats a lone "/" as a file path, so send the keydown directly.
+ page.execute_script('document.body.dispatchEvent(new KeyboardEvent("keydown", { key: "/", bubbles: true }))')
+ assert_selector "input[type=search]:focus"
+
+ page.send_keys("tags")
+ assert_selector "[data-settings-search-target=item]:not(.hidden)", text: I18n.t("settings.settings_nav.tags_label")
+
+ page.send_keys(:escape)
+ assert_field I18n.t("settings.settings_search.placeholder"), with: ""
+ assert_current_path settings_profile_path
+ assert_selector "nav", text: I18n.t("settings.settings_nav.tags_label")
+ end
+
test "does not show admin settings to non-admin users" do
VCR.use_cassette("git_repository_provider/fetch_latest_release_notes") do
# Visit accounts path directly as non-admin user to avoid user menu issues