A platform for community discussion. Free, open, simple.
UX: Indicate when the emoji picker category list is scrollable (#41858)
Renato Atiliof6dcbc61408f
diff --git a/app/assets/stylesheets/common/components/_index.scss b/app/assets/stylesheets/common/components/_index.scssindex dd86f0cf2b2..a2812432b0e 100644--- a/app/assets/stylesheets/common/components/_index.scss+++ b/app/assets/stylesheets/common/components/_index.scss@@ -42,6 +42,7 @@@import "hashtag";@import "header-search";@import "horizontal-overflow-nav";+@import "d-overflow-controls";@import "iframed-html";@import "ignored-user-list";@import "keyboard_shortcuts";diff --git a/app/assets/stylesheets/common/components/d-overflow-controls.scss b/app/assets/stylesheets/common/components/d-overflow-controls.scssnew file mode 100644index 00000000000..d050f48641d--- /dev/null+++ b/app/assets/stylesheets/common/components/d-overflow-controls.scss@@ -0,0 +1,127 @@+.d-overflow-controls {+ --fade-width: 2rem;+ --fade-color: var(--secondary);+ position: relative;+ min-width: 0;+ min-height: 0;++ &__content {+ scrollbar-width: none;+ -ms-overflow-style: none;++ // keep scroll-into-view targets clear of the edge fade/chevron buttons+ scroll-padding: var(--fade-width);++ &::-webkit-scrollbar {+ display: none;+ }+ }++ &__btn {+ position: absolute;+ z-index: 2;+ background: var(--fade-color);+ border: none;+ display: flex;+ align-items: center;+ justify-content: center;+ cursor: pointer;+ color: var(--primary-high);++ &:hover {+ color: var(--primary);+ }++ &.--left,+ &.--right {+ top: 0;+ bottom: 0;+ margin-block: 1px;+ padding: 0 var(--space-1);+ }++ &.--up,+ &.--down {+ left: 0;+ right: 0;+ margin-inline: 1px;+ padding: var(--space-1) 0;+ }++ &.--left {+ /*! rtl:ignore */+ left: 0;++ &::after {+ content: "";+ position: absolute;++ /*! rtl:ignore */+ left: 100%;+ height: 100%;+ width: var(--fade-width);++ /*! rtl:ignore */+ background: linear-gradient(to right, var(--fade-color), transparent);+ pointer-events: none;+ }++ // Undo automatic icon flip since button stays in physical position+ .rtl & .d-icon {+ transform: scaleX(1);+ }+ }++ &.--right {+ /*! rtl:ignore */+ right: 0;++ &::before {+ content: "";+ position: absolute;++ /*! rtl:ignore */+ right: 100%;+ height: 100%;+ width: var(--fade-width);++ /*! rtl:ignore */+ background: linear-gradient(to left, var(--fade-color), transparent);+ pointer-events: none;+ }++ // Undo automatic icon flip since button stays in physical position+ .rtl & .d-icon {+ transform: scaleX(1);+ }+ }++ &.--up {+ top: 0;++ &::after {+ content: "";+ position: absolute;+ top: 100%;+ width: 100%;+ height: var(--fade-width);+ background: linear-gradient(to bottom, var(--fade-color), transparent);+ pointer-events: none;+ }+ }++ &.--down {+ bottom: 0;++ &::before {+ content: "";+ position: absolute;+ bottom: 100%;+ width: 100%;+ height: var(--fade-width);+ background: linear-gradient(to top, var(--fade-color), transparent);+ pointer-events: none;+ }+ }+ }+}diff --git a/app/assets/stylesheets/common/components/emoji-picker.scss b/app/assets/stylesheets/common/components/emoji-picker.scssindex 185cb4ac7de..5ebdf9534e1 100644--- a/app/assets/stylesheets/common/components/emoji-picker.scss+++ b/app/assets/stylesheets/common/components/emoji-picker.scss@@ -125,6 +125,16 @@padding: 2em;}+ &__sections-nav-wrap {+ --fade-color: var(--primary-low);+ flex: 0 0 auto;++ @include viewport.until(sm) {+ order: 1;+ width: 100%;+ }+ }+&__sections-nav {display: flex;flex-direction: column;@@ -138,7 +148,6 @@overscroll-behavior: contain;@include viewport.until(sm) {- order: 1;height: 50px;width: 100%;flex-direction: row;diff --git a/app/assets/stylesheets/common/d-editor.scss b/app/assets/stylesheets/common/d-editor.scssindex 9c009e34d11..a629cf4fa04 100644--- a/app/assets/stylesheets/common/d-editor.scss+++ b/app/assets/stylesheets/common/d-editor.scss@@ -323,75 +323,6 @@border-start-end-radius: inherit;}-.d-editor-button-bar__scroll-btn {- --fade-width: 2rem;- --fade-color: var(--secondary);- position: absolute;- top: 0;- bottom: 0;- z-index: 2;- background: var(--fade-color);- border: none;- margin-block: 1px;- display: flex;- align-items: center;- cursor: pointer;- color: var(--primary-high);- padding: 0 var(--space-1);-- &:hover {- color: var(--primary);- }-- &.--left {- /*! rtl:ignore */- left: 0;-- &::after {- content: "";- position: absolute;-- /*! rtl:ignore */- left: 100%;- height: 100%;- width: var(--fade-width);-- /*! rtl:ignore */- background: linear-gradient(to right, var(--fade-color), transparent);- pointer-events: none;- }-- // Undo automatic icon flip since button stays in physical position- .rtl & .d-icon {- transform: scaleX(1);- }- }-- &.--right {- /*! rtl:ignore */- right: 0;-- &::before {- content: "";- position: absolute;-- /*! rtl:ignore */- right: 100%;- height: 100%;- width: var(--fade-width);-- /*! rtl:ignore */- background: linear-gradient(to left, var(--fade-color), transparent);- pointer-events: none;- }-- // Undo automatic icon flip since button stays in physical position- .rtl & .d-icon {- transform: scaleX(1);- }- }-}-.d-editor-button-bar {display: flex;flex-direction: row;diff --git a/frontend/discourse/app/components/composer/toolbar-scroll-container.gjs b/frontend/discourse/app/components/composer/toolbar-scroll-container.gjsdeleted file mode 100644index 1d303c559f4..00000000000--- a/frontend/discourse/app/components/composer/toolbar-scroll-container.gjs+++ /dev/null@@ -1,111 +0,0 @@-import Component from "@glimmer/component";-import { tracked } from "@glimmer/tracking";-import { on } from "@ember/modifier";-import { action } from "@ember/object";-import didInsert from "@ember/render-modifiers/modifiers/did-insert";-import { bind } from "discourse/lib/decorators";-import { isDocumentRTL } from "discourse/lib/text-direction";-import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";-import dIcon from "discourse/ui-kit/helpers/d-icon";-import dOnResize from "discourse/ui-kit/modifiers/d-on-resize";--export default class ToolbarScrollContainer extends Component {- @tracked hasLeftScroll = false;- @tracked hasRightScroll = false;- scrollable = null;-- @action- setup(element) {- this.scrollable = element;- this.checkScroll(element);- }-- @bind- onResize(entries) {- this.checkScroll(entries[0].target);- }-- @action- onScroll(event) {- this.checkScroll(event.target);- }-- checkScroll(element) {- const { scrollWidth, scrollLeft, offsetWidth } = element;- const hasOverflow = scrollWidth > offsetWidth;- const canScrollBack = hasOverflow && Math.abs(scrollLeft) > 2;- const canScrollForward =- hasOverflow && scrollWidth - Math.abs(scrollLeft) - offsetWidth > 2;-- // Buttons stay in physical positions (rtl:ignore in CSS), but in RTL- // the scroll direction is reversed, so swap which button shows- if (isDocumentRTL()) {- this.hasLeftScroll = canScrollForward;- this.hasRightScroll = canScrollBack;- } else {- this.hasLeftScroll = canScrollBack;- this.hasRightScroll = canScrollForward;- }- }-- @action- scrollLeft() {- this.scrollable?.scrollBy({- left: -this.scrollable.offsetWidth,- behavior: "smooth",- });- }-- @action- scrollRight() {- this.scrollable?.scrollBy({- left: this.scrollable.offsetWidth,- behavior: "smooth",- });- }-- @action- preventFocusGrab(event) {- event.preventDefault();- }-- <template>- <div class="d-editor-button-bar__wrap">- {{#if this.hasLeftScroll}}- {{! eslint-disable ember/template-no-pointer-down-event-binding }}- <button- type="button"- class="d-editor-button-bar__scroll-btn --left"- tabindex="-1"- {{on "mousedown" this.preventFocusGrab}}- {{on "click" this.scrollLeft}}- >- {{dIcon "chevron-left"}}- </button>- {{/if}}-- <div- class={{dConcatClass "d-editor-button-bar" @class}}- role="toolbar"- {{didInsert this.setup}}- {{dOnResize this.onResize}}- {{on "scroll" this.onScroll}}- >- {{yield}}- </div>-- {{#if this.hasRightScroll}}- {{! eslint-disable ember/template-no-pointer-down-event-binding }}- <button- type="button"- class="d-editor-button-bar__scroll-btn --right"- tabindex="-1"- {{on "mousedown" this.preventFocusGrab}}- {{on "click" this.scrollRight}}- >- {{dIcon "chevron-right"}}- </button>- {{/if}}- </div>- </template>-}diff --git a/frontend/discourse/app/components/emoji-picker/content.gjs b/frontend/discourse/app/components/emoji-picker/content.gjsindex c93fb76bc2d..edc68831819 100644--- a/frontend/discourse/app/components/emoji-picker/content.gjs+++ b/frontend/discourse/app/components/emoji-picker/content.gjs@@ -27,6 +27,7 @@ import preventScrollOnFocus from "discourse/modifiers/prevent-scroll-on-focus";import { eq, gt, includes, notEq } from "discourse/truth-helpers";import DButton from "discourse/ui-kit/d-button";import DFilterInput from "discourse/ui-kit/d-filter-input";+import DOverflowControls from "discourse/ui-kit/d-overflow-controls";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import dReplaceEmoji from "discourse/ui-kit/helpers/d-replace-emoji";import dAutoFocus from "discourse/ui-kit/modifiers/d-auto-focus";@@ -339,24 +340,45 @@ export default class EmojiPicker extends Component {this.lastVisibleSection = section;next(() => {- schedule("afterRender", () => {- const targetSection = document.querySelector(- `.emoji-picker__section[data-section="${section}"]`- );-- if (targetSection && this.scrollableNode) {- const titleContainer = targetSection.querySelector(- ".emoji-picker__section-title-container"- );- const titleHeight = titleContainer?.offsetHeight ?? 0;- this.scrollableNode.scrollTop = targetSection.offsetTop - titleHeight;- }-- this.scrollObserverEnabled = true;- });+ schedule("afterRender", () => this._scrollToSection(section));});}+ // re-enables the scroll observer only once the final scroll has happened, so+ // the expand-and-retry path below doesn't let it re-detect a section mid-jump+ _scrollToSection(section) {+ const targetSection = document.querySelector(+ `.emoji-picker__section[data-section="${section}"]`+ );++ if (!targetSection || !this.scrollableNode) {+ this.scrollObserverEnabled = true;+ return;+ }++ const node = this.scrollableNode;+ const titleHeight =+ targetSection.querySelector(".emoji-picker__section-title-container")+ ?.offsetHeight ?? 0;+ const desiredScrollTop = targetSection.offsetTop - titleHeight;+ const maxScrollTop = node.scrollHeight - node.clientHeight;++ // when the sections below the target don't fill the panel, the target can't+ // reach the top and the jump lands in empty space; expand the remaining+ // sections so real content fills it, then scroll once they've rendered+ if (+ desiredScrollTop > maxScrollTop &&+ this.visibleSections.length < Object.keys(this.groups).length+ ) {+ this.addVisibleSections(Object.keys(this.groups));+ schedule("afterRender", () => this._scrollToSection(section));+ return;+ }++ node.scrollTop = Math.min(desiredScrollTop, maxScrollTop);+ this.scrollObserverEnabled = true;+ }+@actionasync loadEmojis() {if (this.emojiStore.list) {@@ -404,12 +426,18 @@ export default class EmojiPicker extends Component {this.lastVisibleSection = sectionElement.dataset.section;this.addVisibleSections(visibleSections.map((s) => s.dataset.section));- document- .querySelector(".emoji-picker__section-btn.active")- ?.scrollIntoView({- block: "nearest",- inline: "start",- });+ // target the button by section rather than `.active`, which only updates+ // on the next render and would leave us scrolling the previous one+ const navButton = document.querySelector(+ `.emoji-picker__section-btn[data-section="${this.lastVisibleSection}"]`+ );++ if (navButton) {+ navButton.scrollIntoView({ block: "nearest", inline: "start" });+ // scrollIntoView doesn't emit a scroll event, so nudge the surrounding+ // scroll container to refresh its scroll indicators+ navButton.parentElement?.dispatchEvent(new Event("scroll"));+ }}}@@ -437,9 +465,8 @@ export default class EmojiPicker extends Component {for (const sectionNode of document.querySelectorAll(".emoji-picker__section")) {- const sectionName = sectionNode.dataset.section;sections.push(sectionNode.dataset.section);- if (sectionName === section) {+ if (sectionNode.dataset.section === section) {break;}}@@ -493,7 +520,11 @@ export default class EmojiPicker extends Component {</div><div class="emoji-picker__content">- <div class="emoji-picker__sections-nav" {{this.setupSectionsNavScroll}}>+ <DOverflowControls+ @wrapperClass="emoji-picker__sections-nav-wrap"+ @class="emoji-picker__sections-nav"+ {{this.setupSectionsNavScroll}}+ >{{#each-in this.groups as |section emojis|}}{{#if emojis.length}}<DButton@@ -522,7 +553,7 @@ export default class EmojiPicker extends Component {</DButton>{{/if}}{{/each-in}}- </div>+ </DOverflowControls>{{#if this.emojiStore.list}}<div class="emoji-picker__scrollable-content" {{this.scrollListener}}>diff --git a/frontend/discourse/app/ui-kit/d-editor.gjs b/frontend/discourse/app/ui-kit/d-editor.gjsindex 0af9238bca1..dd1739067f3 100644--- a/frontend/discourse/app/ui-kit/d-editor.gjs+++ b/frontend/discourse/app/ui-kit/d-editor.gjs@@ -16,7 +16,6 @@ import { Promise } from "rsvp";import TextareaEditor from "discourse/components/composer/textarea-editor";import ToggleSwitch from "discourse/components/composer/toggle-switch";import ToolbarButtons from "discourse/components/composer/toolbar-buttons";-import ToolbarScrollContainer from "discourse/components/composer/toolbar-scroll-container";import DEditorPreview from "discourse/components/d-editor-preview";import EmojiAutocompleteResults from "discourse/components/emoji-autocomplete-results";import EmojiPickerDetached from "discourse/components/emoji-picker/detached";@@ -45,6 +44,7 @@ import { not } from "discourse/truth-helpers";import DButton from "discourse/ui-kit/d-button";import DConditionalInElement from "discourse/ui-kit/d-conditional-in-element";import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";+import DOverflowControls from "discourse/ui-kit/d-overflow-controls";import DPopupInputTip from "discourse/ui-kit/d-popup-input-tip";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import {@@ -794,11 +794,15 @@ export default class DEditor extends Component {@append={{true}}>{{#if this.replacedToolbarInstance}}- <ToolbarScrollContainer+ <DOverflowControls+ @wrapperClass="d-editor-button-bar__wrap"@class={{dConcatClass+ "d-editor-button-bar""--replaced-toolbar"(if this.disabled "--disabled")}}+ @buttonClass="d-editor-button-bar__scroll-btn"+ role="toolbar"><DButton@action={{this.resetToolbar}}@@ -812,9 +816,17 @@ export default class DEditor extends Component {@rovingButtonBar={{this.rovingButtonBar}}@isFirst={{false}}/>- </ToolbarScrollContainer>+ </DOverflowControls>{{else}}- <ToolbarScrollContainer @class={{if this.disabled "--disabled"}}>+ <DOverflowControls+ @wrapperClass="d-editor-button-bar__wrap"+ @class={{dConcatClass+ "d-editor-button-bar"+ (if this.disabled "--disabled")+ }}+ @buttonClass="d-editor-button-bar__scroll-btn"+ role="toolbar"+ >{{#if this.showEditorModeToggle}}<ToggleSwitch@preventFocus={{true}}@@ -824,13 +836,12 @@ export default class DEditor extends Component {{{on "keydown" this.rovingButtonBar}}/>{{/if}}-<ToolbarButtons@data={{this.toolbar}}@rovingButtonBar={{this.rovingButtonBar}}@isFirst={{not this.siteSettings.rich_editor}}/>- </ToolbarScrollContainer>+ </DOverflowControls>{{/if}}</DConditionalInElement>diff --git a/frontend/discourse/app/ui-kit/d-overflow-controls.gts b/frontend/discourse/app/ui-kit/d-overflow-controls.gtsnew file mode 100644index 00000000000..6e282a3268f--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-overflow-controls.gts@@ -0,0 +1,225 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { registerDestructor } from "@ember/destroyable";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import didInsert from "@ember/render-modifiers/modifiers/did-insert";+import { bind } from "discourse/lib/decorators";+import { isDocumentRTL } from "discourse/lib/text-direction";+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";+import dIcon from "discourse/ui-kit/helpers/d-icon";+import dOnResize from "discourse/ui-kit/modifiers/d-on-resize";++interface DOverflowControlsSignature {+ Args: {+ /** Extra class(es) added to the outer wrapper element. */+ wrapperClass?: string;+ /** Extra class(es) added to the scrollable content element. */+ class?: string;+ /** Extra class(es) added to each edge scroll button. */+ buttonClass?: string;+ };++ Element: HTMLDivElement;++ Blocks: {+ default: [];+ };+}++/**+ * Wraps scrollable content and shows chevron + gradient-fade buttons on whichever+ * edges can still be scrolled. Works on both axes: a horizontally-overflowing+ * child gets left/right buttons, a vertically-overflowing one gets up/down. State+ * is recomputed on insert, resize, and scroll.+ *+ * Consumers can theme the buttons with the `--fade-color` and `--fade-width` CSS+ * custom properties, and augment the generated classes via `@wrapperClass`,+ * `@class` (scrollable content) and `@buttonClass`. Any `...attributes` land on+ * the scrollable content element.+ */+export default class DOverflowControls extends Component<DOverflowControlsSignature> {+ @tracked hasTopScroll = false;+ @tracked hasBottomScroll = false;+ @tracked hasLeftScroll = false;+ @tracked hasRightScroll = false;++ #scrollable: HTMLElement | null = null;+ #canScrollX = false;+ #canScrollY = false;+ #mutationObserver?: MutationObserver;++ @action+ setup(element: HTMLElement) {+ this.#scrollable = element;+ this.#refreshScrollableAxes(element);+ this.#checkScroll(element);++ // content added/removed (e.g. async-loaded items) changes overflow without+ // resizing the scroll box, which a ResizeObserver wouldn't catch+ this.#mutationObserver = new MutationObserver(() =>+ this.#checkScroll(element)+ );+ this.#mutationObserver.observe(element, { childList: true });+ registerDestructor(this, () => this.#mutationObserver?.disconnect());+ }++ @bind+ onResize(entries: ResizeObserverEntry[]) {+ // overflow can flip axis at a breakpoint, so re-read it on resize+ const element = entries[0].target as HTMLElement;+ this.#refreshScrollableAxes(element);+ this.#checkScroll(element);+ }++ @action+ onScroll(event: Event) {+ this.#checkScroll(event.target as HTMLElement);+ }++ @action+ scrollLeft() {+ this.#scrollByViewport(-1, 0);+ }++ @action+ scrollRight() {+ this.#scrollByViewport(1, 0);+ }++ @action+ scrollUp() {+ this.#scrollByViewport(0, -1);+ }++ @action+ scrollDown() {+ this.#scrollByViewport(0, 1);+ }++ @action+ preventFocusGrab(event: MouseEvent) {+ event.preventDefault();+ }++ #refreshScrollableAxes(element: HTMLElement) {+ const { overflowX, overflowY } = getComputedStyle(element);+ this.#canScrollX = overflowX === "auto" || overflowX === "scroll";+ this.#canScrollY = overflowY === "auto" || overflowY === "scroll";+ }++ #checkScroll(element: HTMLElement) {+ const {+ scrollWidth,+ scrollLeft,+ offsetWidth,+ scrollHeight,+ scrollTop,+ offsetHeight,+ } = element;++ const hasHorizontalOverflow = this.#canScrollX && scrollWidth > offsetWidth;+ const canScrollBack = hasHorizontalOverflow && Math.abs(scrollLeft) > 2;+ const canScrollForward =+ hasHorizontalOverflow &&+ scrollWidth - Math.abs(scrollLeft) - offsetWidth > 2;++ // Buttons stay in physical positions (rtl:ignore in CSS), but in RTL+ // the scroll direction is reversed, so swap which button shows+ if (isDocumentRTL()) {+ this.hasLeftScroll = canScrollForward;+ this.hasRightScroll = canScrollBack;+ } else {+ this.hasLeftScroll = canScrollBack;+ this.hasRightScroll = canScrollForward;+ }++ const hasVerticalOverflow = this.#canScrollY && scrollHeight > offsetHeight;+ this.hasTopScroll = hasVerticalOverflow && scrollTop > 2;+ this.hasBottomScroll =+ hasVerticalOverflow && scrollHeight - scrollTop - offsetHeight > 2;+ }++ #scrollByViewport(dx: number, dy: number) {+ const element = this.#scrollable;+ if (!element) {+ return;+ }++ element.scrollBy({+ left: dx * element.offsetWidth,+ top: dy * element.offsetHeight,+ behavior: "smooth",+ });+ }++ <template>+ <div class={{dConcatClass "d-overflow-controls" @wrapperClass}}>+ {{#if this.hasTopScroll}}+ {{! eslint-disable ember/template-no-pointer-down-event-binding }}+ <button+ type="button"+ aria-hidden="true"+ class={{dConcatClass "d-overflow-controls__btn --up" @buttonClass}}+ tabindex="-1"+ {{on "mousedown" this.preventFocusGrab}}+ {{on "click" this.scrollUp}}+ >+ {{dIcon "chevron-up"}}+ </button>+ {{/if}}++ {{#if this.hasLeftScroll}}+ {{! eslint-disable ember/template-no-pointer-down-event-binding }}+ <button+ type="button"+ aria-hidden="true"+ class={{dConcatClass "d-overflow-controls__btn --left" @buttonClass}}+ tabindex="-1"+ {{on "mousedown" this.preventFocusGrab}}+ {{on "click" this.scrollLeft}}+ >+ {{dIcon "chevron-left"}}+ </button>+ {{/if}}++ <div+ class={{dConcatClass "d-overflow-controls__content" @class}}+ {{didInsert this.setup}}+ {{dOnResize this.onResize}}+ {{on "scroll" this.onScroll}}+ ...attributes+ >+ {{yield}}+ </div>++ {{#if this.hasRightScroll}}+ {{! eslint-disable ember/template-no-pointer-down-event-binding }}+ <button+ type="button"+ aria-hidden="true"+ class={{dConcatClass "d-overflow-controls__btn --right" @buttonClass}}+ tabindex="-1"+ {{on "mousedown" this.preventFocusGrab}}+ {{on "click" this.scrollRight}}+ >+ {{dIcon "chevron-right"}}+ </button>+ {{/if}}++ {{#if this.hasBottomScroll}}+ {{! eslint-disable ember/template-no-pointer-down-event-binding }}+ <button+ type="button"+ aria-hidden="true"+ class={{dConcatClass "d-overflow-controls__btn --down" @buttonClass}}+ tabindex="-1"+ {{on "mousedown" this.preventFocusGrab}}+ {{on "click" this.scrollDown}}+ >+ {{dIcon "chevron-down"}}+ </button>+ {{/if}}+ </div>+ </template>+}diff --git a/frontend/discourse/app/ui-kit/modifiers/d-on-resize.js b/frontend/discourse/app/ui-kit/modifiers/d-on-resize.jsdeleted file mode 100644index 2d4e1ff60b0..00000000000--- a/frontend/discourse/app/ui-kit/modifiers/d-on-resize.js+++ /dev/null@@ -1,29 +0,0 @@-import { registerDestructor } from "@ember/destroyable";-import { cancel, throttle } from "@ember/runloop";-import Modifier from "ember-modifier";--export default class DOnResize extends Modifier {- constructor(owner, args) {- super(owner, args);- registerDestructor(this, (instance) => instance.cleanup());- }-- modify(element, [fn, options = {}]) {- this.resizeObserver = new ResizeObserver((entries) => {- this.throttleHandler = throttle(- this,- fn,- entries,- options.delay ?? 0,- options.immediate ?? false- );- });-- this.resizeObserver.observe(element);- }-- cleanup() {- cancel(this.throttleHandler);- this.resizeObserver?.disconnect();- }-}diff --git a/frontend/discourse/app/ui-kit/modifiers/d-on-resize.ts b/frontend/discourse/app/ui-kit/modifiers/d-on-resize.tsnew file mode 100644index 00000000000..9b38eed7f69--- /dev/null+++ b/frontend/discourse/app/ui-kit/modifiers/d-on-resize.ts@@ -0,0 +1,56 @@+import { registerDestructor } from "@ember/destroyable";+import type Owner from "@ember/owner";+import { cancel, throttle } from "@ember/runloop";+import Modifier, { type ArgsFor } from "ember-modifier";++interface DOnResizeOptions {+ /** Throttle interval in ms. Defaults to `0`. */+ delay?: number;+ /** Whether to also invoke on the leading edge. Defaults to `false`. */+ immediate?: boolean;+}++type DOnResizeCallback = (entries: ResizeObserverEntry[]) => void;++interface DOnResizeSignature {+ Element: Element;+ Args: {+ Positional: [callback: DOnResizeCallback, options?: DOnResizeOptions];+ };+}++/**+ * Calls `callback` with the observed `ResizeObserverEntry`s whenever the element+ * resizes, throttled through the runloop. Cleans up the observer on teardown.+ */+export default class DOnResize extends Modifier<DOnResizeSignature> {+ #resizeObserver?: ResizeObserver;+ #throttleHandler?: ReturnType<typeof throttle>;++ constructor(owner: Owner, args: ArgsFor<DOnResizeSignature>) {+ super(owner, args);+ registerDestructor(this, () => this.#cleanup());+ }++ modify(+ element: Element,+ [fn, options = {}]: DOnResizeSignature["Args"]["Positional"]+ ) {+ this.#resizeObserver = new ResizeObserver((entries) => {+ this.#throttleHandler = throttle(+ this,+ fn,+ entries,+ options.delay ?? 0,+ options.immediate ?? false+ );+ });++ this.#resizeObserver.observe(element);+ }++ #cleanup() {+ cancel(this.#throttleHandler);+ this.#resizeObserver?.disconnect();+ }+}diff --git a/frontend/discourse/tests/integration/ui-kit/d-overflow-controls-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-overflow-controls-test.gjsnew file mode 100644index 00000000000..33cbbdd5d4c--- /dev/null+++ b/frontend/discourse/tests/integration/ui-kit/d-overflow-controls-test.gjs@@ -0,0 +1,127 @@+import { render, triggerEvent } from "@ember/test-helpers";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import DOverflowControls from "discourse/ui-kit/d-overflow-controls";++async function scrollTo(selector, props) {+ const element = document.querySelector(selector);+ Object.assign(element, props);+ await triggerEvent(element, "scroll");+}++module("Integration | ui-kit | DOverflowControls", function (hooks) {+ setupRenderingTest(hooks);++ test("no buttons when content fits", async function (assert) {+ await render(+ <template>+ <DOverflowControls style="width: 200px; overflow: auto">+ <div style="width: 50px; height: 20px"></div>+ </DOverflowControls>+ </template>+ );++ assert.dom(".d-overflow-controls__btn").doesNotExist();+ });++ test("no buttons when the overflowing axis is not scrollable", async function (assert) {+ await render(+ <template>+ {{! content overflows horizontally but the axis is clipped, not scrollable }}+ <DOverflowControls style="width: 100px; overflow: hidden">+ <div style="width: 500px; height: 20px"></div>+ </DOverflowControls>+ </template>+ );++ assert.dom(".d-overflow-controls__btn").doesNotExist();+ });++ test("horizontal overflow shows the trailing button, then the leading one", async function (assert) {+ await render(+ <template>+ <DOverflowControls style="width: 100px; overflow-x: auto">+ <div style="width: 500px; height: 20px"></div>+ </DOverflowControls>+ </template>+ );++ assert+ .dom(".d-overflow-controls__btn.--right")+ .exists("shows the scroll-right button at the start");+ assert+ .dom(".d-overflow-controls__btn.--left")+ .doesNotExist("hides the scroll-left button at the start");++ const content = document.querySelector(".d-overflow-controls__content");+ await scrollTo(".d-overflow-controls__content", {+ scrollLeft: content.scrollWidth,+ });++ assert+ .dom(".d-overflow-controls__btn.--left")+ .exists("shows the scroll-left button at the end");+ assert+ .dom(".d-overflow-controls__btn.--right")+ .doesNotExist("hides the scroll-right button at the end");+ });++ test("vertical overflow shows the bottom button, then the top one", async function (assert) {+ await render(+ <template>+ <DOverflowControls style="height: 100px; overflow-y: auto">+ <div style="height: 500px; width: 20px"></div>+ </DOverflowControls>+ </template>+ );++ assert+ .dom(".d-overflow-controls__btn.--down")+ .exists("shows the scroll-down button at the top");+ assert+ .dom(".d-overflow-controls__btn.--up")+ .doesNotExist("hides the scroll-up button at the top");++ const content = document.querySelector(".d-overflow-controls__content");+ await scrollTo(".d-overflow-controls__content", {+ scrollTop: content.scrollHeight,+ });++ assert+ .dom(".d-overflow-controls__btn.--up")+ .exists("shows the scroll-up button at the bottom");+ assert+ .dom(".d-overflow-controls__btn.--down")+ .doesNotExist("hides the scroll-down button at the bottom");+ });++ test("applies consumer classes and attributes", async function (assert) {+ await render(+ <template>+ <DOverflowControls+ @wrapperClass="my-wrap"+ @class="my-content"+ @buttonClass="my-btn"+ style="width: 100px; overflow-x: auto"+ data-test="yes"+ >+ <div style="width: 500px; height: 20px"></div>+ </DOverflowControls>+ </template>+ );++ assert+ .dom(".d-overflow-controls.my-wrap")+ .exists("wrapper gets @wrapperClass");+ assert+ .dom(".d-overflow-controls__content.my-content")+ .hasAttribute(+ "data-test",+ "yes",+ "content gets @class and ...attributes"+ );+ assert+ .dom(".d-overflow-controls__btn.my-btn")+ .exists("buttons get @buttonClass");+ });+});