A platform for community discussion. Free, open, simple.
UX: Let icon pickers search the full icon set (#42554)
Régis Hanol7ae86bff94dc
diff --git a/app/assets/stylesheets/common/components/d-icon-grid-picker.scss b/app/assets/stylesheets/common/components/d-icon-grid-picker.scssindex cf3dae26513..f0b1fa9a206 100644--- a/app/assets/stylesheets/common/components/d-icon-grid-picker.scss+++ b/app/assets/stylesheets/common/components/d-icon-grid-picker.scss@@ -1,3 +1,5 @@+@use "lib/viewport";+// Custom properties for the grid layout, set on the DMenu/modal container.// The DMenu identifier generates `.fk-d-menu.d-icon-grid-picker-content`// which doesn't follow the BEM `__` pattern, so it stays outside the block.@@ -105,6 +107,10 @@box-sizing: border-box;}+ &__sentinel {+ grid-column: 1 / -1;+ }+// Favorites row inherits parent columns via subgrid&__favorites {display: grid;@@ -210,10 +216,17 @@color: var(--primary-medium);grid-column: 1 / -1;}++ &__loading-more {+ display: flex;+ justify-content: center;+ padding: 0.5em;+ grid-column: 1 / -1;+ }}// Mobile overrides-@media screen and (width <= 767px) {+@include viewport.until(md) {.fk-d-menu-modal.d-icon-grid-picker-content {.d-modal__body {padding: 0;diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rbindex f36cf30d6b3..6fc5c31f7f4 100644--- a/app/controllers/application_controller.rb+++ b/app/controllers/application_controller.rb@@ -1096,7 +1096,7 @@ class ApplicationController < ActionController::Basevalue =beginInteger(params[key])- rescue ArgumentError+ rescue ArgumentError, TypeErrorraise Discourse::InvalidParameters.new(key)enddiff --git a/app/controllers/svg_sprite_controller.rb b/app/controllers/svg_sprite_controller.rbindex ddb0db28e08..b22ccaff388 100644--- a/app/controllers/svg_sprite_controller.rb+++ b/app/controllers/svg_sprite_controller.rb@@ -1,6 +1,9 @@# frozen_string_literal: trueclass SvgSpriteController < ApplicationController+ ICONS_PER_PAGE = 100+ MAX_PAGE = 1000+skip_before_action :preload_json,:redirect_to_login_if_required,:redirect_to_profile_if_required,@@ -44,13 +47,24 @@ class SvgSpriteController < ApplicationControllerenddef icon_picker_search- params.permit(:filter, :only_available)- filter = params[:filter] || ""- only_available = params[:only_available]-- icons = SvgSprite.icon_picker_search(filter, only_available).take(500)-- render json: icons, root: false+ permitted = params.permit(:filter, :only_available)++ only_available =+ ActiveModel::Type::Boolean.new.cast(permitted[:only_available].presence || true)+ filter = permitted[:filter].to_s+ page = fetch_page_from_params(max: MAX_PAGE)++ etag = [Discourse.git_version, SvgSprite.version(@theme_id), filter, only_available, page]+ return if !stale?(etag:)++ render json:+ SvgSprite.icon_picker_search(+ filter,+ only_available,+ page:,+ per_page: ICONS_PER_PAGE,+ theme_id: @theme_id,+ )enddef svg_icondiff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex 0cd0b529327..481e34af124 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -3338,6 +3338,9 @@ en:results_count:one: "%{count} icon found"other: "%{count} icons found"+ results_loaded:+ one: "%{count} icon loaded, more available"+ other: "%{count} icons loaded, more available"favorites: "Favorites"selected_icon: "Selected icon: %{iconName}"clear: "Clear icon"diff --git a/frontend/discourse/admin/components/admin-badges-show.gjs b/frontend/discourse/admin/components/admin-badges-show.gjsindex b016022ae01..b3cc93aec07 100644--- a/frontend/discourse/admin/components/admin-badges-show.gjs+++ b/frontend/discourse/admin/components/admin-badges-show.gjs@@ -334,7 +334,7 @@ export default class AdminBadgesShow extends Component {@type="icon"as |field|>- <field.Control />+ <field.Control @onlyAvailable={{false}} /></form.Field></Content><Content @name="upload-image">diff --git a/frontend/discourse/admin/components/site-settings/icon.gjs b/frontend/discourse/admin/components/site-settings/icon.gjsindex 14e32c59f81..475ee835e8f 100644--- a/frontend/discourse/admin/components/site-settings/icon.gjs+++ b/frontend/discourse/admin/components/site-settings/icon.gjs@@ -15,6 +15,7 @@ export default class Icon extends Component {@disabled={{@disabled}}@showCaret={{true}}@showSelectedName={{true}}+ @onlyAvailable={{false}}/></template>}diff --git a/frontend/discourse/app/components/group-flair-inputs.gjs b/frontend/discourse/app/components/group-flair-inputs.gjsindex 31496ddac87..ebb507e3b27 100644--- a/frontend/discourse/app/components/group-flair-inputs.gjs+++ b/frontend/discourse/app/components/group-flair-inputs.gjs@@ -1,14 +1,13 @@-/* eslint-disable ember/no-classic-components, ember/no-observers */+/* eslint-disable ember/no-classic-components */import Component from "@ember/component";import { fn } from "@ember/helper";import { action, computed } from "@ember/object";import { tagName } from "@ember-decorators/component";-import { observes, on } from "@ember-decorators/object";+import { on } from "@ember-decorators/object";import UppyImageUploader from "discourse/components/uppy-image-uploader";-import { ajax } from "discourse/lib/ajax";-import discourseDebounce from "discourse/lib/debounce";import getURL from "discourse/lib/get-url";import { convertIconClass } from "discourse/lib/icon-library";+import { ensureSpriteSymbol } from "discourse/lib/svg-sprite-loader";import { or } from "discourse/truth-helpers";import DAvatarFlair from "discourse/ui-kit/d-avatar-flair";import DIconGridPicker from "discourse/ui-kit/d-icon-grid-picker";@@ -36,38 +35,11 @@ export default class GroupFlairInputs extends Component {}@on("didInsertElement")- @observes("model.flair_icon")- _loadSVGIcon(flairIcon) {- if (flairIcon) {- discourseDebounce(this, this._loadIcon, 1000);- }- }-_loadIcon() {- if (!this.model.flair_icon) {- return;- }-- const icon = convertIconClass(this.model.flair_icon),- c = "#svg-sprites",- h = "ajax-icon-holder",- singleIconEl = `${c} .${h}`;-- if (!icon) {- return;- }+ const icon = convertIconClass(this.model.flair_icon || "");- if (!document.querySelector(`${c} symbol#${icon}`)) {- ajax(`/svg-sprite/search/${icon}`).then((data) => {- if (!document.querySelector(singleIconEl)) {- document- .querySelector(c)- .insertAdjacentHTML("beforeend", `<div class="${h}"></div>`);- }-- document.querySelector(singleIconEl).innerHTML =- `<svg xmlns='http://www.w3.org/2000/svg' style='display: none;'>${data}</svg>`;- });+ if (icon) {+ ensureSpriteSymbol(icon);}}@@ -139,6 +111,7 @@ export default class GroupFlairInputs extends Component {@value={{this.model.flair_icon}}@onChange={{fn (mut this.model.flair_icon)}}@showCaret={{true}}+ @onlyAvailable={{false}}@label={{unless this.model.flair_icon (i18n "select_placeholder")}}/>{{else if this.flairPreviewImage}}diff --git a/frontend/discourse/app/form-kit/components/fk/control/icon.gjs b/frontend/discourse/app/form-kit/components/fk/control/icon.gjsindex cd6fbfb00a8..d3bb068d67f 100644--- a/frontend/discourse/app/form-kit/components/fk/control/icon.gjs+++ b/frontend/discourse/app/form-kit/components/fk/control/icon.gjs@@ -18,6 +18,7 @@ export default class FKControlIcon extends FKBaseControl {@allowClear={{@allowClear}}@showCaret={{true}}@showSelectedName={{true}}+ @onlyAvailable={{@onlyAvailable}}class="form-kit__control-icon"/></template>diff --git a/frontend/discourse/app/lib/icon-library.js b/frontend/discourse/app/lib/icon-library.jsindex 3f3c93d6d0b..a13247ec344 100644--- a/frontend/discourse/app/lib/icon-library.js+++ b/frontend/discourse/app/lib/icon-library.js@@ -6,7 +6,6 @@ import { i18n } from "discourse-i18n";export const SVG_NAMESPACE = "http://www.w3.org/2000/svg";let _renderers = [];-let warnMissingIcons = true;let _iconList;export const REPLACEMENTS = {@@ -62,14 +61,6 @@ export function replaceIcon(source, destination) {REPLACEMENTS[source] = destination;}-export function disableMissingIconWarning() {- warnMissingIcons = false;-}--export function enableMissingIconWarning() {- warnMissingIcons = false;-}-export function renderIcon(renderType, id, params) {params ||= {};@@ -88,6 +79,12 @@ export function renderIcon(renderType, id, params) {}}+/**+ * @param {string} id - The icon id.+ * @param {object} [params] - Options passed to the icon renderer. Set+ * `ignoreMissing` where the icon is knowingly outside the sprite subset, to+ * skip the development-mode missing-icon warning.+ */export function iconHTML(id, params) {return renderIcon("string", id, params);}@@ -124,26 +121,29 @@ function iconClasses(icon, params) {}export function setIconList(iconList) {- _iconList = iconList;+ _iconList = new Set(iconList);}export function isExistingIconId(id) {- return _iconList?.includes(id);+ return _iconList?.has(id);}function warnIfMissing(id) {- if (warnMissingIcons && isDevelopment() && !isExistingIconId(id)) {+ if (isDevelopment() && !isExistingIconId(id)) {console.warn(`The icon "${id}" is missing from the SVG subset.`); // eslint-disable-line no-console}}-function handleIconId(icon) {+function handleIconId(icon, params) {let id = icon.replacementId || icon.id || "";// TODO: clean up "thumbtack unpinned" at source instead of hereid = id.replace(" unpinned", "");- warnIfMissing(id);+ if (!params.ignoreMissing) {+ warnIfMissing(id);+ }+return id;}@@ -152,7 +152,7 @@ registerIconRenderer({name: "font-awesome",string(icon, params) {- const id = escape(handleIconId(icon));+ const id = escape(handleIconId(icon, params));let html = `<svg class='${escape(iconClasses(icon, params))} svg-string' width='1em' height='1em'`;if (params["aria-label"]) {@@ -187,7 +187,7 @@ registerIconRenderer({},element(icon, params) {- const id = escape(handleIconId(icon));+ const id = escape(handleIconId(icon, params));const classes = iconClasses(icon, params) + " svg-node";const svgElement = document.createElementNS(SVG_NAMESPACE, "svg");diff --git a/frontend/discourse/app/lib/svg-sprite-loader.js b/frontend/discourse/app/lib/svg-sprite-loader.jsindex 1bcd5bbca92..b39246c4274 100644--- a/frontend/discourse/app/lib/svg-sprite-loader.js+++ b/frontend/discourse/app/lib/svg-sprite-loader.js@@ -1,16 +1,119 @@+import { ajax } from "discourse/lib/ajax";+import { SVG_NAMESPACE } from "discourse/lib/icon-library";import loadScript from "discourse/lib/load-script";const SVG_CONTAINER_ID = "svg-sprites";+const EXTRA_SPRITE_NAME = "extra-icons";-export function loadSprites(spritePath, spriteName) {+function spriteContainerElement() {let spriteContainer = document.getElementById(SVG_CONTAINER_ID);if (!spriteContainer) {spriteContainer = document.createElement("div");spriteContainer.id = SVG_CONTAINER_ID;const spriteWrapper = document.querySelector("discourse-assets-icons");- spriteWrapper?.appendChild(spriteContainer);+ (spriteWrapper ?? document.body).appendChild(spriteContainer);+ }+ return spriteContainer;+}++/**+ * Whether the page sprite can already render an icon.+ *+ * @param {string} id+ * @returns {boolean}+ */+export function hasSpriteSymbol(id) {+ return !!spriteContainerElement().querySelector(+ `symbol[id="${CSS.escape(id)}"]`+ );+}++/**+ * Appends the `<symbol>` markup of every icon whose id is not already rendered+ * under `searchRoot`, so `<use href="#id">` resolves for it.+ *+ * @param {Element} target - Element the missing symbols are appended to.+ * @param {Array<{id: string, symbol?: string}>} icons - Icons and, for those the+ * target cannot already render, their `<symbol>` markup.+ * @param {ParentNode} searchRoot - Scope the existing-symbol lookup runs against.+ */+function appendSymbols(target, icons, searchRoot) {+ const candidates = icons.filter(({ symbol }) => symbol);++ if (!candidates.length) {+ return;+ }++ const present = new Set(+ Array.from(searchRoot.querySelectorAll("symbol[id]"), ({ id }) => id)+ );+ const missing = candidates.filter(({ id }) => !present.has(id));++ if (missing.length) {+ target.insertAdjacentHTML(+ "beforeend",+ missing.map(({ symbol }) => symbol).join("")+ );+ }+}++/**+ * Adds symbols to the page sprite for icons it does not already have, so+ * `<use href="#id">` resolves for a value picked before it joins the sprite.+ *+ * @param {Array<{id: string, symbol?: string}>} icons - Icons and, for those the+ * sprite cannot already render, their `<symbol>` markup.+ */+export function addExtraSpriteSymbols(icons) {+ if (!icons.some(({ symbol }) => symbol)) {+ return;+ }++ const spriteContainer = spriteContainerElement();++ let sprites = spriteContainer.querySelector(`.${EXTRA_SPRITE_NAME}`);+ if (!sprites) {+ sprites = document.createElementNS(SVG_NAMESPACE, "svg");+ sprites.classList.add(EXTRA_SPRITE_NAME);+ sprites.style.display = "none";+ spriteContainer.appendChild(sprites);+ }++ appendSymbols(sprites, icons, spriteContainer);+}++/**+ * Removes every symbol added through {@link addExtraSpriteSymbols}.+ */+export function clearExtraSpriteSymbols() {+ document+ .getElementById(SVG_CONTAINER_ID)+ ?.querySelector(`.${EXTRA_SPRITE_NAME}`)+ ?.remove();+}++/**+ * Fetches an icon's `<symbol>` markup and adds it to the page sprite when the+ * sprite cannot already render it. Failures are swallowed: the icon simply+ * stays unrendered until it joins the sprite.+ *+ * @param {string} id+ * @returns {Promise<void>}+ */+export async function ensureSpriteSymbol(id) {+ if (hasSpriteSymbol(id)) {+ return;}+ try {+ const symbol = await ajax(`/svg-sprite/search/${encodeURIComponent(id)}`);+ addExtraSpriteSymbols([{ id, symbol }]);+ } catch {}+}++export function loadSprites(spritePath, spriteName) {+ const spriteContainer = spriteContainerElement();+let sprites = spriteContainer.querySelector(`.${spriteName}`);if (!sprites) {sprites = document.createElement("div");diff --git a/frontend/discourse/app/ui-kit/d-icon-grid-picker/content.gjs b/frontend/discourse/app/ui-kit/d-icon-grid-picker/content.gjsindex 52952d73d9f..798a72df8be 100644--- a/frontend/discourse/app/ui-kit/d-icon-grid-picker/content.gjs+++ b/frontend/discourse/app/ui-kit/d-icon-grid-picker/content.gjs@@ -4,19 +4,71 @@ import { tracked } from "@glimmer/tracking";import { fn, hash } from "@ember/helper";import { on } from "@ember/modifier";import { action } from "@ember/object";+import { schedule } from "@ember/runloop";import { service } from "@ember/service";+import { trustHTML } from "@ember/template";import { modifier } from "ember-modifier";import withEventValue from "discourse/helpers/with-event-value";import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import { SVG_NAMESPACE } from "discourse/lib/icon-library";+import { addExtraSpriteSymbols } from "discourse/lib/svg-sprite-loader";import { eq } from "discourse/truth-helpers";import DAsyncContent from "discourse/ui-kit/d-async-content";import DFilterInput from "discourse/ui-kit/d-filter-input";+import DLoadMore from "discourse/ui-kit/d-load-more";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import dIcon from "discourse/ui-kit/helpers/d-icon";+import dLoadingSpinner from "discourse/ui-kit/helpers/d-loading-spinner";import { i18n } from "discourse-i18n";-/* Module-level cache for the unfiltered icon list, keyed by onlyAvailable flag */-const unfilteredIconCache = new Map();+const ICON_TOOLTIP = "d-icon-grid-picker-icon";++/**+ * @typedef IconButtonSignature+ *+ * @property {object} Args+ *+ * @property {{id: string, symbol?: string}} Args.icon - The icon to render.+ * @property {boolean} [Args.selected] - Whether the icon is the currently selected value.+ * @property {(icon: {id: string, symbol?: string}) => void} Args.onSelect - Called with the picked icon.+ */++/** @extends {Component<IconButtonSignature>} */+class IconButton extends Component {+ /**+ * The icon's own `<symbol>`, for icons the page sprite cannot render. The+ * `<svg>` wrapper puts it in the SVG namespace when inserted as HTML, and it+ * renders in the cell that uses it, so it is torn down with that cell.+ */+ get symbol() {+ const { symbol } = this.args.icon;++ return symbol+ ? trustHTML(+ `<svg xmlns="${SVG_NAMESPACE}" style="display: none">${symbol}</svg>`+ )+ : null;+ }++ <template>+ <button+ type="button"+ role="option"+ aria-label={{@icon.id}}+ aria-selected={{if @selected "true" "false"}}+ class={{dConcatClass+ "d-icon-grid-picker__icon"+ (if @selected "--selected")+ }}+ data-icon-id={{@icon.id}}+ {{on "click" (fn @onSelect @icon)}}+ >+ {{this.symbol}}+ {{dIcon @icon.id ignoreMissing=true}}+ </button>+ </template>+}/*** The content panel rendered inside the DMenu dropdown or modal.@@ -27,7 +79,7 @@ const unfilteredIconCache = new Map();* @param {string[]} [favorites] - Icon IDs to display in a pinned favorites row above the grid.* @param {boolean} [showSelectedName] - When true, the selected favorite chip also displays* the icon name alongside the icon.- * @param {boolean} [onlyAvailable] - When true, only shows icons available in the+ * @param {boolean} [onlyAvailable] - When true, only offers icons available in the* current SVG sprite set. Defaults to true.*/export default class DIconGridPickerContent extends Component {@@ -36,7 +88,18 @@ export default class DIconGridPickerContent extends Component {@service tooltip;@tracked filter = "";- @tracked resultCount = null;++ /** @type {Array<{id: string, symbol?: string}>?} Null until the first page resolves. */+ @tracked icons = null;++ @tracked hasMore = false;+ @tracked loadingMore = false;+ @tracked gridWrapper = null;++ registerGridWrapper = modifier((/** @type {HTMLElement} */ element) => {+ this.gridWrapper = element;+ return () => (this.gridWrapper = null);+ });/*** Modifier that measures the natural content width of the selected-chip element@@ -61,29 +124,60 @@ export default class DIconGridPickerContent extends Component {});/**- * Modifier that registers a hover tooltip showing the icon ID on each grid cell.- * Skips the selected-chip element since it already displays the name inline.+ * Modifier that shows a hover tooltip with the icon ID for any cell in the+ * grid. One delegated tooltip rather than one per cell, since the grid grows+ * by a page at a time. The selected chip is skipped: it shows its name inline.*/- registerIconTooltip = modifier((/** @type {HTMLElement} */ element) => {- const iconId = element.dataset.iconId;- if (- !iconId ||- element.classList.contains("d-icon-grid-picker__selected-chip")- ) {- return;- }+ iconTooltips = modifier((/** @type {HTMLElement} */ element) => {+ /** @type {HTMLElement?} */+ let current = null;- const instance = this.tooltip.register(element, {- content: iconId,- placement: "top",- fallbackPlacements: ["bottom"],- triggers: ["hover"],- animated: false,- });+ const closeTooltip = () => {+ current = null;+ this.tooltip.close(ICON_TOOLTIP);+ };++ const onPointerOver = (/** @type {PointerEvent} */ event) => {+ const cell = /** @type {HTMLElement?} */ (+ /** @type {HTMLElement} */ (event.target).closest?.(+ ".d-icon-grid-picker__icon[data-icon-id]:not(.d-icon-grid-picker__selected-chip)"+ )+ );++ if (cell === current) {+ return;+ }- return () => instance.destroy();+ current = cell;++ if (!cell) {+ this.tooltip.close(ICON_TOOLTIP);+ return;+ }++ this.tooltip.show(cell, {+ identifier: ICON_TOOLTIP,+ content: cell.dataset.iconId,+ placement: "top",+ fallbackPlacements: ["bottom"],+ animated: false,+ });+ };++ element.addEventListener("pointerover", onPointerOver);+ element.addEventListener("pointerleave", closeTooltip);++ return () => {+ element.removeEventListener("pointerover", onPointerOver);+ element.removeEventListener("pointerleave", closeTooltip);+ this.tooltip.close(ICON_TOOLTIP);+ };});+ #search = 0;++ #page = 0;+/*** Returns the list of favorite icon IDs to display, with the currently* selected icon always first (deduplicated against the favorites array).@@ -116,21 +210,17 @@ export default class DIconGridPickerContent extends Component {}/**- * Updates the tracked filter string as the user types in the search input.+ * Starts a new search: paging belongs to the search that produced it, so the+ * grid stops growing and any page still in flight is discarded on arrival.** @param {string} value - The current input value.*/@action- onFilterInput(value) {+ setFilter(value) {this.filter = value;- }-- /**- * Clears the search filter, restoring the full icon list and favorites row.- */- @action- clearFilter() {- this.filter = "";+ this.hasMore = false;+ this.loadingMore = false;+ this.#search++;}/**@@ -176,28 +266,44 @@ export default class DIconGridPickerContent extends Component {case "ArrowDown": {event.preventDefault();event.stopPropagation();- const below = allIcons- .filter((el) => el.offsetTop > target.offsetTop)- .find((el) => el.offsetLeft === target.offsetLeft);+ let below = null;+ let nextRow = null;+ for (let i = idx + 1; i < allIcons.length; i++) {+ const el = allIcons[i];+ if (el.offsetTop <= target.offsetTop) {+ continue;+ }+ nextRow ??= el;+ if (el.offsetLeft === target.offsetLeft) {+ below = el;+ break;+ }+ }if (below) {below.focus();- } else {+ } else if (nextRow) {/* No exact column match (e.g. selected chip spans columns);jump to first icon on the next row */- const nextRow = allIcons.find(- (el) => el.offsetTop > target.offsetTop- );- nextRow?.focus();+ nextRow.focus();+ } else {+ this.loadMoreAndFocus();}break;}case "ArrowUp": {event.preventDefault();event.stopPropagation();- const above = [...allIcons]- .reverse()- .filter((el) => el.offsetTop < target.offsetTop)- .find((el) => el.offsetLeft === target.offsetLeft);+ let above = null;+ for (let i = idx - 1; i >= 0; i--) {+ const el = allIcons[i];+ if (el.offsetTop >= target.offsetTop) {+ continue;+ }+ if (el.offsetLeft === target.offsetLeft) {+ above = el;+ break;+ }+ }if (above) {above.focus();} else {@@ -245,41 +351,132 @@ export default class DIconGridPickerContent extends Component {}get resultAnnouncement() {- if (this.resultCount === null) {+ if (!this.icons) {return "";}- return i18n("d_icon_grid_picker.results_count", {- count: this.resultCount,- });++ return i18n(+ this.hasMore+ ? "d_icon_grid_picker.results_loaded"+ : "d_icon_grid_picker.results_count",+ { count: this.icons.length }+ );+ }++ /**+ * @param {number} page+ * @param {AbortSignal} [signal]+ * @returns {Promise<{icons: Array<{id: string, symbol?: string}>, has_more: boolean}>}+ */+ async #fetchPage(page, signal) {+ const request = /** @type {Promise<any> & {abort: () => void}} */ (+ ajax("/svg-sprite/picker-search", {+ data: {+ filter: this.filter.trim(),+ only_available: this.args.onlyAvailable ?? true,+ page,+ },+ })+ );++ signal?.addEventListener("abort", () => request.abort(), { once: true });++ return await request;}/**- * Fetches icons from the server, optionally filtered by a search term.- * Used as the `@asyncData` callback for the `AsyncContent` loader.+ * Whether an async continuation still belongs to the live component and to+ * the search that started it.*- * @param {string} filter - The search string to filter icons by name.- * @returns {Promise<Array<{id: string, symbol: string}>>} Array of matching icons.+ * @param {number} search+ * @returns {boolean}+ */+ #isCurrent(search) {+ return this.#search === search && !this.isDestroying && !this.isDestroyed;+ }++ /**+ * Loads the first page of icons. Used as the `@asyncData` callback for the+ * `AsyncContent` loader, which debounces it and aborts superseded searches.+ *+ * @param {string} _filter - Tracked by `@context`; read from `this.filter`.+ * @param {{signal: AbortSignal}} options+ * @returns {Promise<Array<{id: string, symbol?: string}>>} The first page.*/@action- async fetchIcons(filter) {- const onlyAvailable = this.args.onlyAvailable ?? true;+ async fetchIcons(_filter, { signal }) {+ const search = this.#search;+ const { icons, has_more: hasMore } = await this.#fetchPage(0, signal);- if (!filter && unfilteredIconCache.has(onlyAvailable)) {- const cached = unfilteredIconCache.get(onlyAvailable);- this.resultCount = cached.length;- return cached;+ if (this.#isCurrent(search)) {+ this.icons = icons;+ this.hasMore = hasMore;+ this.#page = 0;}- const icons = await ajax("/svg-sprite/picker-search", {- data: { filter: filter || "", only_available: onlyAvailable },- });+ return icons;+ }- if (!filter) {- unfilteredIconCache.set(onlyAvailable, icons);+ @action+ async loadMore() {+ if (this.loadingMore || !this.hasMore) {+ return;}- this.resultCount = icons.length;- return icons;+ const search = this.#search;+ this.loadingMore = true;++ try {+ const { icons, has_more: hasMore } = await this.#fetchPage(+ this.#page + 1+ );++ if (!this.#isCurrent(search)) {+ return;+ }++ this.icons = [...this.icons, ...icons];+ this.hasMore = hasMore;+ this.#page++;+ } catch (error) {+ if (this.#isCurrent(search)) {+ this.hasMore = false;+ popupAjaxError(error);+ }+ } finally {+ if (this.#isCurrent(search)) {+ this.loadingMore = false;+ }+ }+ }++ /**+ * Loads the next page on behalf of the keyboard, which has no sentinel to+ * scroll into, and moves focus onto the first icon that arrives.+ */+ async loadMoreAndFocus() {+ const next = this.icons.length;+ await this.loadMore();++ schedule("afterRender", () => {+ /** @type {HTMLElement | undefined} */ (+ this.gridWrapper?.querySelector(+ `.d-icon-grid-picker__grid [data-icon-id="${this.icons[next]?.id}"]`+ )+ )?.focus();+ });+ }++ /**+ * Keeps the picked icon rendering once the picker closes, until the value is+ * saved and the icon becomes part of the sprite.+ *+ * @param {{id: string, symbol?: string}} icon+ */+ @action+ selectIcon(icon) {+ addExtraSpriteSymbols([icon]);+ this.args.onSelect(icon.id);}<template>@@ -295,8 +492,8 @@ export default class DIconGridPickerContent extends Component {aria-controls="d-icon-grid-picker-listbox"placeholder={{i18n "d_icon_grid_picker.search_placeholder"}}@value={{this.filter}}- @filterAction={{withEventValue this.onFilterInput}}- @onClearInput={{this.clearFilter}}+ @filterAction={{withEventValue this.setFilter}}+ @onClearInput={{fn this.setFilter ""}}@icons={{hash left="magnifying-glass"}}@containerClass="d-icon-grid-picker__filter"/>@@ -305,6 +502,8 @@ export default class DIconGridPickerContent extends Component {<divclass="d-icon-grid-picker__grid-wrapper"id="d-icon-grid-picker-listbox"+ {{this.registerGridWrapper}}+ {{this.iconTooltips}}role="listbox"aria-label={{i18n "d_icon_grid_picker.select_icon"}}>@@ -327,11 +526,10 @@ export default class DIconGridPickerContent extends Component {(if @showSelectedName "d-icon-grid-picker__selected-chip")}}data-icon-id={{favIcon}}- {{this.registerIconTooltip}}{{this.snapToGrid}}- {{on "click" (fn @onSelect favIcon)}}+ {{on "click" (fn this.selectIcon (hash id=favIcon))}}>- {{dIcon favIcon}}+ {{dIcon favIcon ignoreMissing=true}}{{#if @showSelectedName}}<spanclass="d-icon-grid-picker__selected-name"@@ -339,19 +537,10 @@ export default class DIconGridPickerContent extends Component {{{/if}}</button>{{else}}- {{! eslint-disable ember/template-require-context-role }}- <button- type="button"- role="option"- aria-label={{favIcon}}- aria-selected="false"- class="d-icon-grid-picker__icon"- data-icon-id={{favIcon}}- {{this.registerIconTooltip}}- {{on "click" (fn @onSelect favIcon)}}- >- {{dIcon favIcon}}- </button>+ <IconButton+ @icon={{hash id=favIcon}}+ @onSelect={{this.selectIcon}}+ />{{/if}}{{/each}}</div>@@ -365,27 +554,16 @@ export default class DIconGridPickerContent extends Component {><:loading><div class="d-icon-grid-picker__loading">- <div class="spinner"></div>+ {{dLoadingSpinner}}</div></:loading>- <:content as |icons|>- {{#each icons as |item|}}- {{! eslint-disable ember/template-require-context-role }}- <button- type="button"- role="option"- aria-label={{item.id}}- aria-selected={{if (eq item.id @value) "true" "false"}}- class={{dConcatClass- "d-icon-grid-picker__icon"- (if (eq item.id @value) "--selected")- }}- data-icon-id={{item.id}}- {{this.registerIconTooltip}}- {{on "click" (fn @onSelect item.id)}}- >- {{dIcon item.id}}- </button>+ <:content>+ {{#each this.icons as |item|}}+ <IconButton+ @icon={{item}}+ @selected={{eq item.id @value}}+ @onSelect={{this.selectIcon}}+ />{{/each}}</:content><:empty>@@ -395,7 +573,23 @@ export default class DIconGridPickerContent extends Component {</:empty></DAsyncContent></div>++ {{#if this.loadingMore}}+ <div class="d-icon-grid-picker__loading-more">+ {{dLoadingSpinner}}+ </div>+ {{/if}}++ {{#if this.hasMore}}+ <DLoadMore+ @action={{this.loadMore}}+ @isLoading={{this.loadingMore}}+ @root={{this.gridWrapper}}+ class="d-icon-grid-picker__sentinel"+ />+ {{/if}}</div>+<div class="sr-only" aria-live="polite" role="status">{{this.resultAnnouncement}}</div>diff --git a/frontend/discourse/app/ui-kit/d-icon-grid-picker/index.gjs b/frontend/discourse/app/ui-kit/d-icon-grid-picker/index.gjsindex df3fd0f2a9f..12fb7c3c5f7 100644--- a/frontend/discourse/app/ui-kit/d-icon-grid-picker/index.gjs+++ b/frontend/discourse/app/ui-kit/d-icon-grid-picker/index.gjs@@ -30,8 +30,9 @@ import { i18n } from "discourse-i18n";* @property {boolean} [Args.showCaret] - When true, shows a chevron icon in the trigger* that flips between angle-down and angle-up based on the menu's expanded state.* @property {boolean} [Args.disabled] - When true, disables the trigger button and clear button.- * @property {boolean} [Args.onlyAvailable] - When true, only shows icons available in the- * current SVG sprite set. Defaults to true.+ * @property {boolean} [Args.onlyAvailable] - When true, only offers icons available in the+ * current SVG sprite set. Defaults to true. Pass false only where saving the value adds+ * it to the sprite, otherwise the picked icon is blank once the page reloads.* @property {string} [Args.iconColor] - CSS color value applied to icons in both the trigger* and the picker grid via the `--icon-color` custom property.* @property {string} [Args.selectedTitle] - Translation key for the trigger button title when an@@ -122,14 +123,6 @@ export default class DIconGridPicker extends Component {this.menu = api;}- /**- * Forwards to the external `@onShow` callback if provided.- */- @action- onShow() {- this.args.onShow?.();- }-/*** Handles icon selection by invoking the `@onChange` callback and closing* the menu/modal.@@ -170,14 +163,14 @@ export default class DIconGridPicker extends Component {@modalForMobile={{this.modalForMobile}}@maxWidth={{490}}@autofocus={{true}}- @onShow={{this.onShow}}+ @onShow={{@onShow}}@onRegisterApi={{this.onRegisterMenu}}@onClose={{@onClose}}@inline={{@inline}}><:trigger>{{#if @value}}- {{dIcon @value}}+ {{dIcon @value ignoreMissing=true}}{{/if}}{{#if this.triggerLabel}}diff --git a/frontend/discourse/app/ui-kit/d-load-more.gjs b/frontend/discourse/app/ui-kit/d-load-more.gjsindex 8106d1063c6..18080eab7ad 100644--- a/frontend/discourse/app/ui-kit/d-load-more.gjs+++ b/frontend/discourse/app/ui-kit/d-load-more.gjs@@ -1,7 +1,6 @@import Component from "@glimmer/component";import { action } from "@ember/object";import discourseDebounce from "discourse/lib/debounce";-import dElement from "discourse/ui-kit/helpers/d-element";import dObserveIntersection from "discourse/ui-kit/modifiers/d-observe-intersection";let ENABLE_LOAD_MORE_OBSERVER = true;@@ -16,26 +15,36 @@ export function enableLoadMoreObserver() {}/**- * A component that implements infinite loading using IntersectionObserver.+ * @typedef DLoadMoreSignature*- * LoadMore triggers an action when a sentinel element becomes visible in the viewport,- * which is typically used to load additional content. Besides the `action` argument, it also takes- * in additional options to customize the observer's behavior;- * Refer to https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/IntersectionObserver#options for a full list.+ * @property {HTMLDivElement} Element+ * @property {object} Args*- * @param {Function} action - The action to trigger when more content should be loaded- * @param {boolean} [enabled=true] - Whether to allow the loadMore action to trigger.+ * @property {() => void} Args.action - The action to trigger when more content should be loaded+ * @property {boolean} [Args.enabled=true] - Whether to allow the loadMore action to trigger.* Use this when you know there's no more content available (e.g., `model.canLoadMore`).* When false, the observer continues to run but the action won't be triggered.- * @param {boolean} [isLoading=false] - Whether content is currently loading.+ * @property {boolean} [Args.isLoading=false] - Whether content is currently loading.* When true, the IntersectionObserver won't be created, preventing premature triggers* during initial content load. Pass this to avoid race conditions during page initialization.- * @param {string} [rootMargin="0px 0px 0px 0px"] - Margin around the root element for intersection detection- * @param {number} [threshold=0.0] - Threshold at which the intersection callback is triggered- * @param {string|Element} [root=null] - The element to observe intersection within, or a CSS+ * @property {string} [Args.rootMargin="0px 0px 0px 0px"] - Margin around the root element for intersection detection+ * @property {number} [Args.threshold=0.0] - Threshold at which the intersection callback is triggered+ * @property {string|Element|null} [Args.root=null] - The element to observe intersection within, or a CSS* selector for it. Pass the element itself when it mounts in the same render as the* sentinel, since a selector cannot resolve a root that does not exist yet.*+ * @property {object} Blocks+ * @property {[]} Blocks.default - Content rendered above the sentinel.+ */++/**+ * A component that implements infinite loading using IntersectionObserver.+ *+ * LoadMore triggers an action when a sentinel element becomes visible in the viewport,+ * which is typically used to load additional content. Besides the `action` argument, it also takes+ * in additional options to customize the observer's behavior;+ * Refer to https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/IntersectionObserver#options for a full list.+ ** @example Basic usage with a block:* ```gjs* <LoadMore @action={{this.loadMoreTopics}}>@@ -65,16 +74,19 @@ export function enableLoadMoreObserver() {* </LoadMore>* ```*- * @example With custom IntersectionObserver options:+ * @example With custom IntersectionObserver options (attributes land on the+ * sentinel itself when no block is given, so consumers can style it):* ```gjs* <LoadMore* @action={{this.fetchMoreUsers}}* @rootMargin="100px"* @threshold={{0.2}}* @root={{this.scrollContainer}}- * class="users-container"+ * class="users-list__sentinel"* />* ```+ *+ * @extends {Component<DLoadMoreSignature>}*/export default class DLoadMore extends Component {observer;@@ -106,8 +118,8 @@ export default class DLoadMore extends Component {}<template>- {{#let (dElement (if (has-block) "div" "")) as |Wrapper|}}- <Wrapper ...attributes>+ {{#if (has-block)}}+ <div ...attributes>{{yield}}<div{{dObserveIntersection@@ -120,7 +132,20 @@ export default class DLoadMore extends Component {class="load-more-sentinel"aria-hidden="true"/>- </Wrapper>- {{/let}}+ </div>+ {{else}}+ <div+ {{dObserveIntersection+ this.onIntersection+ threshold=this.threshold+ rootMargin=this.rootMargin+ root=this.root+ isLoading=@isLoading+ }}+ class="load-more-sentinel"+ aria-hidden="true"+ ...attributes+ />+ {{/if}}</template>}diff --git a/frontend/discourse/select-kit/components/icon-picker.js b/frontend/discourse/select-kit/components/icon-picker.jsindex 3fa89704578..25f384c1639 100644--- a/frontend/discourse/select-kit/components/icon-picker.js+++ b/frontend/discourse/select-kit/components/icon-picker.js@@ -2,26 +2,22 @@ import { action, computed } from "@ember/object";import { classNames } from "@ember-decorators/component";import { ajax } from "discourse/lib/ajax";import deprecated from "discourse/lib/deprecated";-import { isDevelopment } from "discourse/lib/environment";import { makeArray } from "discourse/lib/helpers";-import {- convertIconClass,- disableMissingIconWarning,- enableMissingIconWarning,-} from "discourse/lib/icon-library";+import { convertIconClass } from "discourse/lib/icon-library";+import { addExtraSpriteSymbols } from "discourse/lib/svg-sprite-loader";import FilterForMore from "discourse/select-kit/components/filter-for-more";import MultiSelectComponent from "discourse/select-kit/components/multi-select";import {MAIN_COLLECTION,pluginApiIdentifiers,+ selectKitOptions,} from "discourse/select-kit/components/select-kit";const MORE_ICONS_COLLECTION = "MORE_ICONS_COLLECTION";-const MAX_RESULTS_RETURNED = 200;-// Matches max returned results from icon_picker_search in svg_sprite_controller.rb@classNames("icon-picker")@pluginApiIdentifiers("icon-picker")+@selectKitOptions({ ignoreMissingIcons: true })export default class IconPicker extends MultiSelectComponent {init() {super.init(...arguments);@@ -32,11 +28,8 @@ export default class IconPicker extends MultiSelectComponent {);this._cachedIconsList = null;- this._resultCount = 0;-- if (isDevelopment()) {- disableMissingIconWarning();- }+ this._cachedHasMore = false;+ this._hasMore = false;this.insertAfterCollection(MAIN_COLLECTION, MORE_ICONS_COLLECTION);}@@ -50,7 +43,7 @@ export default class IconPicker extends MultiSelectComponent {modifyContentForCollection(collection) {if (collection === MORE_ICONS_COLLECTION) {return {- shouldShowMoreTip: this._resultCount === MAX_RESULTS_RETURNED,+ shouldShowMoreTip: this._hasMore,};}}@@ -62,7 +55,7 @@ export default class IconPicker extends MultiSelectComponent {search(filter = "") {if (filter === "" && this._cachedIconsList?.length) {- this._resultCount = this._cachedIconsList.length;+ this._hasMore = this._cachedHasMore;return this._cachedIconsList;} else {return ajax("/svg-sprite/picker-search", {@@ -70,12 +63,14 @@ export default class IconPicker extends MultiSelectComponent {filter,only_available: this.onlyAvailable,},- }).then((icons) => {- icons = icons.map(this._processIcon);+ }).then((response) => {+ addExtraSpriteSymbols(response.icons);+ const icons = response.icons.map(this._processIcon);if (filter === "") {this._cachedIconsList = icons;+ this._cachedHasMore = response.has_more;}- this._resultCount = icons.length;+ this._hasMore = response.has_more;return icons;});}@@ -85,29 +80,6 @@ export default class IconPicker extends MultiSelectComponent {const iconName = typeof icon === "object" ? icon.id : icon,strippedIconName = convertIconClass(iconName);- const spriteEl = "#svg-sprites",- holder = "ajax-icon-holder";-- if (typeof icon === "object") {- if (!document.querySelector(`${spriteEl} .${holder}`)) {- document- .querySelector(spriteEl)- .insertAdjacentHTML(- "beforeend",- `<div class="${holder}" style='display: none;'></div>`- );- }-- if (!document.querySelector(`${spriteEl} symbol#${strippedIconName}`)) {- document- .querySelector(`${spriteEl} .${holder}`)- .insertAdjacentHTML(- "beforeend",- `<svg xmlns='http://www.w3.org/2000/svg'>${icon.symbol}</svg>`- );- }- }-return {id: iconName,name: iconName,@@ -116,17 +88,11 @@ export default class IconPicker extends MultiSelectComponent {}willDestroyElement() {- document- .querySelectorAll("#svg-sprites .ajax-icon-holder")- .forEach((el) => el.remove());super.willDestroyElement(...arguments);this._cachedIconsList = null;- this._resultCount = 0;-- if (isDevelopment()) {- enableMissingIconWarning();- }+ this._cachedHasMore = false;+ this._hasMore = false;}@actiondiff --git a/frontend/discourse/select-kit/components/select-kit/select-kit-row.gjs b/frontend/discourse/select-kit/components/select-kit/select-kit-row.gjsindex 39f4abf9ae1..ae5c16d701b 100644--- a/frontend/discourse/select-kit/components/select-kit/select-kit-row.gjs+++ b/frontend/discourse/select-kit/components/select-kit/select-kit-row.gjs@@ -240,7 +240,11 @@ export default class SelectKitRow extends Component {<template>{{#each this.icons as |i|}}- {{dIcon i translatedTitle=this.dasherizedTitle}}+ {{dIcon+ i+ translatedTitle=this.dasherizedTitle+ ignoreMissing=this.selectKit.options.ignoreMissingIcons+ }}{{/each}}<span class="name">diff --git a/frontend/discourse/tests/integration/components/d-icon-grid-picker-test.gjs b/frontend/discourse/tests/integration/components/d-icon-grid-picker-test.gjsindex d274575c3ca..b79943ffe72 100644--- a/frontend/discourse/tests/integration/components/d-icon-grid-picker-test.gjs+++ b/frontend/discourse/tests/integration/components/d-icon-grid-picker-test.gjs@@ -1,5 +1,9 @@import { click, render, triggerKeyEvent, waitFor } from "@ember/test-helpers";import { module, test } from "qunit";+import {+ clearExtraSpriteSymbols,+ hasSpriteSymbol,+} from "discourse/lib/svg-sprite-loader";import { setupRenderingTest } from "discourse/tests/helpers/component-test";import pretender, { response } from "discourse/tests/helpers/create-pretender";import DIconGridPicker from "discourse/ui-kit/d-icon-grid-picker";@@ -10,6 +14,10 @@ function iconFixtures(ids) {return ids.map((id) => ({ id, symbol: `<symbol id="${id}"></symbol>` }));}+function pickerResponse(icons, hasMore = false) {+ return response(200, { icons, has_more: hasMore });+}+module("Integration | Component | DIconGridPicker", function (hooks) {setupRenderingTest(hooks);@@ -18,7 +26,7 @@ module("Integration | Component | DIconGridPicker", function (hooks) {const filter = request.queryParams.filter || "";if (filter === "no-match-xyz") {- return response(200, []);+ return pickerResponse([]);}const allIcons = iconFixtures([@@ -30,16 +38,15 @@ module("Integration | Component | DIconGridPicker", function (hooks) {]);if (filter) {- return response(- 200,- allIcons.filter((i) => i.id.includes(filter))- );+ return pickerResponse(allIcons.filter((i) => i.id.includes(filter)));}- return response(200, allIcons);+ return pickerResponse(allIcons);});});+ hooks.afterEach(clearExtraSpriteSymbols);+test("renders trigger with selected icon", async function (assert) {await render(<template>@@ -580,3 +587,133 @@ async function fillInFilterInput(input, value) {await new Promise((resolve) => setTimeout(resolve, 300));await waitFor(".d-icon-grid-picker__icon, .d-icon-grid-picker__empty");}++module("Integration | Component | DIconGridPicker | paging", function (hooks) {+ setupRenderingTest(hooks);++ const PAGE_SIZE = 100;+ const UNBUNDLED = "unbundled-test-icon";++ let requests;++ function pageOf(index) {+ return iconFixtures(+ Array.from({ length: PAGE_SIZE }, (_, i) => `icon-${index}-${i}`)+ );+ }++ hooks.beforeEach(function () {+ requests = [];++ pretender.get("/svg-sprite/picker-search", (request) => {+ requests.push(request.queryParams);++ const page = parseInt(request.queryParams.page, 10) || 0;++ if (request.queryParams.filter === UNBUNDLED) {+ return pickerResponse(iconFixtures([UNBUNDLED]));+ }++ return page < 2+ ? pickerResponse(pageOf(page), true)+ : pickerResponse(iconFixtures(["last"]));+ });+ });++ hooks.afterEach(clearExtraSpriteSymbols);++ test("asks for the first page and reports whether more exist", async function (assert) {+ await render(+ <template>+ <DIconGridPicker @value={{null}} @onChange={{noop}} />+ </template>+ );++ await click(".d-icon-grid-picker-trigger");+ await waitFor(".d-icon-grid-picker__icon");++ assert.deepEqual(+ requests,+ [{ filter: "", only_available: "true", page: "0" }],+ "requests the first page of available icons"+ );+ assert+ .dom(".d-icon-grid-picker__grid .d-icon-grid-picker__icon")+ .exists({ count: PAGE_SIZE }, "renders one page of icons");+ });++ test("loads the next page when arrowing past the last icon", async function (assert) {+ await render(+ <template>+ <DIconGridPicker @value={{null}} @onChange={{noop}} />+ </template>+ );++ await click(".d-icon-grid-picker-trigger");+ await waitFor(".d-icon-grid-picker__icon");++ const icons = [...document.querySelectorAll(".d-icon-grid-picker__icon")];+ const last = icons[icons.length - 1];+ last.focus();+ await triggerKeyEvent(last, "keydown", "ArrowDown");+ await waitFor(`[data-icon-id="icon-1-0"]`);++ assert.strictEqual(requests[1].page, "1", "asks for the next page");+ assert+ .dom(".d-icon-grid-picker__grid .d-icon-grid-picker__icon")+ .exists({ count: PAGE_SIZE * 2 }, "appends to the icons already shown");+ assert+ .dom(document.activeElement)+ .hasAttribute(+ "data-icon-id",+ "icon-1-0",+ "moves focus onto the first icon of the new page"+ );+ });++ test("keeps searched icons out of the page sprite until one is picked", async function (assert) {+ let selected;++ const onChange = (value) => (selected = value);++ await render(+ <template>+ <DIconGridPicker+ @value={{null}}+ @onChange={{onChange}}+ @onlyAvailable={{false}}+ />+ </template>+ );++ await click(".d-icon-grid-picker-trigger");+ await waitFor(".d-icon-grid-picker__icon");++ await fillInFilterInput(+ document.querySelector(".d-icon-grid-picker__filter .filter-input"),+ UNBUNDLED+ );+ await waitFor(`[data-icon-id="${UNBUNDLED}"]`);++ assert.strictEqual(+ requests[0].only_available,+ "false",+ "searches every icon"+ );+ assert+ .dom(`[data-icon-id="${UNBUNDLED}"] symbol#${UNBUNDLED}`, document.body)+ .exists("renders the symbol so the grid can display it");+ assert.false(+ hasSpriteSymbol(UNBUNDLED),+ "leaves the page sprite alone while browsing"+ );++ await click(`[data-icon-id="${UNBUNDLED}"]`);++ assert.strictEqual(selected, UNBUNDLED, "reports the picked icon");+ assert.true(+ hasSpriteSymbol(UNBUNDLED),+ "adds the picked icon so it still renders once closed"+ );+ });+});diff --git a/frontend/discourse/tests/integration/components/form-kit/controls/icon-test.gjs b/frontend/discourse/tests/integration/components/form-kit/controls/icon-test.gjsindex 9a814175b8e..4388c6ad149 100644--- a/frontend/discourse/tests/integration/components/form-kit/controls/icon-test.gjs+++ b/frontend/discourse/tests/integration/components/form-kit/controls/icon-test.gjs@@ -10,7 +10,10 @@ module("Integration | Component | FormKit | Controls | Icon", function (hooks) {hooks.beforeEach(function () {pretender.get("/svg-sprite/picker-search", () =>- response(200, [{ id: "pencil", name: "pencil" }])+ response(200, {+ icons: [{ id: "pencil", name: "pencil" }],+ has_more: false,+ }));});diff --git a/lib/svg_sprite.rb b/lib/svg_sprite.rbindex 92eb0c1a5a4..ac2a8879f14 100644--- a/lib/svg_sprite.rb+++ b/lib/svg_sprite.rb@@ -466,11 +466,30 @@ License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFLsvgs_for(SiteSetting.default_theme_id)[searched_icon.strip] || falseend- def self.icon_picker_search(keyword, only_available = false)- symbols = svgs_for(SiteSetting.default_theme_id)- symbols.slice!(*all_icons(SiteSetting.default_theme_id)) if only_available- symbols.reject! { |icon_id, _sym| !icon_id.include?(keyword) } if keyword.present?- symbols.sort_by(&:first).map { |id, symbol| { id:, symbol: } }+ def self.icon_picker_search(keyword, only_available, page:, per_page:, theme_id: nil)+ ids = picker_icon_ids(theme_id, only_available)+ ids = ids.lazy.select { |id| id.include?(keyword) } if keyword.present?+ ids = ids.drop(page * per_page).first(per_page + 1)++ has_more = ids.size > per_page+ ids = ids.take(per_page)++ missing = only_available ? [] : (ids - picker_icon_ids(theme_id, true)).to_set+ return { icons: ids.map { |id| { id: } }, has_more: } if missing.empty?++ custom = theme_id.present? ? custom_svgs(theme_id) : {}+ icons =+ ids.map { |id| missing.include?(id) ? { id:, symbol: custom[id] || core_svgs[id] } : { id: } }+ { icons:, has_more: }+ end++ def self.picker_icon_ids(theme_id, only_available)+ get_set_cache("picker_icon_ids_#{Theme.transform_ids(theme_id).join(",")}_#{only_available}") do+ symbols = svgs_for(theme_id)+ in_sprite = all_icons(theme_id).select { |id| symbols.key?(id) }++ only_available ? in_sprite : in_sprite + (symbols.keys - in_sprite).sort+ endend# For use in no_ember .html.erb layoutsdiff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/property-engine-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/property-engine-test.gjsindex f2e89f7f8ba..dbdbfd0a071 100644--- a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/property-engine-test.gjs+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/property-engine-test.gjs@@ -23,10 +23,13 @@ module("Integration | Component | workflows property engine", function (hooks) {hooks.beforeEach(function () {pretender.get("/svg-sprite/picker-search", () =>- response(200, [- { id: "gear", symbol: '<symbol id="gear"></symbol>' },- { id: "bolt", symbol: '<symbol id="bolt"></symbol>' },- ])+ response(200, {+ icons: [+ { id: "gear", symbol: '<symbol id="gear"></symbol>' },+ { id: "bolt", symbol: '<symbol id="bolt"></symbol>' },+ ],+ has_more: false,+ }));pretender.get("/admin/plugins/discourse-workflows/variables.json", () =>response(200, { variables: [] })diff --git a/spec/lib/svg_sprite/svg_sprite_spec.rb b/spec/lib/svg_sprite/svg_sprite_spec.rbindex b3971388e6f..c3ec10122d2 100644--- a/spec/lib/svg_sprite/svg_sprite_spec.rb+++ b/spec/lib/svg_sprite/svg_sprite_spec.rb@@ -96,6 +96,14 @@ RSpec.describe SvgSprite doexpect(SvgSprite.all_icons).not_to include(" fab fa-facebook-messenger ")end+ it "picks up a new badge icon in the picker list" do+ expect(SvgSprite.picker_icon_ids(nil, true)).not_to include("seedling")++ Fabricate(:badge, name: "Seedling Badge", icon: "seedling")++ expect(SvgSprite.picker_icon_ids(nil, true)).to include("seedling")+ end+it "includes icons from badges" doFabricate(:badge, name: "Custom Icon Badge", icon: "far fa-building")expect(SvgSprite.all_icons).to include("far fa-building")diff --git a/spec/requests/svg_sprite_controller_spec.rb b/spec/requests/svg_sprite_controller_spec.rbindex a004a3af151..e3e0b7e0b3a 100644--- a/spec/requests/svg_sprite_controller_spec.rb+++ b/spec/requests/svg_sprite_controller_spec.rb@@ -85,42 +85,120 @@ RSpec.describe SvgSpriteController doexpect(response.status).to eq(403)end- it "should work with no filter and max out at 500 results" do+ it "should work with no filter and return one page of results" dosign_in(user)get "/svg-sprite/picker-search"expect(response.status).to eq(200)- data = response.parsed_body- expect(data.length).to be <= 500- expect(data[0]["id"]).to eq("0")+ data = response.parsed_body["icons"]+ expect(data.length).to eq(SvgSpriteController::ICONS_PER_PAGE)+ expect(data[0]["id"]).to be_in(SvgSprite.all_icons)endit "should filter" dosign_in(user)- get "/svg-sprite/picker-search", params: { filter: "500px" }+ get "/svg-sprite/picker-search", params: { filter: "500px", only_available: "false" }expect(response.status).to eq(200)- data = response.parsed_body+ data = response.parsed_body["icons"]expect(data.length).to eq(1)expect(data[0]["id"]).to eq("fab-500px")+ expect(response.parsed_body["has_more"]).to eq(false)end- it "should display only available" do+ it "paginates and reports whether more pages exist" dosign_in(user)- get "/svg-sprite/picker-search"- data = response.parsed_body- beer_icon = response.parsed_body.find { |i| i["id"] == "beer-mug-empty" }+ get "/svg-sprite/picker-search", params: { only_available: "false" }+ first_page = response.parsed_body++ get "/svg-sprite/picker-search", params: { only_available: "false", page: 1 }+ second_page = response.parsed_body++ expect(first_page["icons"].length).to eq(SvgSpriteController::ICONS_PER_PAGE)+ expect(first_page["has_more"]).to eq(true)+ expect(second_page["icons"].length).to eq(SvgSpriteController::ICONS_PER_PAGE)+ expect(+ first_page["icons"].map { |i| i["id"] } & second_page["icons"].map { |i| i["id"] },+ ).to be_empty+ end++ it "returns an empty page past the last one" do+ sign_in(user)++ get "/svg-sprite/picker-search", params: { page: 999 }++ expect(response.status).to eq(200)+ expect(response.parsed_body).to eq("icons" => [], "has_more" => false)+ end++ it "rejects a negative, non-numeric, or absurdly large page" do+ sign_in(user)++ ["-1", "not-a-number", ["1"], "99999999999999999999999999"].each do |page|+ get "/svg-sprite/picker-search", params: { page: }++ expect(response.status).to eq(400)+ end+ end++ it "lists the icons in the sprite before the rest" do+ sign_in(user)++ get "/svg-sprite/picker-search", params: { only_available: "false" }++ available = SvgSprite.all_icons+ ids = response.parsed_body["icons"].map { |i| i["id"] }++ expect(ids.first).to be_in(available)+ expect(ids).to eq(ids.sort_by { |id| [available.include?(id) ? 0 : 1, id] })+ end++ it "keeps the restricted set when only_available is blank" do+ sign_in(user)++ get "/svg-sprite/picker-search", params: { only_available: "" }++ beer_icon = response.parsed_body["icons"].find { |i| i["id"] == "beer-mug-empty" }+ expect(beer_icon).to be nil+ end++ it "returns every icon when only_available is false" do+ sign_in(user)++ get "/svg-sprite/picker-search", params: { only_available: "false", filter: "beer" }++ beer_icon = response.parsed_body["icons"].find { |i| i["id"] == "beer-mug-empty" }expect(beer_icon).to be_present+ end++ it "revalidates with an etag until the sprite changes" do+ sign_in(user)++ get "/svg-sprite/picker-search"+ etag = response.headers["ETag"]+ expect(etag).to be_present++ get "/svg-sprite/picker-search", headers: { "HTTP_IF_NONE_MATCH" => etag }+ expect(response.status).to eq(304)++ Fabricate(:badge, name: "Seedling Badge", icon: "seedling")++ get "/svg-sprite/picker-search", headers: { "HTTP_IF_NONE_MATCH" => etag }+ expect(response.status).to eq(200)+ end++ it "should display only available" do+ sign_in(user)++ get "/svg-sprite/picker-search", params: { only_available: "true", filter: "beer" }+ expect(response.parsed_body["icons"]).to eq([])get "/svg-sprite/picker-search", params: { only_available: "true" }- data = response.parsed_body- beer_icon = response.parsed_body.find { |i| i["id"] == "beer-mug-empty" }- expect(beer_icon).to be nil- expect(data.length).to be > 0+ expect(response.parsed_body["icons"].length).to be > 0endenddiff --git a/spec/system/page_objects/components/d_icon_grid_picker.rb b/spec/system/page_objects/components/d_icon_grid_picker.rbindex 67a1d77b828..d10ddb1de0e 100644--- a/spec/system/page_objects/components/d_icon_grid_picker.rb+++ b/spec/system/page_objects/components/d_icon_grid_picker.rb@@ -13,6 +13,7 @@ module PageObjectsenddef select_icon(icon_id)+ filter(icon_id)find("[data-icon-id='#{icon_id}']").clickenddiff --git a/spec/system/page_objects/modals/sidebar_section_form.rb b/spec/system/page_objects/modals/sidebar_section_form.rbindex b2878d5e6ee..6b0fba15ffe 100644--- a/spec/system/page_objects/modals/sidebar_section_form.rb+++ b/spec/system/page_objects/modals/sidebar_section_form.rb@@ -12,7 +12,6 @@ module PageObjectsfill_in("link-url", with: url, match: :first)icon_picker = first_link_icon_pickericon_picker.expand- icon_picker.filter(icon)icon_picker.select_icon(icon)end@@ -26,7 +25,6 @@ module PageObjectsicon_picker = PageObjects::Components::DIconGridPicker.new(link_row)icon_picker.expand- icon_picker.filter(icon)icon_picker.select_icon(icon)endenddiff --git a/spec/system/page_objects/pages/admin_badges.rb b/spec/system/page_objects/pages/admin_badges.rbindex 301be9d348f..7e559a1a32e 100644--- a/spec/system/page_objects/pages/admin_badges.rb+++ b/spec/system/page_objects/pages/admin_badges.rb@@ -54,7 +54,7 @@ module PageObjectsdef choose_icon(name)form.choose_conditional("choose-icon")- form.field("icon").select("truck-medical")+ form.field("icon").select(name)selfend