A platform for community discussion. Free, open, simple.
DEV: Migrate Data Explorer resizing to shared separator (#42592)
Sérgio Saquetim405b5df1a7e7
diff --git a/frontend/discourse/app/lib/resize-measurements.ts b/frontend/discourse/app/lib/resize-measurements.tsindex 5b45259257c..9c15b8212cf 100644--- a/frontend/discourse/app/lib/resize-measurements.ts+++ b/frontend/discourse/app/lib/resize-measurements.ts@@ -16,8 +16,8 @@ const DEFAULT_MIN_SIZE: Record<ResizeAxis, number> = {/** 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" },+ vertical: { computed: "height", min: "minHeight", max: "maxHeight" },+ horizontal: { computed: "width", min: "minWidth", max: "maxWidth" },} as const;/**@@ -37,11 +37,16 @@ function pixels(declared: string | undefined): number | null {}/**- * The box's current extent along the axis being resized, from its border box.+ * The box's current extent along the axis being resized, read from the same box+ * that `style.height` and `style.width` write.*- * 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.+ * Those properties set the content box under `content-box` and the border box+ * under `border-box`. `offsetHeight` is right only in the second case, so a+ * bordered `content-box` element drifts a little on every gesture.+ *+ * Null when there is nothing to measure, which a resize would otherwise drag on+ * from. `pixels` enforces that. An element with no box keeps whatever was+ * declared, and a percentage would parse into a plausible-looking number.*/export function measuredSize(element: HTMLElement | null | undefined,@@ -51,7 +56,7 @@ export function measuredSize(return null;}- return element[AXIS_PROPERTIES[axis].offset];+ return pixels(getComputedStyle(element)[AXIS_PROPERTIES[axis].computed]);}/**@@ -74,8 +79,11 @@ export function measuredMin(}/**- * What is left of the viewport, leaving the header its space, which is as far as- * a box can grow.+ * What is left of the viewport, leaving the header its space.+ *+ * This suits a box pinned in the viewport, which would otherwise grow out of+ * view. A box in a scrolling page only lengthens the page, so this caps it for+ * no reason. Such a consumer should pass its own maximum.** Asymmetric on purpose: `clientWidth` drops the scrollbar gutter while* `innerHeight` keeps it, and matching them would move behaviour that shipped.@@ -87,8 +95,12 @@ export function viewportCap(axis: ResizeAxis): number {}/**- * 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.+ * The largest the box may be dragged to. A declared maximum binds, so dragging+ * past it would report a size never rendered, and `cap` binds above that.+ *+ * Never below {@link measuredMin}. A short viewport can put the cap under the+ * declared minimum, and CSS lets the minimum win. Announcing a maximum beneath+ * it would promise a range the box cannot take.*/export function measuredMax(element: HTMLElement | null | undefined,@@ -100,5 +112,6 @@ export function measuredMax(}const declared = pixels(getComputedStyle(element)[AXIS_PROPERTIES[axis].max]);- return declared === null ? cap : Math.min(declared, cap);+ const capped = declared === null ? cap : Math.min(declared, cap);+ return Math.max(capped, measuredMin(element, axis));}diff --git a/frontend/discourse/app/ui-kit/d-resize-separator.gts b/frontend/discourse/app/ui-kit/d-resize-separator.gtsindex a7cdc9d5d3b..b8792656033 100644--- a/frontend/discourse/app/ui-kit/d-resize-separator.gts+++ b/frontend/discourse/app/ui-kit/d-resize-separator.gts@@ -23,13 +23,12 @@ import dResizeEdge, {type Measurement = number | null | (() => number | null);/**- * A bound, which unlike a size is never unmeasured: there is nothing to clamp- * against until it is known, so an unmeasured bound would silently become `0`- * in the gesture's arithmetic rather than mean "no limit".+ * A bound, which unlike a size is expected to be known. There is nothing to clamp+ * against until it is, so a consumer with no limit should leave the arg off.*- * Documentation rather than enforcement. `strictNullChecks` is off repo-wide, so- * `number | null` collapses to `number` and a nullable measurement still- * type-checks here. What actually refuses one is the gesture's own guard.+ * `strictNullChecks` is off repo-wide, so a nullable measurement still type-checks+ * here. The gesture holds the line instead. It skips a bound that does not+ * resolve, rather than reading it as zero.*/type Bound = number | (() => number);@@ -211,6 +210,10 @@ interface DResizeSeparatorSignature {* or a count in the consumer's own units — and each one given overrides what* would have been measured.*+ * Supply `@max` for a second reason too, about layout rather than units. The+ * measured maximum leaves the header its space, which suits a box pinned in the+ * viewport. A box in a scrolling page should pass its own.+ ** @example* The ordinary case, where the separator resizes a box on the page:* ```gjsdiff --git a/frontend/discourse/app/ui-kit/modifiers/d-draggable.js b/frontend/discourse/app/ui-kit/modifiers/d-draggable.jsindex ab1f04a2aff..dd9866fa340 100644--- a/frontend/discourse/app/ui-kit/modifiers/d-draggable.js+++ b/frontend/discourse/app/ui-kit/modifiers/d-draggable.js@@ -1,8 +1,23 @@import { registerDestructor } from "@ember/destroyable";import Modifier from "ember-modifier";import { bind } from "discourse/lib/decorators";+import deprecated from "discourse/lib/deprecated";import ElementClassLease from "discourse/lib/element-class-lease";+/**+ * Binds a press-drag lifecycle using legacy mouse and touch event pairs, plus+ * native drag events, with document-level listeners for the gesture's duration.+ *+ * @deprecated since 2026.8.0. Use `dPointerDrag`+ * (`discourse/ui-kit/modifiers/d-pointer-drag`). Rename `didStartDrag`,+ * `dragMove` and `didEndDrag` to `onDragStart`, `onDrag` and `onDragEnd`, and+ * add `onDragCancel` so an interrupted gesture still finishes.+ *+ * Three differences bite beyond the renames:+ * - the second callback argument is gesture info, not the element;+ * - the body class is automatic here, but needs `bodyClass` there;+ * - a touch handler reading `event.touches[0]` should read the event itself.+ */export default class DDraggableModifier extends Modifier {hasStarted = false;element;@@ -10,6 +25,10 @@ export default class DDraggableModifier extends Modifier {constructor(owner, args) {super(owner, args);+ deprecated(+ "`dDraggable` is deprecated. Use `dPointerDrag` (`discourse/ui-kit/modifiers/d-pointer-drag`); it is not a drop-in, see its JSDoc.",+ { id: "discourse.ui-kit.d-draggable", since: "2026.8.0" }+ );registerDestructor(this, (instance) => instance.cleanup());}diff --git a/frontend/discourse/app/ui-kit/modifiers/d-resize-edge.ts b/frontend/discourse/app/ui-kit/modifiers/d-resize-edge.tsindex 9dcac79fbc9..1d7aefa8048 100644--- a/frontend/discourse/app/ui-kit/modifiers/d-resize-edge.ts+++ b/frontend/discourse/app/ui-kit/modifiers/d-resize-edge.ts@@ -268,6 +268,18 @@ export default class DResizeEdgeModifier extends Modifier<DResizeEdgeSignature>return;}+ // A jump with no bound has nowhere to land. Leave the key to whatever else+ // would act on it, as the size check below does.+ let jumpTarget;+ if (event.key === "Home" || event.key === "End") {+ jumpTarget = this.#read(+ event.key === "Home" ? this.#named.min : this.#named.max+ );+ if (!Number.isFinite(jumpTarget)) {+ return;+ }+ }+if (this.#keyboardValue === null) {const startValue = this.#read(this.#named.value);// Checked before the key is claimed: with no size to step from there is@@ -294,11 +306,8 @@ export default class DResizeEdgeModifier extends Modifier<DResizeEdgeSignature>case growKey:next = this.#keyboardValue + KEYBOARD_STEP * this.#growthDirection;break;- case "Home":- next = this.#read(this.#named.min);- break;default:- next = this.#read(this.#named.max);+ next = jumpTarget;break;}@@ -515,14 +524,17 @@ export default class DResizeEdgeModifier extends Modifier<DResizeEdgeSignature>}#clamp(size: number) {+ // An absent bound reads as zero in arithmetic, which would collapse the size+ // onto the other one. Skip it instead.+ const max = this.#read(this.#named.max);+ const min = this.#read(this.#named.min);+// The minimum is applied last, so it wins when the two bounds conflict — a// short viewport can put `max` below `min`, and the stylesheet's own min-height// would still hold the box open. Letting `max` win would report a size the// element never takes.- return Math.max(- Math.min(size, this.#read(this.#named.max)),- this.#read(this.#named.min)- );+ const capped = Number.isFinite(max) ? Math.min(size, max) : size;+ return Number.isFinite(min) ? Math.max(capped, min) : capped;}#cancelFrame() {diff --git a/frontend/discourse/tests/integration/modifiers/d-resize-edge-test.gjs b/frontend/discourse/tests/integration/modifiers/d-resize-edge-test.gjsindex cd9b0a51cdc..2f69340c178 100644--- a/frontend/discourse/tests/integration/modifiers/d-resize-edge-test.gjs+++ b/frontend/discourse/tests/integration/modifiers/d-resize-edge-test.gjs@@ -1161,6 +1161,97 @@ module("Integration | Modifier | d-resize-edge", function (hooks) {);});+ test("an absent maximum leaves a pointer drag unclamped", async function (assert) {+ const state = new Harness();+ const noMax = () => null;++ await render(+ <template>+ <div+ class="resize-edge"+ {{dResizeEdge+ value=state.value+ min=240+ max=noMax+ onResize=state.onResize+ onResizeEnd=state.onResizeEnd+ }}+ ></div>+ </template>+ );++ const edge = find(EDGE);+ stubPointerCapture(edge);+ await triggerEvent(edge, "pointerdown", {+ button: 0,+ clientX: 300,+ pointerId: 1,+ });+ await triggerEvent(edge, "pointerup", {+ button: 0,+ clientX: 420,+ pointerId: 1,+ });++ assert.deepEqual(+ state.resizeEnds,+ [420],+ "the size the pointer reached is reported, not a coerced bound"+ );+ });++ test("End is left alone when no maximum resolves", async function (assert) {+ const state = new Harness();+ const noMax = () => null;++ await render(+ <template>+ <div+ class="resize-edge"+ {{dResizeEdge+ value=state.value+ min=240+ max=noMax+ onResize=state.onResize+ onResizeEnd=state.onResizeEnd+ }}+ ></div>+ </template>+ );++ await triggerKeyEvent(EDGE, "keydown", "End");+ await triggerKeyEvent(EDGE, "keyup", "End");++ assert.deepEqual(state.resizes, [], "no size is reported");+ assert.deepEqual(state.resizeEnds, [], "no gesture is opened or closed");+ });++ test("Home is left alone when no minimum resolves", async function (assert) {+ const state = new Harness();+ const noMin = () => null;++ await render(+ <template>+ <div+ class="resize-edge"+ {{dResizeEdge+ value=state.value+ min=noMin+ max=360+ onResize=state.onResize+ onResizeEnd=state.onResizeEnd+ }}+ ></div>+ </template>+ );++ await triggerKeyEvent(EDGE, "keydown", "Home");+ await triggerKeyEvent(EDGE, "keyup", "Home");++ assert.deepEqual(state.resizes, [], "no size is reported");+ assert.deepEqual(state.resizeEnds, [], "no gesture is opened or closed");+ });+test("an interrupted resize keeps the size it was dragged to", async function (assert) {const state = new Harness();diff --git a/frontend/discourse/tests/integration/ui-kit/modifiers/d-draggable-test.gjs b/frontend/discourse/tests/integration/ui-kit/modifiers/d-draggable-test.gjsnew file mode 100644index 00000000000..302c16b07f7--- /dev/null+++ b/frontend/discourse/tests/integration/ui-kit/modifiers/d-draggable-test.gjs@@ -0,0 +1,57 @@+import { render, resetOnerror, setupOnerror } from "@ember/test-helpers";+import { module, test } from "qunit";+import DeprecationWorkflow from "discourse/deprecation-workflow";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import {+ restoreCountingDeprecation,+ skipCountingDeprecation,+} from "discourse/tests/helpers/deprecation-counter";+import {+ disableRaiseOnDeprecationQUnitResult,+ enableRaiseOnDeprecationQUnitResult,+} from "discourse/tests/helpers/raise-on-deprecation";+import dDraggable from "discourse/ui-kit/modifiers/d-draggable";++const DEPRECATION_ID = "discourse.ui-kit.d-draggable";++module("Integration | ui-kit | modifiers | dDraggable", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ // Reaching the modifier both pushes a failed assertion and throws. Only the+ // assertion is suppressed here; the throw is what these tests are about.+ disableRaiseOnDeprecationQUnitResult();+ skipCountingDeprecation(DEPRECATION_ID);+ });++ hooks.afterEach(function () {+ resetOnerror();+ enableRaiseOnDeprecationQUnitResult();+ restoreCountingDeprecation(DEPRECATION_ID);+ });++ test("using it raises, naming the id that tracks remaining usage", async function (assert) {+ let raised = null;+ setupOnerror((error) => (raised = error));++ await render(+ <template>+ <div {{dDraggable}}></div>+ </template>+ );++ // Asserted after the render rather than inside the handler, so a render that+ // raises nothing fails here instead of silently making no assertion.+ assert.true(+ raised?.message.includes(DEPRECATION_ID),+ "the raised error names the deprecation id"+ );+ });++ test("nothing silences the deprecation, so a usage in core or a preinstalled plugin fails CI", function (assert) {+ assert.true(+ DeprecationWorkflow.shouldThrow(DEPRECATION_ID, true),+ "an id with no workflow entry raises under RAISE_ON_DEPRECATION"+ );+ });+});diff --git a/frontend/discourse/tests/integration/ui-kit/modifiers/d-pointer-drag-test.gjs b/frontend/discourse/tests/integration/ui-kit/modifiers/d-pointer-drag-test.gjsindex ade075be533..93d36f4c850 100644--- a/frontend/discourse/tests/integration/ui-kit/modifiers/d-pointer-drag-test.gjs+++ b/frontend/discourse/tests/integration/ui-kit/modifiers/d-pointer-drag-test.gjs@@ -7,6 +7,7 @@ import {triggerEvent,} from "@ember/test-helpers";import { module, test } from "qunit";+import { withSilencedDeprecationsAsync } from "discourse/lib/deprecated";import { setupRenderingTest } from "discourse/tests/helpers/component-test";import {stubPointerCapture,@@ -15,6 +16,8 @@ import {import dDraggable from "discourse/ui-kit/modifiers/d-draggable";import dPointerDrag, * as dPointerDragModule from "discourse/ui-kit/modifiers/d-pointer-drag";+const LEGACY_DEPRECATION_ID = "discourse.ui-kit.d-draggable";+function installEventListenerSpy(element) {const added = [];const listeners = new Map();@@ -1608,11 +1611,15 @@ module("Integration | ui-kit | d-pointer-drag", function (hooks) {test("a legacy drag keeps the body class after a pointer drag ends", async function (assert) {const noop = () => {};- await render(- <template>- <div class="dpd-target" {{dPointerDrag bodyClass="dragging"}}></div>- <div class="legacy-target" {{dDraggable didEndDrag=noop}}></div>- </template>+ // The deprecation throws from the constructor, so the modifier would+ // never reach the listeners these tests need.+ await withSilencedDeprecationsAsync(LEGACY_DEPRECATION_ID, () =>+ render(+ <template>+ <div class="dpd-target" {{dPointerDrag bodyClass="dragging"}}></div>+ <div class="legacy-target" {{dDraggable didEndDrag=noop}}></div>+ </template>+ ));const pointerTarget = find(".dpd-target");@@ -1640,11 +1647,15 @@ module("Integration | ui-kit | d-pointer-drag", function (hooks) {test("a pointer drag keeps the body class after a legacy drag ends", async function (assert) {const noop = () => {};- await render(- <template>- <div class="dpd-target" {{dPointerDrag bodyClass="dragging"}}></div>- <div class="legacy-target" {{dDraggable didEndDrag=noop}}></div>- </template>+ // The deprecation throws from the constructor, so the modifier would+ // never reach the listeners these tests need.+ await withSilencedDeprecationsAsync(LEGACY_DEPRECATION_ID, () =>+ render(+ <template>+ <div class="dpd-target" {{dPointerDrag bodyClass="dragging"}}></div>+ <div class="legacy-target" {{dDraggable didEndDrag=noop}}></div>+ </template>+ ));const pointerTarget = find(".dpd-target");diff --git a/frontend/discourse/tests/unit/lib/resize-measurements-test.js b/frontend/discourse/tests/unit/lib/resize-measurements-test.jsnew file mode 100644index 00000000000..7d2089bf236--- /dev/null+++ b/frontend/discourse/tests/unit/lib/resize-measurements-test.js@@ -0,0 +1,141 @@+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import {+ measuredMax,+ measuredMin,+ measuredSize,+} from "discourse/lib/resize-measurements";++/**+ * Appends a styled box and removes it when the test ends.+ *+ * @param {object} hooks - The QUnit hooks the cleanup registers against.+ * @returns {(css: string) => HTMLElement} A factory taking inline styles.+ */+function boxFactory(hooks) {+ const created = [];+ hooks.afterEach(function () {+ created.splice(0).forEach((element) => element.remove());+ });++ return (css) => {+ const element = document.createElement("div");+ element.style.cssText = `position:absolute;top:-9999px;${css}`;+ document.body.appendChild(element);+ created.push(element);+ return element;+ };+}++module("Unit | Lib | resize-measurements", function (hooks) {+ setupTest(hooks);+ const box = boxFactory(hooks);++ module("measuredSize round-trips what consumers write", function () {+ const CASES = [+ { boxSizing: "content-box", padding: "0" },+ { boxSizing: "content-box", padding: "10px" },+ { boxSizing: "border-box", padding: "0" },+ { boxSizing: "border-box", padding: "10px" },+ ];++ for (const { boxSizing, padding } of CASES) {+ for (const axis of ["vertical", "horizontal"]) {+ const property = axis === "vertical" ? "height" : "width";++ test(`${axis}, ${boxSizing}, padding ${padding}`, function (assert) {+ const element = box(+ `box-sizing:${boxSizing};border:1px solid;padding:${padding};` ++ `height:400px;width:400px;`+ );++ element.style[property] = "440px";++ assert.strictEqual(+ measuredSize(element, axis),+ 440,+ "reads back the number that was written"+ );+ });+ }+ }++ test("a written fraction is preserved rather than rounded", function (assert) {+ const element = box("box-sizing:border-box;height:100px;width:100px;");+ element.style.height = "440.5px";++ assert.strictEqual(measuredSize(element, "vertical"), 440.5);+ });++ test("a flex item reports the height it was given", function (assert) {+ const parent = box("display:flex;flex-direction:column;height:600px;");+ const child = document.createElement("div");+ child.style.cssText = "box-sizing:content-box;border:1px solid;";+ parent.appendChild(child);++ child.style.height = "440px";++ assert.strictEqual(measuredSize(child, "vertical"), 440);+ });+ });++ module("measuredSize refuses a box that is not laid out", function () {+ test("a detached element is unmeasured", function (assert) {+ const element = document.createElement("div");+ element.style.height = "440px";++ assert.strictEqual(measuredSize(element, "vertical"), null);+ });++ test("a display:none element is unmeasured, percentage height and all", function (assert) {+ // With no box, CSSOM returns the computed value, so a percentage+ // survives as a plausible-looking number.+ const parent = box("height:800px;");+ const child = document.createElement("div");+ child.style.cssText = "display:none;height:50%;";+ parent.appendChild(child);++ assert.strictEqual(measuredSize(child, "vertical"), null);+ });++ test("an auto height is unmeasured", function (assert) {+ const parent = box("display:none;");+ const child = document.createElement("div");+ child.style.cssText = "height:auto;";+ parent.appendChild(child);++ assert.strictEqual(measuredSize(child, "vertical"), null);+ });+ });++ module("measuredMax never lands below measuredMin", function () {+ test("a declared minimum above the cap wins", function (assert) {+ const element = box("min-height:400px;height:400px;");++ assert.strictEqual(measuredMin(element, "vertical"), 400);+ assert.strictEqual(+ measuredMax(element, "vertical", 300),+ 400,+ "the floor beats a cap that would announce an impossible range"+ );+ });++ test("a declared maximum below the minimum still loses to it", function (assert) {+ const element = box("min-height:400px;max-height:300px;height:400px;");++ assert.strictEqual(measuredMax(element, "vertical", 1000), 400);+ });++ test("the cap still wins when it sits above the minimum", function (assert) {+ const element = box("min-height:200px;height:200px;");++ assert.strictEqual(measuredMax(element, "vertical", 500), 500);+ });++ test("a detached element is capped, with no minimum to floor against", function (assert) {+ const element = document.createElement("div");++ assert.strictEqual(measuredMax(element, "vertical", 300), 300);+ });+ });+});diff --git a/plugins/discourse-data-explorer/admin/assets/javascripts/admin/templates/admin-plugins/show/explorer/edit.gjs b/plugins/discourse-data-explorer/admin/assets/javascripts/admin/templates/admin-plugins/show/explorer/edit.gjsindex d790300c66e..eac82e3d06a 100644--- a/plugins/discourse-data-explorer/admin/assets/javascripts/admin/templates/admin-plugins/show/explorer/edit.gjs+++ b/plugins/discourse-data-explorer/admin/assets/javascripts/admin/templates/admin-plugins/show/explorer/edit.gjs@@ -9,10 +9,9 @@ import MultiSelect from "discourse/select-kit/components/multi-select";import { and, eq, notEq, or } from "discourse/truth-helpers";import DButton from "discourse/ui-kit/d-button";import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";+import DResizeSeparator from "discourse/ui-kit/d-resize-separator";import DTextField from "discourse/ui-kit/d-text-field";import DTextarea from "discourse/ui-kit/d-textarea";-import dIcon from "discourse/ui-kit/helpers/d-icon";-import dDraggable from "discourse/ui-kit/modifiers/d-draggable";import { i18n } from "discourse-i18n";import CodeView from "discourse/plugins/discourse-data-explorer/discourse/components/code-view";import ExplorerSchema from "discourse/plugins/discourse-data-explorer/discourse/components/explorer-schema";@@ -23,6 +22,18 @@ import QueryResultDownloadButtons from "discourse/plugins/discourse-data-exploreimport QueryResultsWrapper from "discourse/plugins/discourse-data-explorer/discourse/components/query-results-wrapper";import QueryRunSplitButton from "discourse/plugins/discourse-data-explorer/discourse/components/query-run-split-button";+const PaneSeparator = <template>+ <DResizeSeparator+ class="grippie"+ @axis="vertical"+ @side="start"+ @max={{@controller.maxPaneHeight}}+ @label={{i18n "explorer.resize_editor"}}+ @measure={{@controller.panesFor}}+ @onResize={{@controller.onPaneResize}}+ />+</template>;+export default class QueriesEdit extends Component {get showDestroyQuery() {return this.args.controller.model?.id > -1;@@ -122,7 +133,7 @@ export default class QueriesEdit extends Component {</div>{{#if @controller.editingQuery}}- <div class="panels-flex">+ <div class="panels-flex query-editor__panes"><div class="editor-panel"><AceEditor@content={{@controller.model.sql}}@@ -143,15 +154,7 @@ export default class QueriesEdit extends Component {</div></div>- <div- class="grippie"- {{dDraggable- }}- >- </div>+ <PaneSeparator @controller={{@controller}} /><div class="clear"></div>{{else}}@@ -255,7 +258,7 @@ export default class QueriesEdit extends Component {</div>{{#if @controller.editingQuery}}- <div class="panels-flex">+ <div class="panels-flex query-editor__panes"><div class="editor-panel"><AceEditor@content={{@controller.model.sql}}@@ -276,16 +279,7 @@ export default class QueriesEdit extends Component {</div></div>- <div- class="grippie"- {{dDraggable- }}- >- {{dIcon "discourse-expand"}}- </div>+ <PaneSeparator @controller={{@controller}} /><div class="clear"></div>{{else}}diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/edit.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/edit.jsindex 69f7abe0074..5d46ec1aef0 100644--- a/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/edit.js+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/edit.js@@ -7,6 +7,7 @@ import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";import { AUTO_GROUPS } from "discourse/lib/constants";import { bind } from "discourse/lib/decorators";+import { measuredMin } from "discourse/lib/resize-measurements";import { i18n } from "discourse-i18n";import QueryHelp from "discourse/plugins/discourse-data-explorer/discourse/components/modal/query-help";import { ParamValidationError } from "discourse/plugins/discourse-data-explorer/discourse/components/param-input-form";@@ -46,6 +47,16 @@ export default class PluginsExplorerController extends Controller {order = null;form = null;shouldAutoRun = false;++ /**+ * A weak handle on the panes the live separator resolved, rather than a global+ * query that would find whichever editor comes first in the document.+ *+ * Weak because this controller is an app-lifetime singleton and the separator+ * can go without telling it, so a strong reference would hold a detached+ * subtree until something else replaced it.+ */+ #resolvedPanes = null;_pristine = null;_teardownAiGeneration = null;_aiGenerationToken = 0;@@ -167,6 +178,11 @@ export default class PluginsExplorerController extends Controller {return items;}+ /** The one place the weak handle is dereferenced. */+ get #panes() {+ return this.#resolvedPanes?.deref() ?? null;+ }+initView() {const queryId = this.model?.id;const stored = queryId ? dataExplorerStore.get(`view_${queryId}`) : null;@@ -181,6 +197,50 @@ export default class PluginsExplorerController extends Controller {}}+ /**+ * The panes the separator resizes, found from the separator's own position.+ *+ * @param {HTMLElement} separator - The separator element.+ * @returns {HTMLElement|null} The panes, or null before they render.+ */+ @bind+ panesFor(separator) {+ const panes =+ separator.closest(".query-editor")?.querySelector(".panels-flex") ?? null;+ this.#resolvedPanes = panes ? new WeakRef(panes) : null;+ // The element, not the handle. It goes straight to a ResizeObserver.+ return panes;+ }++ /**+ * The largest the panes may be dragged to.+ *+ * A screenful, not the space below the header. This page scrolls, so growing+ * the panes lengthens it rather than pushing anything out of view.+ *+ * @returns {number} The maximum height in pixels.+ */+ @bind+ maxPaneHeight() {+ return Math.max(window.innerHeight, measuredMin(this.#panes, "vertical"));+ }++ @bind+ onPaneResize(size) {+ const panes = this.#panes;+ if (!panes) {+ return;+ }++ panes.style.height = `${size}px`;+ this.appEvents.trigger("ace:resize");+ }++ /** Lets go of the panes. Called by the route on exit. */+ releasePanes() {+ this.#resolvedPanes = null;+ }+@actionsetView(value) {this.view = value;@@ -338,37 +398,6 @@ export default class PluginsExplorerController extends Controller {});}- @bind- dragMove(e) {- if (!e.movementX) {- return;- }-- const editPane = document.querySelector(".query-editor");- const target = editPane.querySelector(".panels-flex");-- // we need to get the initial height / width of edit pane- // before we manipulate the size- if (!this.initialPaneWidth && !this.originalPaneHeight) {- this.originalPaneHeight = target.clientHeight;- }-- const newHeight = Math.max(- this.originalPaneHeight,- target.clientHeight + e.movementY- );-- target.style.height = newHeight + "px";-- this.appEvents.trigger("ace:resize");- }-- @bind- didStartDrag() {}-- @bind- didEndDrag() {}-@actionupdateGroupIds(value) {this.model.set("group_ids", value);diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/index.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/index.jsindex 75837824ee3..071791c112c 100644--- a/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/index.js+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/index.js@@ -12,7 +12,6 @@ import { i18n } from "discourse-i18n";export default class PluginsExplorerController extends Controller {@service dialog;- @service appEvents;@service router;@service store;@@ -68,38 +67,6 @@ export default class PluginsExplorerController extends Controller {});}- @bind- dragMove(e) {- if (!e.movementY && !e.movementX) {- return;- }-- const editPane = document.querySelector(".query-editor");- const target = editPane.querySelector(".panels-flex");- const grippie = editPane.querySelector(".grippie");-- // we need to get the initial height / width of edit pane- // before we manipulate the size- if (!this.initialPaneWidth && !this.originalPaneHeight) {- this.originalPaneWidth = target.clientWidth;- this.originalPaneHeight = target.clientHeight;- }-- const newHeight = Math.max(- this.originalPaneHeight,- target.clientHeight + e.movementY- );- const newWidth = Math.max(- this.originalPaneWidth,- target.clientWidth + e.movementX- );-- target.style.height = newHeight + "px";- target.style.width = newWidth + "px";- grippie.style.width = newWidth + "px";- this.appEvents.trigger("ace:resize");- }-@bindscrollTop() {window.scrollTo(0, 0);diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/admin-plugins/show/explorer/edit.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/admin-plugins/show/explorer/edit.jsindex 5f2e1ad8406..781823d03a2 100644--- a/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/admin-plugins/show/explorer/edit.js+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/admin-plugins/show/explorer/edit.js@@ -86,6 +86,7 @@ export default class AdminPluginsExplorerQueriesDetails extends DiscourseRoute {resetController(controller, isExiting) {if (isExiting) {controller._teardownAi();+ controller.releasePanes();}}}diff --git a/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss b/plugins/discourse-data-explorer/assets/stylesheets/explorer.scssindex 45c06db7345..0c4814fc91a 100644--- a/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss+++ b/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss@@ -115,6 +115,25 @@ table.group-reports {}}+ /* The floor a resize may not cross, read from here by the separator. Declared+ rather than measured once, so it follows the layout rather than whichever+ state the editor opened in. Carried by a class, so panes without a separator+ keep their own sizing. */++ .query-editor__panes {+ min-height: 400px;++ @include viewport.until(sm) {+ min-height: 548px;+ }+ }++ &.no-schema .query-editor__panes {+ @include viewport.until(sm) {+ min-height: 300px;+ }+ }+.editor-panel {flex: 1 0 50%;@@ -315,11 +334,8 @@ table.group-reports {}.grippie {- cursor: nwse-resize;padding-bottom: var(--space-2);user-select: none;- color: var(--primary);- text-align: right;}}diff --git a/plugins/discourse-data-explorer/config/locales/client.en.yml b/plugins/discourse-data-explorer/config/locales/client.en.ymlindex d219312c52b..0d3d694e627 100644--- a/plugins/discourse-data-explorer/config/locales/client.en.yml+++ b/plugins/discourse-data-explorer/config/locales/client.en.yml@@ -22,6 +22,7 @@ en:title: "Create a Data Explorer query"description: "Write a custom SQL query to surface anything specific to your community."explorer:+ resize_editor: "Resize the query editor"default_query: "Default"default_query_notice: "This is a default query, the SQL cannot be edited. To edit the SQL, create a new query."queries: "Queries"diff --git a/plugins/discourse-data-explorer/spec/system/page_objects/pages/data_explorer_query_runner.rb b/plugins/discourse-data-explorer/spec/system/page_objects/pages/data_explorer_query_runner.rbindex 19b9223571c..085da3a770a 100644--- a/plugins/discourse-data-explorer/spec/system/page_objects/pages/data_explorer_query_runner.rb+++ b/plugins/discourse-data-explorer/spec/system/page_objects/pages/data_explorer_query_runner.rb@@ -131,6 +131,40 @@ module PageObjectsdef has_chart?page.has_css?(".query-results .chart-canvas-container")end++ def collapse_schema+ page.find(".schema__toggle.--collapse").click+ self+ end++ # Clicked through the DOM. Stacked, this affordance sits past the left edge+ # of the viewport, where a real click cannot land on it.+ def expand_schema+ page.execute_script("document.querySelector('.schema__toggle.--expand').click()")+ self+ end++ # Drags the editor separator, negative to shrink.+ def resize_panes_by(y)+ drag_with_pointer(from: ".query-editor .grippie", by: { y: y })+ self+ end++ # The floor the separator announces for the layout as it stands.+ def pane_floor+ page.find(".query-editor .grippie")["aria-valuemin"].to_f+ end++ # How much taller the panes' content is than the box clipping it. One pixel+ # is not overflow; the two readings round independently.+ def pane_overflow+ page.evaluate_script(<<~JS)+ (() => {+ const panes = document.querySelector(".query-editor .panels-flex");+ return Math.max(0, panes.scrollHeight - panes.clientHeight - 1);+ })()+ JS+ endendendenddiff --git a/plugins/discourse-data-explorer/spec/system/query_editor_resize_spec.rb b/plugins/discourse-data-explorer/spec/system/query_editor_resize_spec.rbnew file mode 100644index 00000000000..16ab5b6cc19--- /dev/null+++ b/plugins/discourse-data-explorer/spec/system/query_editor_resize_spec.rb@@ -0,0 +1,77 @@+# frozen_string_literal: true++RSpec.describe "Data explorer query editor resizing" do+ fab!(:admin)+ fab!(:query) { Fabricate(:query, name: "Resize", sql: "SELECT 1", user: admin) }++ let(:query_runner) { PageObjects::Pages::DataExplorerQueryRunner.new }++ before do+ SiteSetting.data_explorer_enabled = true+ sign_in admin+ end++ # Narrow enough for the stacked layout, where the panes are content-sized and a+ # short floor clips them. Wide, they have a fixed height and cannot overflow.+ def in_the_stacked_layout(&block)+ resize_window(width: 500, height: 900, &block)+ end++ def shrink_hard+ query_runner.resize_panes_by(-400)+ # Asserted through a retry: the drag bypasses Capybara's settle wait.+ try_until_success { expect(query_runner.pane_overflow).to eq(0) }+ end++ it "will not shrink the panes past the content they clip" do+ in_the_stacked_layout do+ query_runner.visit_admin_query(query.id)+ expect(page).to have_css(".query-editor .panels-flex")++ shrink_hard+ end+ end++ it "will not shrink past the shorter content left when the schema is hidden" do+ in_the_stacked_layout do+ query_runner.visit_admin_query(query.id)+ expect(page).to have_css(".query-editor .panels-flex")+ query_runner.collapse_schema+ expect(page).to have_css(".query-editor.no-schema")++ shrink_hard+ end+ end++ it "asks less of the layout once the schema is out of it" do+ in_the_stacked_layout do+ query_runner.visit_admin_query(query.id)+ expect(page).to have_css(".query-editor .panels-flex")+ with_schema = query_runner.pane_floor++ query_runner.collapse_schema+ expect(page).to have_css(".query-editor.no-schema")++ # Stacked, the floor is what the panes rest at, not just a drag limit. The+ # taller figure would leave the editor standing in space it cannot fill.+ expect(query_runner.pane_floor).to be < with_schema+ end+ end++ it "follows the schema appearing after the panes were first measured without it" do+ in_the_stacked_layout do+ query_runner.visit_admin_query(query.id)+ query_runner.collapse_schema+ expect(page).to have_css(".query-editor.no-schema")++ # Revisited so the editor is built with the schema already hidden. Only+ # this order leaves a captured floor too low for the content that follows.+ query_runner.visit_admin_query(query.id)+ expect(page).to have_css(".query-editor.no-schema")+ query_runner.expand_schema+ expect(page).to have_no_css(".query-editor.no-schema")++ shrink_hard+ end+ end+enddiff --git a/plugins/discourse-data-explorer/test/javascripts/acceptance/run-query-test.js b/plugins/discourse-data-explorer/test/javascripts/acceptance/run-query-test.jsindex e4c1eabc71b..50504712987 100644--- a/plugins/discourse-data-explorer/test/javascripts/acceptance/run-query-test.js+++ b/plugins/discourse-data-explorer/test/javascripts/acceptance/run-query-test.js@@ -1,7 +1,17 @@-import { click, visit } from "@ember/test-helpers";+import {+ click,+ find,+ triggerEvent,+ triggerKeyEvent,+ visit,+} from "@ember/test-helpers";import { test } from "qunit";import sinon from "sinon";import { acceptance } from "discourse/tests/helpers/qunit-helpers";+import {+ settleGestureFrame,+ stubPointerCapture,+} from "discourse/tests/helpers/ui-kit/pointer-gesture-helper";import { i18n } from "discourse-i18n";acceptance("Run Query", function (needs) {@@ -428,4 +438,149 @@ acceptance("Run Query", function (needs) {assert.dom("div.query-results").exists("query results should be displayed");});++ test("dragging the grippie resizes the editor panes", async function (assert) {+ await visit("/admin/plugins/discourse-data-explorer/queries/2");++ const grippie = find(".query-editor .grippie");+ const panes = find(".query-editor .panels-flex");+ stubPointerCapture(grippie);+ const startingHeight = panes.clientHeight;++ await triggerEvent(grippie, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientY: 200,+ });+ // No sideways movement: a vertical resize must not need any.+ await triggerEvent(grippie, "pointermove", { pointerId: 1, clientY: 240 });+ await settleGestureFrame();++ assert.strictEqual(+ panes.style.height,+ `${startingHeight + 40}px`,+ "the panes grow by the pointer's vertical travel"+ );+ // Asserted mid-gesture as well as after: absence on release alone would+ // pass against a resize that never held the cursor at all.+ assert+ .dom(document.body)+ .hasClass("d-resizing-ns", "the cursor is held while the drag runs");++ await triggerEvent(grippie, "pointerup", { pointerId: 1, clientY: 240 });+ assert+ .dom(document.body)+ .doesNotHaveClass(+ "d-resizing-ns",+ "the held cursor is given back on release"+ );+ });++ test("the grippie is an operable separator", async function (assert) {+ await visit("/admin/plugins/discourse-data-explorer/queries/2");++ const grippie = find(".query-editor .grippie");++ assert+ .dom(grippie)+ .hasAttribute("role", "separator")+ .hasAttribute("aria-orientation", "horizontal")+ .hasAttribute("tabindex", "0")+ .hasAttribute("data-resize-axis", "vertical");+ assert+ .dom(grippie)+ .hasAttribute(+ "aria-label",+ i18n("explorer.resize_editor"),+ "the separator says what it resizes rather than announcing a bare splitter"+ );++ const panes = find(".query-editor .panels-flex");+ const startingHeight = panes.clientHeight;+ await triggerKeyEvent(grippie, "keydown", "ArrowDown");++ assert.true(+ parseInt(panes.style.height, 10) > startingHeight,+ "arrow keys resize it without a pointer"+ );+ });++ test("the separator announces a size inside the bounds it announces", async function (assert) {+ await visit("/admin/plugins/discourse-data-explorer/queries/2");++ const grippie = find(".query-editor .grippie");+ const read = (name) => parseFloat(grippie.getAttribute(name));++ // Asserted against each other, not against pixels. The numbers depend on the+ // stylesheet and the window; a size outside its own range is wrong regardless.+ assert.true(+ Number.isFinite(read("aria-valuenow")),+ "a size is announced once the panes are measured"+ );+ assert.true(+ read("aria-valuemin") <= read("aria-valuenow"),+ "the announced size is not below the announced minimum"+ );+ assert.true(+ read("aria-valuenow") <= read("aria-valuemax"),+ "the announced size is not above the announced maximum"+ );+ });++ test("dragging far past the maximum stops at it", async function (assert) {+ await visit("/admin/plugins/discourse-data-explorer/queries/2");++ const grippie = find(".query-editor .grippie");+ const panes = find(".query-editor .panels-flex");+ stubPointerCapture(grippie);+ const ceiling = parseFloat(grippie.getAttribute("aria-valuemax"));++ await triggerEvent(grippie, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientY: 200,+ });+ await triggerEvent(grippie, "pointermove", {+ pointerId: 1,+ clientY: 200 + ceiling * 3,+ });+ await settleGestureFrame();+ await triggerEvent(grippie, "pointerup", {+ pointerId: 1,+ clientY: 200 + ceiling * 3,+ });++ assert.true(+ parseFloat(panes.style.height) <= ceiling,+ "the panes stop at the maximum rather than following the pointer"+ );+ });++ test("a separator torn down mid-gesture writes nothing afterwards", async function (assert) {+ await visit("/admin/plugins/discourse-data-explorer/queries/2");++ const grippie = find(".query-editor .grippie");+ const panes = find(".query-editor .panels-flex");+ stubPointerCapture(grippie);++ await triggerEvent(grippie, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientY: 200,+ });+ await triggerEvent(grippie, "pointermove", { pointerId: 1, clientY: 260 });+ await settleGestureFrame();+ const heightWhenTornDown = panes.style.height;++ // Leaving the route with the gesture still held: the separator goes, and the+ // controller is a singleton that outlives it.+ await visit("/admin/plugins/discourse-data-explorer");+ await triggerEvent(document, "pointerup", { pointerId: 1, clientY: 900 });++ assert.strictEqual(+ panes.style.height,+ heightWhenTornDown,+ "the detached panes keep the size they had when the separator went"+ );+ });});