Skip to content

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

DEV: Migrate composer and Ace resizing to shared separator (#42591)

Sérgio Saquetime02b2a6094a0
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 78e7e999110..9e95411385a 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -1,5 +1,7 @@
en:
js:
+ ace_editor:
+ resize: "Resize code editor"
user_api_key:
title: 'Authorize "%{application_name}"'
authorize: "Authorize"
diff --git a/docs/developer-guides/docs/03-code-internals/22-app-events-triggers.md b/docs/developer-guides/docs/03-code-internals/22-app-events-triggers.md
index aa40961e918..77a8d4c9cf8 100644
--- a/docs/developer-guides/docs/03-code-internals/22-app-events-triggers.md
+++ b/docs/developer-guides/docs/03-code-internals/22-app-events-triggers.md
@@ -314,7 +314,7 @@ No arguments passed to this event.
| 1 | objectArg1 | object | True | - |
| - | objectArg1.postId | property | True | - |
-#### composer:div-resizing [:link:](https://github.com/discourse/discourse/blob/main/frontend/discourse/app/components/composer-container.gjs#L55)
+#### composer:div-resizing [:link:](https://github.com/discourse/discourse/blob/main/frontend/discourse/app/components/composer-container.gjs#L259)
No arguments passed to this event.
@@ -414,11 +414,11 @@ No arguments passed to this event.
</details>
-#### composer:resize-ended [:link:](https://github.com/discourse/discourse/blob/main/frontend/discourse/app/components/composer-container.gjs#L66)
+#### composer:resize-ended [:link:](https://github.com/discourse/discourse/blob/main/frontend/discourse/app/components/composer-container.gjs#L280)
No arguments passed to this event.
-#### composer:resize-started [:link:](https://github.com/discourse/discourse/blob/main/frontend/discourse/app/components/composer-container.gjs#L51)
+#### composer:resize-started [:link:](https://github.com/discourse/discourse/blob/main/frontend/discourse/app/components/composer-container.gjs#L254)
No arguments passed to this event.
@@ -432,7 +432,7 @@ No arguments passed to this event.
No arguments passed to this event.
-##### /frontend/discourse/app/components/composer-container.gjs#72 [:link:](https://github.com/discourse/discourse/blob/main/frontend/discourse/app/components/composer-container.gjs#L72)
+##### /frontend/discourse/app/components/composer-container.gjs#296 [:link:](https://github.com/discourse/discourse/blob/main/frontend/discourse/app/components/composer-container.gjs#L296)
No arguments passed to this event.
diff --git a/frontend/discourse/app/components/ace-editor.gjs b/frontend/discourse/app/components/ace-editor.gjs
index a6bede8b237..2edfddf9dd8 100644
--- a/frontend/discourse/app/components/ace-editor.gjs
+++ b/frontend/discourse/app/components/ace-editor.gjs
@@ -1,6 +1,5 @@
import Component from "@glimmer/component";
import { tracked } from "@glimmer/tracking";
-import { hash } from "@ember/helper";
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
import didUpdate from "@ember/render-modifiers/modifiers/did-update";
import { service } from "@ember/service";
@@ -9,8 +8,8 @@ import { modifier } from "ember-modifier";
import { bind } from "discourse/lib/decorators";
import { isTesting } from "discourse/lib/environment";
import loadAce from "discourse/lib/load-ace-editor";
-import grippieDragResize from "discourse/modifiers/grippie-drag-resize";
import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";
+import DResizeSeparator from "discourse/ui-kit/d-resize-separator";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
import { i18n } from "discourse-i18n";
@@ -63,6 +62,9 @@ export default class AceEditor extends Component {
@service appEvents;
@tracked isLoading = true;
+
+ /** The resized box, handed to the separator once the editor has built it. */
+ @tracked editorContainer = null;
editor = null;
ace = null;
skipChangePropagation = false;
@@ -153,6 +155,7 @@ export default class AceEditor extends Component {
this.editor.on("blur", () => this.warnSCSSDeprecations());
+ this.editorContainer = this.editor.container;
this.editor.$blockScrolling = Infinity;
this.editor.renderer.setScrollMargin(10, 10);
@@ -270,7 +273,13 @@ export default class AceEditor extends Component {
@bind
onResizeDrag(size) {
- this.editor.container.style.height = `${size}px`;
+ this.editorContainer.classList.add("clear-transitions");
+ this.editorContainer.style.height = `${size}px`;
+ }
+
+ @bind
+ onResizeEnd() {
+ this.editorContainer.classList.remove("clear-transitions");
}
<template>
@@ -288,14 +297,15 @@ export default class AceEditor extends Component {
>
</div>
{{#if @resizable}}
- <div
+ <DResizeSeparator
class="grippie"
- {{grippieDragResize
- ".ace_editor--resizable"
- "bottom"
- (hash onThrottledDrag=this.onResizeDrag)
- }}
- ></div>
+ @axis="vertical"
+ @side="start"
+ @measure={{this.editorContainer}}
+ @label={{i18n "ace_editor.resize"}}
+ @onResize={{this.onResizeDrag}}
+ @onResizeEnd={{this.onResizeEnd}}
+ />
{{/if}}
</DConditionalLoadingSpinner>
</div>
diff --git a/frontend/discourse/app/components/composer-container.gjs b/frontend/discourse/app/components/composer-container.gjs
index ab320a88637..8fcc489415b 100644
--- a/frontend/discourse/app/components/composer-container.gjs
+++ b/frontend/discourse/app/components/composer-container.gjs
@@ -31,13 +31,13 @@ import {
SWIPE_VELOCITY_THRESHOLD,
} from "discourse/lib/swipe-events";
import PostLocalization from "discourse/models/post-localization";
-import grippieDragResize from "discourse/modifiers/grippie-drag-resize";
import CategoryChooser from "discourse/select-kit/components/category-chooser";
import DropdownSelectBox from "discourse/select-kit/components/dropdown-select-box";
import MiniTagChooser from "discourse/select-kit/components/mini-tag-chooser";
import { or } from "discourse/truth-helpers";
import DButton from "discourse/ui-kit/d-button";
import DPopupInputTip from "discourse/ui-kit/d-popup-input-tip";
+import DResizeSeparator from "discourse/ui-kit/d-resize-separator";
import DTextField from "discourse/ui-kit/d-text-field";
import dAvatar from "discourse/ui-kit/helpers/d-avatar";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
@@ -243,8 +243,14 @@ export default class ComposerContainer extends Component {
}
}
+ /** The box being resized. A function, because the separator resolves it. */
@bind
- onResizeDragStart() {
+ replyControl() {
+ return document.getElementById("reply-control");
+ }
+
+ @bind
+ onResizeStart() {
this.appEvents.trigger("composer:resize-started");
}
@@ -252,10 +258,11 @@ export default class ComposerContainer extends Component {
onResizeDrag(size) {
this.appEvents.trigger("composer:div-resizing");
+ this.replyControl()?.classList.add("clear-transitions");
+
const height = `${size}px`;
// resuming from minimized restores the height from the model
this.composer.model?.set("composerHeight", height);
- this.keyValueStore.set({ key: "composerHeight", value: height });
document.documentElement.style.setProperty(
"--composer-height",
size ? height : ""
@@ -265,8 +272,16 @@ export default class ComposerContainer extends Component {
}
@bind
- onResizeDragEnd() {
+ onResizeEnd(size) {
+ this.replyControl()?.classList.remove("clear-transitions");
+ // Announced before persisting, because the write can throw — storage quota —
+ // and a subscriber that undoes its own drag-time state has to hear the end of
+ // every resize regardless.
this.appEvents.trigger("composer:resize-ended");
+ // Persisted once per resize rather than on every report: the size is now
+ // reported once per animation frame instead of on a fixed throttle, and this
+ // write is the only thing that cared about the cadence.
+ this.keyValueStore.set({ key: "composerHeight", value: `${size}px` });
}
_triggerComposerResized() {
@@ -290,18 +305,16 @@ export default class ComposerContainer extends Component {
@cancelled={{this.composer.cancelled}}
@save={{this.composer.saveAction}}
>
- <div
+ <DResizeSeparator
class="grippie"
- {{grippieDragResize
- "#reply-control"
- "top"
- (hash
- onResizeStart=this.onResizeDragStart
- onThrottledDrag=this.onResizeDrag
- onResizeEnd=this.onResizeDragEnd
- )
- }}
- ></div>
+ @axis="vertical"
+ @side="end"
+ @measure={{this.replyControl}}
+ @label={{i18n "composer.resize"}}
+ @onResizeStart={{this.onResizeStart}}
+ @onResize={{this.onResizeDrag}}
+ @onResizeEnd={{this.onResizeEnd}}
+ />
{{#if this.composer.visible}}
{{htmlClass (if this.composer.isPreviewVisible "composer-has-preview")}}
diff --git a/frontend/discourse/app/lib/resize-measurements.ts b/frontend/discourse/app/lib/resize-measurements.ts
new file mode 100644
index 00000000000..5b45259257c
--- /dev/null
+++ b/frontend/discourse/app/lib/resize-measurements.ts
@@ -0,0 +1,104 @@
+import { headerOffset } from "discourse/lib/offset-calculator";
+
+/** The axis a resize runs along. */
+export type ResizeAxis = "vertical" | "horizontal";
+
+/**
+ * Floor for a box whose minimum does not resolve to pixels, per axis.
+ *
+ * Not one constant: a flex item computes `auto` on both axes and a horizontal
+ * splitter usually resizes one, so that floor binds far more often.
+ */
+const DEFAULT_MIN_SIZE: Record<ResizeAxis, number> = {
+ vertical: 250,
+ horizontal: 100,
+};
+
+/** Which properties describe a box's extent along each axis. */
+const AXIS_PROPERTIES = {
+ vertical: { offset: "offsetHeight", min: "minHeight", max: "maxHeight" },
+ horizontal: { offset: "offsetWidth", min: "minWidth", max: "maxWidth" },
+} as const;
+
+/**
+ * A computed length in pixels, or `null` when it is not one.
+ *
+ * Both checks are load-bearing. CSSOM leaves these properties' percentages
+ * unresolved and `50%` parses to a plausible `50`, which only the unit catches;
+ * `calc(10% + 5px)` ends in `px`, which only the parse catches.
+ */
+function pixels(declared: string | undefined): number | null {
+ if (!declared?.endsWith("px")) {
+ return null;
+ }
+
+ const value = parseFloat(declared);
+ return Number.isFinite(value) ? value : null;
+}
+
+/**
+ * The box's current extent along the axis being resized, from its border box.
+ *
+ * Null rather than zero when there is nothing to measure, which a resize would
+ * read as a real extent and drag on from. A detached box reports zero, so it
+ * counts as unmeasured too.
+ */
+export function measuredSize(
+ element: HTMLElement | null | undefined,
+ axis: ResizeAxis
+): number | null {
+ if (!element?.isConnected) {
+ return null;
+ }
+
+ return element[AXIS_PROPERTIES[axis].offset];
+}
+
+/**
+ * The smallest the box may be dragged to, read from the stylesheet so the two
+ * cannot drift apart. Zero with no box to measure: the floor stands in for an
+ * unresolved minimum, not for an absent consumer.
+ */
+export function measuredMin(
+ element: HTMLElement | null | undefined,
+ axis: ResizeAxis
+): number {
+ if (!element?.isConnected) {
+ return 0;
+ }
+
+ return (
+ pixels(getComputedStyle(element)[AXIS_PROPERTIES[axis].min]) ??
+ DEFAULT_MIN_SIZE[axis]
+ );
+}
+
+/**
+ * What is left of the viewport, leaving the header its space, which is as far as
+ * a box can grow.
+ *
+ * Asymmetric on purpose: `clientWidth` drops the scrollbar gutter while
+ * `innerHeight` keeps it, and matching them would move behaviour that shipped.
+ */
+export function viewportCap(axis: ResizeAxis): number {
+ return axis === "horizontal"
+ ? document.documentElement.clientWidth
+ : window.innerHeight - headerOffset();
+}
+
+/**
+ * The largest the box may be dragged to, never above `cap`. A declared maximum
+ * binds too, so dragging past it would report a size never rendered.
+ */
+export function measuredMax(
+ element: HTMLElement | null | undefined,
+ axis: ResizeAxis,
+ cap: number = viewportCap(axis)
+): number {
+ if (!element?.isConnected) {
+ return cap;
+ }
+
+ const declared = pixels(getComputedStyle(element)[AXIS_PROPERTIES[axis].max]);
+ return declared === null ? cap : Math.min(declared, cap);
+}
diff --git a/frontend/discourse/app/modifiers/grippie-drag-resize.js b/frontend/discourse/app/modifiers/grippie-drag-resize.js
deleted file mode 100644
index 3053a65b547..00000000000
--- a/frontend/discourse/app/modifiers/grippie-drag-resize.js
+++ /dev/null
@@ -1,185 +0,0 @@
-import { registerDestructor } from "@ember/destroyable";
-import { cancel, throttle } from "@ember/runloop";
-import { service } from "@ember/service";
-import Modifier from "ember-modifier";
-import { headerOffset } from "discourse/lib/offset-calculator";
-
-const START_DRAG_EVENTS = ["touchstart", "mousedown"];
-const DRAG_EVENTS = ["touchmove", "mousemove"];
-const END_DRAG_EVENTS = ["touchend", "mouseup"];
-const THROTTLE_RATE = 20;
-
-function mouseYPos(event) {
- return (
- event.clientY ||
- (event.touches && event.touches[0] && event.touches[0].clientY)
- );
-}
-
-/**
- * This modifier allows a target element to be resized vertically
- * by dragging an element, referred to as a "grippie", positioned
- * at the top or bottom of the target element.
- *
- * For example, a code editor or a composer like this:
- *
- * -------------------------------------
- * | |
- * | | <- resizableElement
- * | |
- * | |
- * ------------------------------------
- * | ======= | <- grippie
- * ------------------------------------
- */
-export default class GrippieDragResize extends Modifier {
- @service capabilities;
-
- constructor(owner, args) {
- super(owner, args);
- registerDestructor(this, (instance) => instance.cleanup());
- }
-
- startDragHandler(event) {
- event.preventDefault();
-
- // Only allow left-click dragging
- // c.f. https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button#value
- if (event.type === "mousedown" && event.button !== 0) {
- return;
- }
-
- this.originalResizableElementHeight = this.resizableElement.offsetHeight;
- this.lastMousePos = mouseYPos(event);
- this._throttledPerformDragHandler = this.throttledPerformDrag.bind(this);
- this._endDragHandler = this.endDragHandler.bind(this);
-
- DRAG_EVENTS.forEach((dragEvent) => {
- document.addEventListener(dragEvent, this._throttledPerformDragHandler, {
- capture: true,
- });
- });
-
- END_DRAG_EVENTS.forEach((endDragEvent) => {
- document.addEventListener(endDragEvent, this._endDragHandler);
- });
-
- this.onDragStart?.();
- }
-
- endDragHandler() {
- this.onDragEnd?.();
-
- DRAG_EVENTS.forEach((dragEvent) => {
- document.removeEventListener(
- dragEvent,
- this._throttledPerformDragHandler,
- {
- capture: true,
- }
- );
- });
-
- END_DRAG_EVENTS.forEach((endDragEvent) => {
- document.removeEventListener(endDragEvent, this._endDragHandler);
- });
-
- this.resizableElement.classList.remove("clear-transitions");
- this.resizableElement.focus();
- }
-
- throttledPerformDrag(event) {
- event.preventDefault();
- this.throttledDragHandler = throttle(
- this,
- () =>
- this.performDragHandler(
- this.resizableElement,
- this.grippiePosition,
- this.onThrottledDrag,
- event
- ),
- event,
- THROTTLE_RATE
- );
- }
-
- performDragHandler(
- resizableElement,
- grippiePosition,
- onThrottledDrag,
- event
- ) {
- resizableElement.classList.add("clear-transitions");
- const currentMousePos = mouseYPos(event);
-
- let size;
- if (grippiePosition === "top") {
- size =
- this.originalResizableElementHeight +
- (this.lastMousePos - currentMousePos);
- } else {
- size =
- this.originalResizableElementHeight -
- (this.lastMousePos - currentMousePos);
- }
-
- const maxHeight = this.capabilities.isTablet
- ? window.innerHeight
- : window.innerHeight - headerOffset();
-
- size = Math.min(size, maxHeight);
-
- const elementMinHeight = getComputedStyle(resizableElement).minHeight;
- const minHeight = parseInt(
- elementMinHeight === "auto" ? 250 : elementMinHeight,
- 10
- );
-
- size = Math.max(minHeight, size);
-
- onThrottledDrag?.(size);
- }
-
- /*
- * @param {HTMLElement} element - The element to which the modifier is applied, the grippie.
- * @param {string} resizableElementSelector - A CSS selector to find the resizable element,
- * should be something like a code editor or composer textarea.
- * @param {string} grippiePosition - The position of the grippie relative to
- * resizableElementSelector, either "top" or "bottom".
- * @param {Object} [callbacks] - An object containing optional callback functions.
- * * onDragStart - Callback function to be called when dragging starts.
- * * onThrottledDrag - Callback function to be called during throttled
- * drag events while moving the mouse.
- * * onDragEnd - Callback function to be called when dragging ends.
- */
- modify(element, [resizableElementSelector, grippiePosition, callbacks]) {
- this.element = element;
- this.resizableElement = document.querySelector(resizableElementSelector);
- this.grippiePosition = grippiePosition;
- this.onDragStart = callbacks.onDragStart;
- this.onThrottledDrag = callbacks.onThrottledDrag;
- this.onDragEnd = callbacks.onDragEnd;
-
- this._startDragHandler = this.startDragHandler.bind(this);
-
- START_DRAG_EVENTS.forEach((startDragEvent) => {
- element.addEventListener(startDragEvent, this._startDragHandler, {
- passive: false,
- });
- });
- }
-
- cleanup() {
- cancel(this.throttledDragHandler);
-
- if (this._startDragHandler) {
- START_DRAG_EVENTS.forEach((startDragEvent) => {
- this.element.removeEventListener(
- startDragEvent,
- this._startDragHandler
- );
- });
- }
- }
-}
diff --git a/frontend/discourse/app/ui-kit/d-resize-separator.gts b/frontend/discourse/app/ui-kit/d-resize-separator.gts
index 3ff63fecdf6..e0f5ec1171c 100644
--- a/frontend/discourse/app/ui-kit/d-resize-separator.gts
+++ b/frontend/discourse/app/ui-kit/d-resize-separator.gts
@@ -1,8 +1,16 @@
import Component from "@glimmer/component";
import { tracked } from "@glimmer/tracking";
+import { registerDestructor } from "@ember/destroyable";
import { action } from "@ember/object";
+import type Owner from "@ember/owner";
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
import { modifier } from "ember-modifier";
+import {
+ measuredMax,
+ measuredMin,
+ measuredSize,
+ type ResizeAxis,
+} from "discourse/lib/resize-measurements";
import dResizeEdge, {
type ResizeReportMeta,
} from "discourse/ui-kit/modifiers/d-resize-edge";
@@ -29,9 +37,9 @@ type Bound = number | (() => number);
* The box being resized: the element itself, or a function receiving the
* separator's own element and returning it.
*/
-type ObserveTarget =
- | Element
- | ((separator: HTMLElement) => Element | null | undefined);
+type MeasureTarget =
+ | HTMLElement
+ | ((separator: HTMLElement) => HTMLElement | null | undefined);
/**
* Which cursor is held while a gesture on each axis runs, mapped by
@@ -42,25 +50,26 @@ const CURSOR_CLASS = {
horizontal: "d-resizing-ew",
};
-interface ObserveResizedSignature {
+interface MeasureBoxSignature {
Element: HTMLElement;
Args: {
- Positional: [separator: DResizeSeparator, target?: ObserveTarget];
+ Positional: [separator: DResizeSeparator, target?: MeasureTarget];
};
}
/**
- * Watches the box being resized so the announced size keeps up with changes no
- * gesture caused.
+ * Resolves the box being resized and holds it for the component, then watches it
+ * so the announced size keeps up with changes no gesture caused.
*
* Re-runs when `target` changes, which is what lets a consumer pass the element
* itself once it exists. A function `target` is resolved on each run, so a stable
* function reference is never retried — that form suits a box already around the
* separator when it renders.
*/
-const observeResized = modifier<ObserveResizedSignature>(
+const measureBox = modifier<MeasureBoxSignature>(
(separator, [separatorComponent, target]) => {
const element = typeof target === "function" ? target(separator) : target;
+ separatorComponent.measuredBox = element ?? null;
if (!element) {
return;
}
@@ -68,7 +77,10 @@ const observeResized = modifier<ObserveResizedSignature>(
const observer = new ResizeObserver(() => separatorComponent.refresh());
observer.observe(element);
- return () => observer.disconnect();
+ return () => {
+ observer.disconnect();
+ separatorComponent.measuredBox = null;
+ };
}
);
@@ -102,7 +114,7 @@ interface DResizeSeparatorSignature {
* `"vertical"` to resize height, `"horizontal"` to resize width. Defaults to
* `"vertical"`.
*/
- axis?: "vertical" | "horizontal";
+ axis?: ResizeAxis;
/**
* The edge of the resized box the handle sits on, naming the edge OPPOSITE
@@ -112,16 +124,31 @@ interface DResizeSeparatorSignature {
side?: "start" | "end";
/**
- * The current size. Pass a function whenever the number is a live
- * measurement rather than tracked state.
+ * The box being resized. Given this, the separator measures its own size and
+ * bounds along `@axis` and keeps the announced values up to date, which is
+ * all an ordinary consumer needs.
+ *
+ * Either the element, or a function receiving the separator's own element
+ * and returning it. Resolved when the arg itself changes, so a stable
+ * function reference is called exactly once: pass that form for a box
+ * already around the separator when it renders, and the element form when it
+ * appears later, since replacing the element re-resolves.
+ */
+ measure?: MeasureTarget;
+
+ /**
+ * The current size, when it is NOT the measured extent of `@measure` — a
+ * number in the consumer's own units, say, or an offset from a resting size.
+ * Overrides the measurement. Pass a function whenever the number is a live
+ * reading rather than tracked state.
*/
- value: Measurement;
+ value?: Measurement;
- /** The smallest size the box may be dragged to. */
- min: Bound;
+ /** The smallest size the box may be dragged to. Overrides the measurement. */
+ min?: Bound;
- /** The largest size the box may be dragged to. */
- max: Bound;
+ /** The largest size the box may be dragged to. Overrides the measurement. */
+ max?: Bound;
/**
* What the separator is called, already translated. Required: a focusable
@@ -136,20 +163,15 @@ interface DResizeSeparatorSignature {
/** Fired throughout the gesture. Preview here. */
onResize?: (size: number) => void;
- /** Fired once at the end. Commit here. */
- onResizeEnd?: (size: number) => void;
-
/**
- * The box being resized, so the announced size keeps up with changes no
- * gesture caused, such as a panel opening or a preview toggling. Viewport
- * changes are picked up regardless and need no arg.
+ * Fired once at the end. Commit here.
*
- * Either the element, or a function receiving the separator's own element and
- * returning it. Pass the element when it may not exist at first render, since
- * a change to it re-attaches the observer; a function is resolved once, which
- * suits a box already around the separator when it renders.
+ * Also fired if the separator is destroyed with a gesture still held, since
+ * the engine beneath reports nothing on teardown and a consumer that opened
+ * something at the start would otherwise never get to close it. The size is
+ * the last one reported.
*/
- observe?: ObserveTarget;
+ onResizeEnd?: (size: number) => void;
};
Blocks: {
/**
@@ -183,18 +205,19 @@ interface DResizeSeparatorSignature {
* element a drag began on survives the pointer leaving it is engine-dependent,
* so the intent is stated on the page instead of left to the handle.
*
- * Sizes carry no unit of their own: they are whatever `@value`, `@min` and `@max`
- * are expressed in, which is a height for a stacked splitter and a width for a
- * side panel.
+ * Point it at the box with `@measure` and it reads the size and both bounds
+ * itself, along whichever axis it is resizing. Supply `@value`, `@min` or `@max`
+ * only when the number is NOT that measurement — an offset from a resting size,
+ * or a count in the consumer's own units — and each one given overrides what
+ * would have been measured.
*
* @example
+ * The ordinary case, where the separator resizes a box on the page:
* ```gjs
* <DResizeSeparator
* @axis="vertical"
* @side="end"
- * @value={{this.height}}
- * @min={{this.minHeight}}
- * @max={{this.maxHeight}}
+ * @measure={{this.panel}}
* @label={{i18n "composer.resize"}}
* @onResize={{this.preview}}
* @onResizeEnd={{this.commit}}
@@ -202,6 +225,18 @@ interface DResizeSeparatorSignature {
* />
* ```
*
+ * @example
+ * Sizes that are not a measurement, so the consumer supplies all three:
+ * ```gjs
+ * <DResizeSeparator
+ * @value={{this.dragOffset}}
+ * @min={{0}}
+ * @max={{this.maxOffset}}
+ * @label={{i18n "composer.resize"}}
+ * @onResize={{this.preview}}
+ * />
+ * ```
+ *
* Attributes pass through, so a consumer keeps its own class alongside this one —
* the two are merged rather than replaced — and may add its own modifiers.
*
@@ -210,6 +245,19 @@ interface DResizeSeparatorSignature {
* @see The `dOnResize` modifier to merely OBSERVE a size change. It is not a gesture.
*/
export default class DResizeSeparator extends Component<DResizeSeparatorSignature> {
+ /**
+ * The box resolved from `@measure`, written by the modifier that resolves it.
+ * Untracked: the size args read it when the gesture asks, and the modifier
+ * refreshes the announcement itself once it has one.
+ */
+ measuredBox: HTMLElement | null = null;
+
+ /** The last size a live gesture reported, so teardown can commit it. */
+ #reportedSize: number | null = null;
+
+ /** Whether a gesture has begun and not yet ended. */
+ #gestureOpen = false;
+
/** The size and bounds as last read, for assistive technology to announce. */
@tracked
_announced: {
@@ -218,10 +266,36 @@ export default class DResizeSeparator extends Component<DResizeSeparatorSignatur
max: number | undefined;
} | null = null;
+ constructor(owner: Owner, args: DResizeSeparatorSignature["Args"]) {
+ super(owner, args);
+ // The engine reports nothing when the element goes, so a gesture held at
+ // teardown would leave whatever the consumer opened at the start unclosed.
+ registerDestructor(this, () => this.#closeHeldGesture());
+ }
+
get axis() {
return this.args.axis ?? "vertical";
}
+ /**
+ * The size args as the gesture will see them: the consumer's own when it gave
+ * any, otherwise measurements of `@measure`.
+ *
+ * Owning the measuring functions keeps a trap off the public surface: a size
+ * given as a plain number is read once and frozen for the modifier's lifetime.
+ */
+ get resolvedValue(): Measurement {
+ return this.args.value ?? this.measureValue;
+ }
+
+ get resolvedMin(): Bound {
+ return this.args.min ?? this.measureMin;
+ }
+
+ get resolvedMax(): Bound {
+ return this.args.max ?? this.measureMax;
+ }
+
/** A separator's orientation is its own direction, not the axis it moves. */
get orientation() {
return this.axis === "horizontal" ? "vertical" : "horizontal";
@@ -236,7 +310,7 @@ export default class DResizeSeparator extends Component<DResizeSeparatorSignatur
* is left off rather than reporting a number nothing measured.
*/
get valueNow() {
- const now = this.#announce("value", "now");
+ const now = this.#announce(this.resolvedValue, "now");
if (now === undefined) {
return undefined;
}
@@ -251,11 +325,11 @@ export default class DResizeSeparator extends Component<DResizeSeparatorSignatur
}
get valueMin() {
- return this.#announce("min", "min");
+ return this.#announce(this.resolvedMin, "min");
}
get valueMax() {
- return this.#announce("max", "max");
+ return this.#announce(this.resolvedMax, "max");
}
/** Re-reads the size. Called on insert, after every report, and by the observer. */
@@ -264,6 +338,28 @@ export default class DResizeSeparator extends Component<DResizeSeparatorSignatur
this.#snapshot();
}
+ @action
+ measureValue() {
+ return measuredSize(this.measuredBox, this.axis);
+ }
+
+ @action
+ measureMin() {
+ return measuredMin(this.measuredBox, this.axis);
+ }
+
+ @action
+ measureMax() {
+ return measuredMax(this.measuredBox, this.axis);
+ }
+
+ @action
+ onResizeStart() {
+ this.#gestureOpen = true;
+ this.#reportedSize = null;
+ this.args.onResizeStart?.();
+ }
+
/**
* Re-reads the size only for a keyboard gesture.
*
@@ -282,6 +378,7 @@ export default class DResizeSeparator extends Component<DResizeSeparatorSignatur
*/
@action
onResize(size: number, meta: ResizeReportMeta) {
+ this.#reportedSize = size;
this.args.onResize?.(size);
// A held arrow key is one gesture spanning every repeat, so the commit that
@@ -297,10 +394,38 @@ export default class DResizeSeparator extends Component<DResizeSeparatorSignatur
@action
onResizeEnd(size: number) {
+ this.#gestureOpen = false;
+ this.#reportedSize = null;
this.args.onResizeEnd?.(size);
this.#snapshot(size);
}
+ /** Ends a gesture the engine abandoned, on the way out. */
+ #closeHeldGesture() {
+ if (!this.#gestureOpen) {
+ return;
+ }
+ this.#gestureOpen = false;
+
+ // Falls back so a gesture that opened something before reporting still
+ // closes it. Through `valueNow`, not the mirror behind it: only that clamps,
+ // and the raw reading can sit outside bounds the gesture would have applied.
+ const size = this.#reportedSize ?? this.valueNow;
+ this.#reportedSize = null;
+ if (size == null) {
+ return;
+ }
+
+ try {
+ this.args.onResizeEnd?.(size);
+ } catch (error) {
+ // Swallowed only here: a destructor throws into the flush tearing down
+ // every sibling component, and would take their cleanup with it.
+ // eslint-disable-next-line no-console
+ console.error(error);
+ }
+ }
+
/**
* Resolves one announced number, from the mirror or from the arg directly.
*
@@ -313,10 +438,9 @@ export default class DResizeSeparator extends Component<DResizeSeparatorSignatur
* @param mirrorKey - Its key in the mirror.
*/
#announce(
- argName: "value" | "min" | "max",
+ arg: Measurement | Bound,
mirrorKey: "now" | "min" | "max"
): number | undefined {
- const arg = this.args[argName];
if (typeof arg === "function") {
return this._announced?.[mirrorKey] ?? undefined;
}
@@ -332,9 +456,9 @@ export default class DResizeSeparator extends Component<DResizeSeparatorSignatur
// measures the DOM applies the new size through tracked state, which has not
// rendered yet while this runs inside its callback, so re-reading would
// announce the size the box is moving away from.
- const now = reportedSize ?? this.#read(this.args.value) ?? undefined;
- const min = this.#read(this.args.min);
- const max = this.#read(this.args.max);
+ const now = reportedSize ?? this.#read(this.resolvedValue) ?? undefined;
+ const min = this.#read(this.resolvedMin);
+ const max = this.#read(this.resolvedMax);
const announced = this._announced;
// Assigning invalidates whether or not the numbers differ, so a refresh that
@@ -377,17 +501,18 @@ export default class DResizeSeparator extends Component<DResizeSeparatorSignatur
aria-valuenow={{this.valueNow}}
aria-valuemin={{this.valueMin}}
aria-valuemax={{this.valueMax}}
+ {{! Before the refresh below, which reads the box this resolves. }}
+ {{measureBox this @measure}}
{{didInsert this.refresh}}
- {{observeResized this @observe}}
{{refreshOnViewportChange this}}
{{dResizeEdge
- value=@value
- min=@min
- max=@max
+ value=this.resolvedValue
+ min=this.resolvedMin
+ max=this.resolvedMax
axis=this.axis
side=@side
bodyClass=this.cursorClass
- onResizeStart=@onResizeStart
+ onResizeStart=this.onResizeStart
onResize=this.onResize
onResizeEnd=this.onResizeEnd
}}
diff --git a/frontend/discourse/tests/acceptance/composer-test.js b/frontend/discourse/tests/acceptance/composer-test.js
index 8e61a698ddc..7652a7d2965 100644
--- a/frontend/discourse/tests/acceptance/composer-test.js
+++ b/frontend/discourse/tests/acceptance/composer-test.js
@@ -4,7 +4,9 @@ import {
fillIn,
find,
focus,
+ resetOnerror,
settled,
+ setupOnerror,
triggerEvent,
triggerKeyEvent,
visit,
@@ -14,6 +16,7 @@ import { module, test } from "qunit";
import sinon from "sinon";
import LinkLookup from "discourse/lib/link-lookup";
import { cloneJSON } from "discourse/lib/object";
+import { headerOffset } from "discourse/lib/offset-calculator";
import { withPluginApi } from "discourse/lib/plugin-api";
import { translateModKey } from "discourse/lib/utilities";
import Composer, { CREATE_TOPIC } from "discourse/models/composer";
@@ -26,8 +29,36 @@ import {
metaModifier,
} from "discourse/tests/helpers/qunit-helpers";
import selectKit from "discourse/tests/helpers/select-kit-helper";
+import {
+ dragPointer,
+ settleGestureFrame,
+ stubPointerCapture,
+} from "discourse/tests/helpers/ui-kit/pointer-gesture-helper";
import { i18n } from "discourse-i18n";
+function composerResizeMeasurements() {
+ const replyControl = find("#reply-control");
+ const currentHeight = replyControl.offsetHeight;
+ const minimumHeight = parseInt(getComputedStyle(replyControl).minHeight, 10);
+ const maximumHeight = window.innerHeight - headerOffset();
+ const targetHeight = Math.floor(
+ minimumHeight + (maximumHeight - minimumHeight) / 2
+ );
+
+ return {
+ currentHeight,
+ minimumHeight,
+ maximumHeight,
+ targetHeight,
+ };
+}
+
+function dragCoordinatesForHeight(currentHeight, targetHeight) {
+ const from = 500;
+
+ return { from, to: from + currentHeight - targetHeight };
+}
+
acceptance(`Composer`, function (needs) {
needs.user({
id: 5,
@@ -128,41 +159,77 @@ acceptance(`Composer`, function (needs) {
);
});
- test("Composer height adjustment", async function (assert) {
+ test("persists and restores a dragged height", async function (assert) {
await visit("/");
await click("#create-topic");
- await triggerEvent(".grippie", "mousedown");
- await triggerEvent(".grippie", "mousemove");
- await triggerEvent(".grippie", "mouseup");
- await visit("/"); // reload page
- await click("#create-topic");
+ const { currentHeight, minimumHeight, maximumHeight, targetHeight } =
+ composerResizeMeasurements();
+ const expectedHeight = `${targetHeight}px`;
- const expectedHeight = localStorage.getItem(
- "__test_discourse_composerHeight"
+ assert.true(
+ targetHeight > minimumHeight,
+ "selects a target above the measured minimum clamp"
+ );
+ assert.true(
+ targetHeight < maximumHeight,
+ "selects a target below the measured maximum clamp"
+ );
+
+ await dragPointer(
+ ".grippie",
+ dragCoordinatesForHeight(currentHeight, targetHeight)
);
- const actualHeight =
- document.documentElement.style.getPropertyValue("--composer-height");
assert.strictEqual(
+ localStorage.getItem("__test_discourse_composerHeight"),
expectedHeight,
- actualHeight,
- "Updated height is persistent"
+ "persists the specific measured mid-range height"
+ );
+
+ await visit("/"); // reload page
+ await click("#create-topic");
+
+ assert.strictEqual(
+ document.documentElement.style.getPropertyValue("--composer-height"),
+ expectedHeight,
+ "restores that specific height on a later visit"
);
});
- test("restores the resized height when resuming a minimized draft", async function (assert) {
+ test("restores the dragged height when resuming a minimized draft", async function (assert) {
await visit("/");
await click("#create-topic");
await fillIn(".d-editor-input", "this draft has been resized");
- // drag past the minimum so the height clamps to a known value
- await triggerEvent(".grippie", "mousedown", { clientY: 500 });
- await triggerEvent(".grippie", "mousemove", { clientY: 3000 });
- await triggerEvent(".grippie", "mouseup");
+ const { currentHeight, minimumHeight, maximumHeight, targetHeight } =
+ composerResizeMeasurements();
+ const resizedHeight = `${targetHeight}px`;
+
+ assert.true(
+ targetHeight > minimumHeight,
+ "selects a target above the measured minimum clamp"
+ );
+ assert.true(
+ targetHeight < maximumHeight,
+ "selects a target below the measured maximum clamp"
+ );
+
+ await dragPointer(
+ ".grippie",
+ dragCoordinatesForHeight(currentHeight, targetHeight)
+ );
+ assert.strictEqual(
+ document.documentElement.style.getPropertyValue("--composer-height"),
+ resizedHeight,
+ "first applies a height that is neither the default nor the minimum"
+ );
- const resizedHeight =
- document.documentElement.style.getPropertyValue("--composer-height");
- assert.strictEqual(resizedHeight, "255px", "applies the dragged height");
+ await dragPointer(".grippie", { from: 500, to: 500 });
+ assert.strictEqual(
+ document.documentElement.style.getPropertyValue("--composer-height"),
+ resizedHeight,
+ "starts a later resize from the current live composer height"
+ );
await click(".toggle-minimize");
assert.strictEqual(
@@ -179,6 +246,288 @@ acceptance(`Composer`, function (needs) {
);
});
+ test("the grippie is an operable separator", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+
+ const { currentHeight, minimumHeight, maximumHeight } =
+ composerResizeMeasurements();
+
+ assert
+ .dom(".grippie")
+ .hasAttribute("role", "separator", "identifies the resize separator")
+ .hasAttribute(
+ "aria-orientation",
+ "horizontal",
+ "describes the separator's visual orientation"
+ )
+ .hasAttribute("aria-label", i18n("composer.resize"), "labels the grippie")
+ .hasAttribute("tabindex", "0", "makes the grippie keyboard focusable")
+ .hasAttribute(
+ "aria-valuenow",
+ `${currentHeight}`,
+ "exposes the current composer height"
+ )
+ .hasAttribute(
+ "aria-valuemin",
+ `${minimumHeight}`,
+ "exposes the computed minimum height"
+ )
+ .hasAttribute(
+ "aria-valuemax",
+ `${maximumHeight}`,
+ "exposes the current viewport maximum"
+ );
+
+ // Held throughout, so all three keys are one gesture. What a release commits
+ // is covered by the ComposerContainer rendering tests, which is also where it
+ // belongs: a release inside the composer schedules an unrelated
+ // similar-topics lookup that has nothing to do with resizing.
+ await triggerKeyEvent(".grippie", "keydown", "Home");
+ assert.strictEqual(
+ document.documentElement.style.getPropertyValue("--composer-height"),
+ `${minimumHeight}px`,
+ "Home resizes to the computed minimum"
+ );
+
+ await triggerKeyEvent(".grippie", "keydown", "ArrowUp");
+ assert.strictEqual(
+ document.documentElement.style.getPropertyValue("--composer-height"),
+ `${minimumHeight + 16}px`,
+ "ArrowUp grows the composer away from the minimum clamp"
+ );
+
+ await triggerKeyEvent(".grippie", "keydown", "End");
+ assert.strictEqual(
+ document.documentElement.style.getPropertyValue("--composer-height"),
+ `${maximumHeight}px`,
+ "End resizes to the current viewport maximum"
+ );
+ });
+
+ test("a pointer resize fires each lifecycle event once", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+
+ const appEvents = this.container.lookup("service:app-events");
+ appEvents.on("composer:resize-started", () => assert.step("started"));
+ appEvents.on("composer:resize-ended", () => assert.step("ended"));
+
+ const { currentHeight, targetHeight } = composerResizeMeasurements();
+ await dragPointer(
+ ".grippie",
+ dragCoordinatesForHeight(currentHeight, targetHeight)
+ );
+
+ assert.verifySteps(
+ ["started", "ended"],
+ "fires each resize lifecycle event exactly once"
+ );
+ });
+
+ test("a click on the grippie opens no resize", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+
+ const appEvents = this.container.lookup("service:app-events");
+ appEvents.on("composer:resize-started", () => assert.step("started"));
+ appEvents.on("composer:resize-ended", () => assert.step("ended"));
+
+ const grippie = find(".grippie");
+ stubPointerCapture(grippie);
+ await triggerEvent(grippie, "pointerdown", {
+ button: 0,
+ clientY: 400,
+ pointerId: 1,
+ });
+ await triggerEvent(grippie, "pointerup", {
+ button: 0,
+ clientY: 400,
+ pointerId: 1,
+ });
+
+ // A started without an ended strands every subscriber that undoes something
+ // on the end. Chat suppresses the drawer's transitions for the length of a
+ // composer resize and only restores them on the end, so an unclosed gesture
+ // leaves them suppressed for the rest of the session.
+ assert.verifySteps(
+ [],
+ "a press that never resized opens no gesture, so nothing is left waiting to be closed"
+ );
+ });
+
+ test("a failed persistence write still ends the resize", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+
+ const appEvents = this.container.lookup("service:app-events");
+ appEvents.on("composer:resize-ended", () => assert.step("ended"));
+
+ const keyValueStore = this.container.lookup("service:key-value-store");
+ const setStub = sinon
+ .stub(keyValueStore, "set")
+ .throws(new Error("simulated localStorage quota failure"));
+
+ const { currentHeight, targetHeight } = composerResizeMeasurements();
+ setupOnerror((error) => {
+ if (error.message !== "simulated localStorage quota failure") {
+ throw error;
+ }
+ });
+ try {
+ await dragPointer(
+ ".grippie",
+ dragCoordinatesForHeight(currentHeight, targetHeight)
+ );
+ } finally {
+ resetOnerror();
+ }
+
+ assert.true(
+ setStub.calledOnce,
+ "the resize attempts the persistence write"
+ );
+ assert.verifySteps(
+ ["ended"],
+ "composer:resize-ended fires after a failed persistence write"
+ );
+ });
+
+ test("a window resize refreshes the announced maximum", async function (assert) {
+ const initialWindowHeight = 900;
+ const expandedWindowHeight = 1200;
+ const innerHeightStub = sinon
+ .stub(window, "innerHeight")
+ .value(initialWindowHeight);
+
+ await visit("/");
+ const replyControl = find("#reply-control");
+ const headerHeight = headerOffset();
+ replyControl.style.maxHeight = `${initialWindowHeight - headerHeight}px`;
+ await click("#create-topic");
+
+ const initialComposerHeight = replyControl.offsetHeight;
+
+ innerHeightStub.value(expandedWindowHeight);
+ replyControl.style.maxHeight = `${expandedWindowHeight - headerHeight}px`;
+ window.dispatchEvent(new Event("resize"));
+ await settled();
+
+ assert.strictEqual(
+ replyControl.offsetHeight,
+ initialComposerHeight,
+ "the window resize leaves the fixed-height composer unchanged"
+ );
+ assert
+ .dom(".grippie")
+ .hasAttribute(
+ "aria-valuemax",
+ `${expandedWindowHeight - headerHeight}`,
+ "a window resize publishes the composer's new maximum height"
+ );
+ });
+
+ test("persists once, when the resize ends", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+
+ const keyValueStore = this.container.lookup("service:key-value-store");
+ const setSpy = sinon.spy(keyValueStore, "set");
+ const { currentHeight, minimumHeight, maximumHeight, targetHeight } =
+ composerResizeMeasurements();
+ const expectedHeight = `${targetHeight}px`;
+ const { from, to } = dragCoordinatesForHeight(currentHeight, targetHeight);
+ const grippie = find(".grippie");
+ stubPointerCapture(grippie);
+
+ assert.true(
+ targetHeight > minimumHeight,
+ "selects a target above the measured minimum clamp"
+ );
+ assert.true(
+ targetHeight < maximumHeight,
+ "selects a target below the measured maximum clamp"
+ );
+
+ await triggerEvent(grippie, "pointerdown", {
+ button: 0,
+ clientY: from,
+ pointerId: 1,
+ });
+ await triggerEvent(grippie, "pointermove", {
+ button: 0,
+ clientY: to,
+ pointerId: 1,
+ });
+ await settleGestureFrame();
+
+ assert.strictEqual(
+ document.documentElement.style.getPropertyValue("--composer-height"),
+ expectedHeight,
+ "applies the resized height on the animation-frame move"
+ );
+ assert.strictEqual(
+ setSpy.callCount,
+ 0,
+ "does not persist during the animation-frame move"
+ );
+
+ await triggerEvent(grippie, "pointerup", {
+ button: 0,
+ clientY: to,
+ pointerId: 1,
+ });
+
+ assert.strictEqual(setSpy.callCount, 1, "persists once when resizing ends");
+ assert.deepEqual(
+ setSpy.firstCall?.args,
+ [{ key: "composerHeight", value: expectedHeight }],
+ "persists the final height"
+ );
+ });
+
+ test("clears transitions from the first move to the end", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+
+ const replyControl = find("#reply-control");
+ const { currentHeight, targetHeight } = composerResizeMeasurements();
+ const { from, to } = dragCoordinatesForHeight(currentHeight, targetHeight);
+ const grippie = find(".grippie");
+ stubPointerCapture(grippie);
+
+ await triggerEvent(grippie, "pointerdown", {
+ button: 0,
+ clientY: from,
+ pointerId: 1,
+ });
+ assert
+ .dom(replyControl)
+ .doesNotHaveClass("clear-transitions", "keeps transitions on at press");
+
+ await triggerEvent(grippie, "pointermove", {
+ button: 0,
+ clientY: to,
+ pointerId: 1,
+ });
+ await settleGestureFrame();
+ assert
+ .dom(replyControl)
+ .hasClass("clear-transitions", "clears transitions on the first move");
+
+ await triggerEvent(grippie, "pointerup", {
+ button: 0,
+ clientY: to,
+ pointerId: 1,
+ });
+ assert
+ .dom(replyControl)
+ .doesNotHaveClass(
+ "clear-transitions",
+ "restores transitions at resize end"
+ );
+ });
+
test("fires resize event after width transition", async function (assert) {
await visit("/");
await click("#create-topic");
diff --git a/frontend/discourse/tests/helpers/ui-kit/pointer-gesture-helper.ts b/frontend/discourse/tests/helpers/ui-kit/pointer-gesture-helper.ts
index dddd9fd6a7a..e5b2067cd6f 100644
--- a/frontend/discourse/tests/helpers/ui-kit/pointer-gesture-helper.ts
+++ b/frontend/discourse/tests/helpers/ui-kit/pointer-gesture-helper.ts
@@ -1,4 +1,4 @@
-import { find } from "@ember/test-helpers";
+import { find, settled, triggerEvent } from "@ember/test-helpers";
/**
* Makes an element accept pointer capture for a pointer that was never real.
@@ -76,3 +76,80 @@ export function stubSharedPointerCapture(targets: (string | HTMLElement)[]) {
ownerOf: (pointerId: number) => owners.get(pointerId) ?? null,
};
}
+
+interface DragPointerOptions {
+ /** The client coordinate the press lands on, along the axis. */
+ from: number;
+ /** The client coordinate the pointer moves to. */
+ to: number;
+ /** Which client coordinate the gesture reads. Defaults to `"vertical"`. */
+ axis?: "vertical" | "horizontal";
+ /** Distinguishes concurrent gestures, and reused IDs across sequential ones. */
+ pointerId?: number;
+ /**
+ * Whether to release at the end. Pass `false` to leave the gesture open, for
+ * tests about what happens while one is still held.
+ */
+ release?: boolean;
+}
+
+/**
+ * Presses, moves and releases a pointer over one element.
+ *
+ * Capture is stubbed here rather than left to the caller, because a drag whose
+ * capture was never stubbed stops at the press without saying so: the assertions
+ * that follow then describe a gesture that never ran.
+ *
+ * @param target - The element to drag, or a selector for it.
+ * @param options - Where the gesture starts and ends, and how it is identified.
+ */
+export async function dragPointer(
+ target: string | HTMLElement,
+ {
+ from,
+ to,
+ axis = "vertical",
+ pointerId = 1,
+ release = true,
+ }: DragPointerOptions
+) {
+ const { element } = stubPointerCapture(target);
+ const coordinate = (value: number) =>
+ axis === "vertical" ? { clientY: value } : { clientX: value };
+
+ await triggerEvent(element, "pointerdown", {
+ button: 0,
+ pointerId,
+ ...coordinate(from),
+ });
+ await triggerEvent(element, "pointermove", {
+ button: 0,
+ pointerId,
+ ...coordinate(to),
+ });
+ await settleGestureFrame();
+
+ if (release) {
+ await triggerEvent(element, "pointerup", {
+ button: 0,
+ pointerId,
+ ...coordinate(to),
+ });
+ }
+
+ return element;
+}
+
+/**
+ * Waits for a gesture's pending report to land.
+ *
+ * Pointer moves are coalesced into an animation frame, so the size or position a
+ * gesture computes is reported on the next frame rather than during the move that
+ * caused it. `settled` does not await frames, so a test that presses, moves, and
+ * asserts reads the value from before the move and quietly passes or fails on the
+ * wrong basis. Await this between a move and any assertion about what the move did.
+ */
+export async function settleGestureFrame() {
+ await new Promise((resolve) => requestAnimationFrame(resolve));
+ await settled();
+}
diff --git a/frontend/discourse/tests/integration/components/ace-editor-test.gjs b/frontend/discourse/tests/integration/components/ace-editor-test.gjs
index 69d131ab9bf..291e9f00183 100644
--- a/frontend/discourse/tests/integration/components/ace-editor-test.gjs
+++ b/frontend/discourse/tests/integration/components/ace-editor-test.gjs
@@ -1,7 +1,23 @@
-import { render, triggerEvent } from "@ember/test-helpers";
+import {
+ find,
+ findAll,
+ focus,
+ render,
+ settled,
+ triggerEvent,
+ triggerKeyEvent,
+} from "@ember/test-helpers";
import { module, test } from "qunit";
+import sinon from "sinon";
import AceEditor from "discourse/components/ace-editor";
+import { headerOffset } from "discourse/lib/offset-calculator";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ dragPointer,
+ settleGestureFrame,
+ stubPointerCapture,
+} from "discourse/tests/helpers/ui-kit/pointer-gesture-helper";
+import { i18n } from "discourse-i18n";
module("Integration | Component | AceEditor", function (hooks) {
setupRenderingTest(hooks);
@@ -85,13 +101,13 @@ module("Integration | Component | AceEditor", function (hooks) {
.hasAttribute("data-disabled", "true", "it has a data-disabled attr");
});
- test("resizable editor", async function (assert) {
+ test("renders an accessible separator", async function (assert) {
await render(
<template>
<AceEditor
@mode="sql"
@content="SELECT * FROM users"
- style="width: 300px; height: 200px"
+ style="width: 300px; height: 220px; min-height: 200px; max-height: 240px"
@resizable={{true}}
/>
</template>
@@ -105,41 +121,240 @@ module("Integration | Component | AceEditor", function (hooks) {
assert
.dom(".ace-wrapper .grippie")
.exists("it renders the grippie element for dragging vertically");
+ assert
+ .dom(".ace-wrapper .grippie")
+ .hasAttribute("role", "separator", "the resize edge is a separator")
+ .hasAttribute(
+ "aria-orientation",
+ "horizontal",
+ "the separator reports its visual orientation"
+ )
+ .hasAttribute(
+ "aria-label",
+ i18n("ace_editor.resize"),
+ "the separator has an accessible name"
+ )
+ .hasAttribute("tabindex", "0", "the separator is keyboard focusable")
+ .hasAttribute(
+ "aria-valuenow",
+ "220",
+ "the separator reports the measured editor height"
+ )
+ .hasAttribute(
+ "aria-valuemin",
+ "200",
+ "the separator reports the computed minimum height"
+ )
+ .hasAttribute(
+ "aria-valuemax",
+ "240",
+ "the separator honors the editor's declared maximum height"
+ );
});
- test("resizable editor height adjustment", async function (assert) {
+ test("a window resize refreshes the announced maximum", async function (assert) {
+ const initialWindowHeight = 600;
+ const expandedWindowHeight = 900;
+ const innerHeightStub = sinon
+ .stub(window, "innerHeight")
+ .value(initialWindowHeight);
+
await render(
<template>
<AceEditor
@mode="sql"
@content="SELECT * FROM users"
- style="width: 300px; min-height: 200px"
+ style="width: 300px; height: 220px; min-height: 200px"
@resizable={{true}}
/>
</template>
);
- const initialHeight = document.querySelector(
- ".ace_editor--resizable"
- ).offsetHeight;
- const expectedHeight = initialHeight + 300;
- await triggerEvent(".grippie", "mousedown", { clientY: initialHeight });
- await triggerEvent(".grippie", "mousemove", { clientY: expectedHeight });
- await triggerEvent(".grippie", "mouseup", { clientY: expectedHeight });
+ innerHeightStub.value(expandedWindowHeight);
+ window.dispatchEvent(new Event("resize"));
+ await settled();
- const actualHeight = document.querySelector(
- ".ace_editor--resizable"
- ).offsetHeight;
- assert.strictEqual(expectedHeight, actualHeight, "height is adjusted");
+ assert
+ .dom(".ace-wrapper .grippie")
+ .hasAttribute(
+ "aria-valuemax",
+ `${expandedWindowHeight - headerOffset()}`,
+ "a window resize publishes the resizable area's new maximum height"
+ );
+ });
- await triggerEvent(".grippie", "mousedown", { clientY: expectedHeight });
- await triggerEvent(".grippie", "mousemove", { clientY: 150 });
- await triggerEvent(".grippie", "mouseup", { clientY: 150 });
+ test("a pointer drag adjusts and clamps the height", async function (assert) {
+ await render(
+ <template>
+ <button class="focus-sentinel" type="button">Keep focus</button>
+ <AceEditor
+ @mode="sql"
+ @content="SELECT * FROM users"
+ style="width: 300px; height: 260px; min-height: 200px"
+ @resizable={{true}}
+ />
+ </template>
+ );
+
+ const editor = find(".ace_editor--resizable");
+ const grippie = find(".grippie");
+ const initialHeight = editor.offsetHeight;
+ const startCoordinate = 47;
+ const growBy = 120;
+ const expectedHeight = initialHeight + growBy;
+
+ await focus(".focus-sentinel");
+ await dragPointer(grippie, {
+ from: startCoordinate,
+ to: startCoordinate + growBy,
+ });
assert.strictEqual(
- document.querySelector(".ace_editor--resizable").offsetHeight,
+ editor.offsetHeight,
+ expectedHeight,
+ "height is adjusted"
+ );
+ assert.dom(".focus-sentinel").isFocused("resizing does not steal focus");
+
+ await dragPointer(grippie, {
+ from: 611,
+ to: 11,
+ pointerId: 2,
+ });
+
+ assert.strictEqual(
+ editor.offsetHeight,
200,
"height will not go past the minimum height of 200px"
);
});
+
+ test("a drag resizes only its own editor", async function (assert) {
+ await render(
+ <template>
+ <AceEditor
+ @mode="sql"
+ @content="SELECT 1"
+ style="width: 300px; height: 240px; min-height: 200px; max-height: 500px"
+ @resizable={{true}}
+ />
+ <AceEditor
+ @mode="sql"
+ @content="SELECT 2"
+ style="width: 300px; height: 320px; min-height: 200px; max-height: 500px"
+ @resizable={{true}}
+ />
+ </template>
+ );
+
+ const editors = findAll(".ace_editor--resizable");
+ const grippies = findAll(".grippie");
+
+ await dragPointer(grippies[1], { from: 41, to: 101 });
+
+ assert.strictEqual(
+ editors[0].offsetHeight,
+ 240,
+ "the first editor keeps its height"
+ );
+ assert.strictEqual(
+ editors[1].offsetHeight,
+ 380,
+ "the second grippie resizes the second editor"
+ );
+ });
+
+ test("arrow, Home and End keys resize the editor", async function (assert) {
+ await render(
+ <template>
+ <AceEditor
+ @mode="sql"
+ @content="SELECT * FROM users"
+ style="width: 300px; height: 300px; min-height: 200px; max-height: 360px"
+ @resizable={{true}}
+ />
+ </template>
+ );
+
+ const editor = find(".ace_editor--resizable");
+ const grippie = find(".grippie");
+
+ // Released between presses: a key held down is one resize, and the size it
+ // reports is announced when it settles rather than on every repeat.
+ const press = async (key) => {
+ await triggerKeyEvent(grippie, "keydown", key);
+ await triggerKeyEvent(grippie, "keyup", key);
+ };
+
+ await press("ArrowDown");
+ assert.strictEqual(editor.offsetHeight, 316, "ArrowDown grows the editor");
+
+ await press("ArrowUp");
+ assert.strictEqual(editor.offsetHeight, 300, "ArrowUp shrinks the editor");
+
+ await press("Home");
+ assert.strictEqual(
+ editor.offsetHeight,
+ 200,
+ "Home uses the minimum height"
+ );
+
+ await press("End");
+ assert.strictEqual(editor.offsetHeight, 360, "End uses the maximum height");
+ assert
+ .dom(grippie)
+ .hasAttribute(
+ "aria-valuenow",
+ "360",
+ "keyboard resizing refreshes the reported height"
+ );
+ });
+
+ test("clears transitions from the first move to the end", async function (assert) {
+ await render(
+ <template>
+ <AceEditor
+ @mode="sql"
+ @content="SELECT * FROM users"
+ style="width: 300px; height: 260px; min-height: 200px"
+ @resizable={{true}}
+ />
+ </template>
+ );
+
+ const editor = find(".ace_editor--resizable");
+ const grippie = find(".grippie");
+ stubPointerCapture(grippie);
+
+ await triggerEvent(grippie, "pointerdown", {
+ button: 0,
+ clientY: 47,
+ pointerId: 1,
+ });
+ assert
+ .dom(editor)
+ .doesNotHaveClass("clear-transitions", "keeps transitions on at press");
+
+ await triggerEvent(grippie, "pointermove", {
+ button: 0,
+ clientY: 167,
+ pointerId: 1,
+ });
+ await settleGestureFrame();
+ assert
+ .dom(editor)
+ .hasClass("clear-transitions", "clears transitions on the first move");
+
+ await triggerEvent(grippie, "pointerup", {
+ button: 0,
+ clientY: 167,
+ pointerId: 1,
+ });
+ assert
+ .dom(editor)
+ .doesNotHaveClass(
+ "clear-transitions",
+ "restores transitions at resize end"
+ );
+ });
});
diff --git a/frontend/discourse/tests/integration/components/composer-container-test.gjs b/frontend/discourse/tests/integration/components/composer-container-test.gjs
new file mode 100644
index 00000000000..d5e0d12d259
--- /dev/null
+++ b/frontend/discourse/tests/integration/components/composer-container-test.gjs
@@ -0,0 +1,119 @@
+import { getOwner } from "@ember/owner";
+import {
+ clearRender,
+ find,
+ render,
+ settled,
+ triggerKeyEvent,
+} from "@ember/test-helpers";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import ComposerContainer from "discourse/components/composer-container";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import { dragPointer } from "discourse/tests/helpers/ui-kit/pointer-gesture-helper";
+
+/**
+ * Releases a key on the separator without bubbling.
+ *
+ * The separator's own listener is what commits the resize, and it sits on the
+ * element. A bubbling release would additionally reach the composer body, whose
+ * keyup handler drives typing state against a composer model this fixture has no
+ * reason to build.
+ */
+async function releaseKey(selector, key) {
+ find(selector).dispatchEvent(
+ new KeyboardEvent("keyup", { key, bubbles: false })
+ );
+ await settled();
+}
+
+module("Integration | Component | ComposerContainer", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ const appEvents = getOwner(this).lookup("service:app-events");
+ this.recordLifecycle = (assert) => {
+ appEvents.on("composer:resize-started", () => assert.step("started"));
+ appEvents.on("composer:resize-ended", () => assert.step("ended"));
+ };
+ });
+
+ hooks.afterEach(function () {
+ // Written on the document rather than on anything this test rendered, so it
+ // outlives the component unless it is taken back.
+ document.documentElement.style.removeProperty("--composer-height");
+ });
+
+ test("teardown with a resize still open ends it", async function (assert) {
+ this.recordLifecycle(assert);
+
+ await render(<template><ComposerContainer /></template>);
+
+ // Held rather than released, so the composer dies mid-gesture. The resize
+ // modifier fires no callback of its own when torn down that way.
+ await dragPointer(".grippie", { from: 500, to: 400, release: false });
+ assert.verifySteps(["started"], "the gesture is open and unclosed");
+
+ await clearRender();
+
+ assert.verifySteps(
+ ["ended"],
+ "teardown closes the resize rather than stranding subscribers that undo something on the end"
+ );
+ });
+
+ test("a resize that already ended is not ended twice", async function (assert) {
+ this.recordLifecycle(assert);
+
+ await render(<template><ComposerContainer /></template>);
+
+ await dragPointer(".grippie", { from: 500, to: 400 });
+ assert.verifySteps(
+ ["started", "ended"],
+ "releasing the pointer ends the resize"
+ );
+
+ await clearRender();
+
+ assert.verifySteps([], "teardown has nothing left to close");
+ });
+
+ test("a held key is one resize that commits when it is released", async function (assert) {
+ this.recordLifecycle(assert);
+ const keyValueStore = getOwner(this).lookup("service:key-value-store");
+ const setSpy = sinon.spy(keyValueStore, "set");
+
+ await render(<template><ComposerContainer /></template>);
+
+ await triggerKeyEvent(".grippie", "keydown", "End");
+ await triggerKeyEvent(".grippie", "keydown", "End", { repeat: true });
+
+ assert.verifySteps(
+ ["started"],
+ "the repeat belongs to the gesture the first press opened"
+ );
+ assert.strictEqual(
+ setSpy.callCount,
+ 0,
+ "nothing is persisted while the key is still held"
+ );
+
+ const height =
+ document.documentElement.style.getPropertyValue("--composer-height");
+ assert.notStrictEqual(height, "", "the held key previewed a height");
+
+ await releaseKey(".grippie", "End");
+
+ assert.verifySteps(["ended"], "releasing the key ends the resize");
+ assert.strictEqual(
+ setSpy.callCount,
+ 1,
+ "and persists once, on the release rather than per repeat"
+ );
+ assert.deepEqual(
+ setSpy.firstCall?.args,
+ [{ key: "composerHeight", value: height }],
+ "persisting the height the gesture settled on"
+ );
+ });
+});
diff --git a/frontend/discourse/tests/integration/ui-kit/d-resize-separator-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-resize-separator-test.gjs
index b07ff5dbfbd..c943499f4e9 100644
--- a/frontend/discourse/tests/integration/ui-kit/d-resize-separator-test.gjs
+++ b/frontend/discourse/tests/integration/ui-kit/d-resize-separator-test.gjs
@@ -3,6 +3,7 @@ import { tracked } from "@glimmer/tracking";
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
import { trustHTML } from "@ember/template";
import {
+ clearRender,
find,
render,
settled,
@@ -12,7 +13,10 @@ import {
} from "@ember/test-helpers";
import { module, test } from "qunit";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-import { stubPointerCapture } from "discourse/tests/helpers/ui-kit/pointer-gesture-helper";
+import {
+ settleGestureFrame,
+ stubPointerCapture,
+} from "discourse/tests/helpers/ui-kit/pointer-gesture-helper";
import DResizeSeparator from "discourse/ui-kit/d-resize-separator";
module("Integration | ui-kit | DResizeSeparator", function (hooks) {
@@ -456,7 +460,7 @@ module("Integration | ui-kit | DResizeSeparator", function (hooks) {
@min={{100}}
@max={{500}}
@label="Resize the thing"
- @observe={{resolve}}
+ @measure={{resolve}}
class="my-handle"
/>
</div>
@@ -549,7 +553,7 @@ module("Integration | ui-kit | DResizeSeparator", function (hooks) {
@min={{100}}
@max={{500}}
@label="Resize the thing"
- @observe={{state.target}}
+ @measure={{state.target}}
class="my-handle"
/>
</template>
@@ -600,8 +604,7 @@ module("Integration | ui-kit | DResizeSeparator", function (hooks) {
clientY: 400,
});
await triggerEvent(handle, "pointermove", { pointerId: 1, clientY: 360 });
- await new Promise(requestAnimationFrame);
- await settled();
+ await settleGestureFrame();
await triggerEvent(handle, "pointerup", { pointerId: 1, clientY: 360 });
// Without a starting size there is nothing to resize *from*, so the honest
@@ -780,4 +783,371 @@ module("Integration | ui-kit | DResizeSeparator", function (hooks) {
"a size beyond the maximum is announced as the maximum"
);
});
+
+ test("@measure supplies the size and bounds when none are given", async function (assert) {
+ const previews = [];
+ const commits = [];
+ const preview = (size) => previews.push(size);
+ const commit = (size) => commits.push(size);
+ const findBox = (separator) =>
+ separator.closest(".fixture")?.querySelector(".box");
+
+ await render(
+ <template>
+ <div class="fixture">
+ <div
+ class="box"
+ style="height: 300px; min-height: 100px; max-height: 500px"
+ ></div>
+ <DResizeSeparator
+ @axis="vertical"
+ @side="end"
+ @measure={{findBox}}
+ @label="Resize the thing"
+ @onResize={{preview}}
+ @onResizeEnd={{commit}}
+ class="my-handle"
+ />
+ </div>
+ </template>
+ );
+
+ const { element: handle } = stubPointerCapture(".my-handle");
+ await triggerEvent(handle, "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ clientY: 400,
+ });
+ await triggerEvent(handle, "pointermove", { pointerId: 1, clientY: 360 });
+ await settleGestureFrame();
+ await triggerEvent(handle, "pointerup", { pointerId: 1, clientY: 360 });
+
+ // On the outcome rather than the cadence, as the sibling drags do: how many
+ // previews precede a commit belongs to the modifier's own suite.
+ assert.deepEqual(
+ commits,
+ [340],
+ "the gesture runs from the box's own height without being told it"
+ );
+ assert.true(previews.length > 0, "previews arrived at all");
+ assert.true(
+ previews.every((size) => size === 340),
+ "and every one of them agrees with the commit"
+ );
+ assert
+ .dom(".my-handle")
+ .hasAttribute("aria-valuemin", "100", "the minimum comes from the box")
+ .hasAttribute("aria-valuemax", "500", "and so does the maximum");
+ });
+
+ test("@measure re-reads the box, so a second drag starts where the first left it", async function (assert) {
+ const commits = [];
+ const commit = (size) => commits.push(size);
+ const findBox = (separator) =>
+ separator.closest(".fixture")?.querySelector(".box");
+ // The box really takes the size, the way a consumer applies it.
+ const apply = (size) => (find(".box").style.height = `${size}px`);
+
+ await render(
+ <template>
+ <div class="fixture">
+ <div class="box" style="height: 300px; min-height: 100px"></div>
+ <DResizeSeparator
+ @axis="vertical"
+ @side="end"
+ @measure={{findBox}}
+ @max={{900}}
+ @label="Resize the thing"
+ @onResize={{apply}}
+ @onResizeEnd={{commit}}
+ class="my-handle"
+ />
+ </div>
+ </template>
+ );
+
+ const { element: handle } = stubPointerCapture(".my-handle");
+ for (const [from, to] of [
+ [400, 360],
+ [400, 380],
+ ]) {
+ await triggerEvent(handle, "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ clientY: from,
+ });
+ await triggerEvent(handle, "pointermove", { pointerId: 1, clientY: to });
+ await settleGestureFrame();
+ await triggerEvent(handle, "pointerup", { pointerId: 1, clientY: to });
+ }
+
+ // Read once and frozen, the second drag would start from 300 again and
+ // commit 320. This is the trap that made every consumer pass a function.
+ assert.deepEqual(
+ commits,
+ [340, 360],
+ "the second gesture grows from the size the first one left"
+ );
+ });
+
+ test("explicit sizes win over @measure", async function (assert) {
+ const reports = [];
+ const record = (size) => reports.push(size);
+ const findBox = (separator) =>
+ separator.closest(".fixture")?.querySelector(".box");
+ const size = () => 120;
+
+ await render(
+ <template>
+ <div class="fixture">
+ <div
+ class="box"
+ style="height: 300px; min-height: 20px; max-height: 700px"
+ ></div>
+ <DResizeSeparator
+ @axis="vertical"
+ @side="end"
+ @measure={{findBox}}
+ @value={{size}}
+ @min={{0}}
+ @max={{800}}
+ @label="Resize the thing"
+ @onResizeEnd={{record}}
+ class="my-handle"
+ />
+ </div>
+ </template>
+ );
+
+ const { element: handle } = stubPointerCapture(".my-handle");
+ await triggerEvent(handle, "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ clientY: 400,
+ });
+ await triggerEvent(handle, "pointermove", { pointerId: 1, clientY: 360 });
+ await settleGestureFrame();
+ await triggerEvent(handle, "pointerup", { pointerId: 1, clientY: 360 });
+
+ // A consumer whose number is not a measurement of the box keeps its own,
+ // and the box's own 20/700 are not what bound it either.
+ assert.deepEqual(
+ reports,
+ [160],
+ "the supplied size is used, not the box's 300"
+ );
+ assert
+ .dom(".my-handle")
+ .hasAttribute("aria-valuemin", "0", "the supplied minimum wins")
+ .hasAttribute("aria-valuemax", "800", "and so does the supplied maximum");
+ });
+
+ test("@measure takes its bounds from the axis being resized", async function (assert) {
+ const findBox = (separator) =>
+ separator.closest(".fixture")?.querySelector(".box");
+
+ await render(
+ <template>
+ <div class="fixture">
+ <div
+ class="box"
+ style="width: 220px; min-width: 60px; max-width: 400px;
+ height: 300px; min-height: 111px; max-height: 999px"
+ ></div>
+ <DResizeSeparator
+ @axis="horizontal"
+ @measure={{findBox}}
+ @label="Resize the panel"
+ class="my-handle"
+ />
+ </div>
+ </template>
+ );
+
+ // The vertical values are deliberately distinctive: reading `minHeight` or
+ // `maxHeight` here would announce 111 or 999, which a size-only assertion
+ // would not notice. Which viewport dimension caps which axis is pinned
+ // separately below, since a declared maximum sits under both.
+ assert
+ .dom(".my-handle")
+ .hasAttribute(
+ "aria-valuemin",
+ "60",
+ "the width minimum, not the height's"
+ )
+ .hasAttribute("aria-valuemax", "400", "and the width maximum");
+ });
+
+ test("an undeclared maximum is capped by the viewport dimension of its own axis", async function (assert) {
+ const findBox = (separator) =>
+ separator.closest(".fixture")?.querySelector(".box");
+
+ await render(
+ <template>
+ <div class="fixture">
+ <div class="box" style="width: 220px; height: 300px"></div>
+ <DResizeSeparator
+ @axis="horizontal"
+ @measure={{findBox}}
+ @label="Resize the panel"
+ class="my-handle"
+ />
+ </div>
+ </template>
+ );
+
+ // With nothing declared, the cap is all that bounds it, so this is the only
+ // place the axis of the cap itself is observable. Every other fixture
+ // declares a maximum below both viewport dimensions.
+ assert
+ .dom(".my-handle")
+ .hasAttribute(
+ "aria-valuemax",
+ String(document.documentElement.clientWidth),
+ "the width of the viewport, not its height"
+ );
+ });
+
+ test("a minimum that is not a pixel length falls back to the floor", async function (assert) {
+ const findBox = (separator) =>
+ separator.closest(".fixture")?.querySelector(".box");
+
+ await render(
+ <template>
+ <div class="fixture" style="height: 800px">
+ {{! A percentage is the dangerous one: unlike `min-content` it parses
+ to a plausible number, so only checking the unit catches it. }}
+ <div class="box" style="height: 300px; min-height: 50%"></div>
+ <DResizeSeparator
+ @axis="vertical"
+ @measure={{findBox}}
+ @label="Resize the thing"
+ class="my-handle"
+ />
+ </div>
+ </template>
+ );
+
+ assert
+ .dom(".my-handle")
+ .hasAttribute(
+ "aria-valuemin",
+ "250",
+ "the floor stands in, rather than 50 being read as pixels"
+ );
+ // The floor is also what an unresolved box reports, so this separates
+ // "fell back" from "never found the box at all".
+ assert
+ .dom(".my-handle")
+ .hasAttribute("aria-valuenow", /\d/, "and the box itself was measured");
+ });
+
+ test("@measure reads the axis being resized", async function (assert) {
+ const findBox = (separator) =>
+ separator.closest(".fixture")?.querySelector(".box");
+
+ await render(
+ <template>
+ <div class="fixture">
+ <div class="box" style="width: 220px; height: 300px"></div>
+ <DResizeSeparator
+ @axis="horizontal"
+ @measure={{findBox}}
+ @label="Resize the panel"
+ class="my-handle"
+ />
+ </div>
+ </template>
+ );
+
+ assert
+ .dom(".my-handle")
+ .hasAttribute(
+ "aria-valuenow",
+ "220",
+ "a horizontal resize measures width, not height"
+ );
+ });
+
+ test("a gesture that already ended is not committed again at teardown", async function (assert) {
+ const ends = [];
+ const record = (size) => ends.push(size);
+ const size = () => 300;
+
+ await render(
+ <template>
+ <DResizeSeparator
+ @axis="vertical"
+ @side="end"
+ @value={{size}}
+ @min={{100}}
+ @max={{500}}
+ @label="Resize the thing"
+ @onResizeEnd={{record}}
+ class="my-handle"
+ />
+ </template>
+ );
+
+ const { element: handle } = stubPointerCapture(".my-handle");
+ await triggerEvent(handle, "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ clientY: 400,
+ });
+ await triggerEvent(handle, "pointermove", { pointerId: 1, clientY: 360 });
+ await settleGestureFrame();
+ await triggerEvent(handle, "pointerup", { pointerId: 1, clientY: 360 });
+
+ assert.deepEqual(ends, [340], "the release committed once");
+
+ await clearRender();
+
+ // Leaving the gesture marked open on a normal end would commit the same
+ // size a second time here, which the sibling test above cannot see.
+ assert.deepEqual(ends, [340], "and teardown has nothing left to commit");
+ });
+
+ test("a gesture still open at teardown is closed once", async function (assert) {
+ const ends = [];
+ const record = (size) => ends.push(size);
+ const size = () => 300;
+
+ await render(
+ <template>
+ <DResizeSeparator
+ @axis="vertical"
+ @side="end"
+ @value={{size}}
+ @min={{100}}
+ @max={{500}}
+ @label="Resize the thing"
+ @onResizeEnd={{record}}
+ class="my-handle"
+ />
+ </template>
+ );
+
+ const { element: handle } = stubPointerCapture(".my-handle");
+ await triggerEvent(handle, "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ clientY: 400,
+ });
+ await triggerEvent(handle, "pointermove", { pointerId: 1, clientY: 360 });
+ await settleGestureFrame();
+
+ assert.deepEqual(ends, [], "nothing committed while the gesture is held");
+
+ // The pointer is still down. The gesture engine reports nothing when the
+ // element goes, so without this the consumer never learns the gesture ended
+ // and whatever it opened at the start stays open.
+ await clearRender();
+
+ assert.deepEqual(
+ ends,
+ [340],
+ "teardown commits the last size the gesture reported"
+ );
+ });
});
diff --git a/frontend/discourse/type-tests/ui-kit/d-resize-separator-errors-test.gts b/frontend/discourse/type-tests/ui-kit/d-resize-separator-errors-test.gts
index 49b203d438d..22d5131fffa 100644
--- a/frontend/discourse/type-tests/ui-kit/d-resize-separator-errors-test.gts
+++ b/frontend/discourse/type-tests/ui-kit/d-resize-separator-errors-test.gts
@@ -19,6 +19,12 @@ const Negatives = <template>
@max={{px}}
@label="Resize"
/>
+
+ <DResizeSeparator
+ {{! @glint-expect-error - the box is an element or a function returning one }}
+ @measure={{px}}
+ @label="Resize"
+ />
</template>;
export default Negatives;
diff --git a/frontend/discourse/type-tests/ui-kit/d-resize-separator-test.gts b/frontend/discourse/type-tests/ui-kit/d-resize-separator-test.gts
index 5d74c131c44..e562e6a99cd 100644
--- a/frontend/discourse/type-tests/ui-kit/d-resize-separator-test.gts
+++ b/frontend/discourse/type-tests/ui-kit/d-resize-separator-test.gts
@@ -9,9 +9,19 @@ declare const size: number;
declare const measure: () => number;
declare const measureMaybe: () => number | null;
declare const box: HTMLElement;
+declare function resolveBox(separator: HTMLElement): HTMLElement | null;
const Positives = <template>
- {{! A separator takes numbers or measurement functions for its size }}
+ {{! The ordinary case: the box alone, in either form }}
+ <DResizeSeparator @measure={{box}} @label="Resize" />
+ <DResizeSeparator
+ @axis="horizontal"
+ @measure={{resolveBox}}
+ @label="Resize"
+ @onResizeStart={{noop}}
+ />
+
+ {{! Sizes may still be supplied, and may be given alongside the box }}
<DResizeSeparator
@axis="vertical"
@side="end"
@@ -19,7 +29,7 @@ const Positives = <template>
@min={{size}}
@max={{size}}
@label="Resize"
- @observe={{box}}
+ @measure={{box}}
@onResizeStart={{noop}}
class="my-block__handle"
/>
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-drawer.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-drawer.gjs
index fd5944e47c8..ed95462b266 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat-drawer.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat-drawer.gjs
@@ -133,9 +133,11 @@ export default class ChatDrawer extends Component {
return;
}
+ // The flag can be set while the container is absent — `_performCheckSize`
+ // null-checks the same selector for that reason.
document
.querySelector(".chat-drawer-outlet-container")
- .classList.add("clear-transitions");
+ ?.classList.add("clear-transitions");
}
_clearDynamicCheckSize() {
@@ -145,7 +147,7 @@ export default class ChatDrawer extends Component {
document
.querySelector(".chat-drawer-outlet-container")
- .classList.remove("clear-transitions");
+ ?.classList.remove("clear-transitions");
this._checkSize();
}
diff --git a/plugins/chat/test/javascripts/unit/components/chat-drawer-test.js b/plugins/chat/test/javascripts/unit/components/chat-drawer-test.js
new file mode 100644
index 00000000000..04fd2aacbb1
--- /dev/null
+++ b/plugins/chat/test/javascripts/unit/components/chat-drawer-test.js
@@ -0,0 +1,55 @@
+import { module, test } from "qunit";
+import ChatDrawer from "discourse/plugins/chat/discourse/components/chat-drawer";
+
+const CONTAINER = ".chat-drawer-outlet-container";
+
+module("Unit | Component | ChatDrawer", function () {
+ test("resize start tolerates an active drawer whose container is absent", function (assert) {
+ let didThrow = false;
+
+ // The premise of the test: with a container present these would not reach
+ // the guard at all, and would pass without exercising anything.
+ assert.strictEqual(
+ document.querySelector(CONTAINER),
+ null,
+ "no drawer container is rendered"
+ );
+
+ try {
+ ChatDrawer.prototype._startDynamicCheckSize.call({
+ chatStateManager: { isDrawerActive: true },
+ });
+ } catch {
+ didThrow = true;
+ }
+
+ assert.false(
+ didThrow,
+ "composer resize start tolerates a missing chat drawer container"
+ );
+ });
+
+ test("resize end tolerates an active drawer whose container is absent", function (assert) {
+ let didThrow = false;
+
+ assert.strictEqual(
+ document.querySelector(CONTAINER),
+ null,
+ "no drawer container is rendered"
+ );
+
+ try {
+ ChatDrawer.prototype._clearDynamicCheckSize.call({
+ chatStateManager: { isDrawerActive: true },
+ _checkSize() {},
+ });
+ } catch {
+ didThrow = true;
+ }
+
+ assert.false(
+ didThrow,
+ "composer resize end tolerates a missing chat drawer container"
+ );
+ });
+});
diff --git a/spec/system/composer_resize_spec.rb b/spec/system/composer_resize_spec.rb
new file mode 100644
index 00000000000..1f1a1ee679f
--- /dev/null
+++ b/spec/system/composer_resize_spec.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+RSpec.describe "Composer resize" do
+ fab!(:user)
+ fab!(:topic)
+ fab!(:post) { Fabricate(:post, topic:) }
+
+ let(:composer) { PageObjects::Components::Composer.new }
+ let(:topic_page) { PageObjects::Pages::Topic.new }
+
+ before { sign_in(user) }
+
+ it "lets the user resize the composer by dragging its separator" do
+ topic_page.visit_topic_and_open_composer(topic)
+ expect(composer).to be_opened
+ initial_height = composer.height
+
+ composer.drag_resize_by(50)
+
+ expect(composer).to have_applied_height(initial_height + 50)
+ end
+end
diff --git a/spec/system/page_objects/components/composer.rb b/spec/system/page_objects/components/composer.rb
index dbedd8b7fbd..ef4e208367e 100644
--- a/spec/system/page_objects/components/composer.rb
+++ b/spec/system/page_objects/components/composer.rb
@@ -66,6 +66,22 @@ module PageObjects
self
end
+ def height
+ find(@composer_id).native.bounding_box["height"].round
+ end
+
+ def drag_resize_by(pixels)
+ drag_with_pointer(from: "#{@composer_id} .grippie", by: { y: -pixels })
+ self
+ end
+
+ # The composer's height is driven by this variable, so matching it is how the
+ # resize is observed. Named for what it reads rather than for the height, which
+ # would suggest measuring the box.
+ def has_applied_height?(height)
+ has_css?("html[style*='--composer-height: #{height}px']", visible: :all)
+ end
+
def fill_title(title)
find("#{@composer_id} #reply-title").fill_in(with: title)
self