Skip to content

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

UX: composer redesign > swipe down to dismiss the keyboard (#41979)

Renato Atilio3849c41d956a
diff --git a/frontend/discourse/app/components/composer-container.gjs b/frontend/discourse/app/components/composer-container.gjs
index e264f5a2b8f..a14ec97a4ab 100644
--- a/frontend/discourse/app/components/composer-container.gjs
+++ b/frontend/discourse/app/components/composer-container.gjs
@@ -24,6 +24,12 @@ import htmlClass from "discourse/helpers/html-class";
import lazyHash from "discourse/helpers/lazy-hash";
import discourseDebounce from "discourse/lib/debounce";
import { bind } from "discourse/lib/decorators";
+import {
+ dampenedOverdrag,
+ shouldDeferSwipeToContent,
+ SWIPE_DISTANCE_THRESHOLD,
+ 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";
@@ -37,6 +43,7 @@ import dAvatar from "discourse/ui-kit/helpers/d-avatar";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
import dIcon from "discourse/ui-kit/helpers/d-icon";
import dLoadingSpinner from "discourse/ui-kit/helpers/d-loading-spinner";
+import dSwipe from "discourse/ui-kit/modifiers/d-swipe";
import { i18n } from "discourse-i18n";
const trackFieldsHeight = modifier((element, [enabled]) => {
@@ -97,6 +104,9 @@ export default class ComposerContainer extends Component {
@tracked toolbarPortalTarget;
+ #swipeEditor = null;
+ #swipeSlide = 0;
+
willDestroy() {
super.willDestroy(...arguments);
cancel(this.composerResizeDebounceHandler);
@@ -106,6 +116,73 @@ export default class ComposerContainer extends Component {
return this.siteSettings.enable_composer_redesign;
}
+ @action
+ onSwipeStart(state, event) {
+ // :focus-within keeps the match when a NodeView input inside the editor
+ // is focused (which doesn't set .in-focus)
+ const editor = state.element.querySelector(
+ ".d-editor-textarea-wrapper.in-focus, .d-editor-textarea-wrapper:focus-within"
+ );
+
+ if (
+ !editor ||
+ !state.goingDown() ||
+ shouldDeferSwipeToContent(state, state.element)
+ ) {
+ event.preventDefault();
+ return;
+ }
+
+ this.#swipeEditor = editor;
+ this.#swipeSlide = -parseFloat(getComputedStyle(editor).marginTop) || 0;
+ editor.style.transition = "none";
+ }
+
+ @action
+ onSwipe(state) {
+ if (!this.#swipeEditor) {
+ return;
+ }
+
+ const pulled = Math.max(0, state.deltaY);
+ const margin =
+ pulled <= this.#swipeSlide
+ ? pulled - this.#swipeSlide
+ : dampenedOverdrag(pulled - this.#swipeSlide);
+ this.#swipeEditor.style.marginTop = `${margin}px`;
+ }
+
+ @action
+ onSwipeEnd(state) {
+ const editor = this.#swipeEditor;
+ if (!editor) {
+ return;
+ }
+ this.#swipeEditor = null;
+ editor.style.transition = "";
+
+ const dismissed =
+ state.deltaY > SWIPE_DISTANCE_THRESHOLD ||
+ state.velocityY > SWIPE_VELOCITY_THRESHOLD;
+
+ if (dismissed && editor.contains(document.activeElement)) {
+ document.activeElement.blur();
+ }
+
+ editor.style.marginTop = "";
+ }
+
+ @action
+ onSwipeCancel() {
+ const editor = this.#swipeEditor;
+ if (!editor) {
+ return;
+ }
+ this.#swipeEditor = null;
+ editor.style.transition = "";
+ editor.style.marginTop = "";
+ }
+
@action
setToolbarPortalTarget(element) {
this.toolbarPortalTarget = element;
@@ -258,6 +335,14 @@ export default class ComposerContainer extends Component {
'with-category'
'without-category'
}}"
+ {{dSwipe
+ onDidStartSwipe=this.onSwipeStart
+ onDidSwipe=this.onSwipe
+ onDidEndSwipe=this.onSwipeEnd
+ onDidCancelSwipe=this.onSwipeCancel
+ enabled=(if this.composerRedesign true false)
+ lockBody=false
+ }}
>
<span class="composer-open-plugin-outlet-container">
<PluginOutlet
diff --git a/frontend/discourse/app/components/composer-editor.gjs b/frontend/discourse/app/components/composer-editor.gjs
index 683a20efc59..3f606fead55 100644
--- a/frontend/discourse/app/components/composer-editor.gjs
+++ b/frontend/discourse/app/components/composer-editor.gjs
@@ -323,7 +323,9 @@ export default class ComposerEditor extends Component {
this.textManipulation.putCursorAtEnd();
}
- const destroyComposerPosition = setupComposerPosition(input);
+ const destroyComposerPosition = setupComposerPosition(input, {
+ swipeToCollapse: this.siteSettings.enable_composer_redesign,
+ });
return () => {
destroyComposerPosition();
diff --git a/frontend/discourse/app/lib/composer/composer-position.js b/frontend/discourse/app/lib/composer/composer-position.js
index 46a199990be..164ab797803 100644
--- a/frontend/discourse/app/lib/composer/composer-position.js
+++ b/frontend/discourse/app/lib/composer/composer-position.js
@@ -2,7 +2,10 @@ import { later } from "@ember/runloop";
import { lock, unlock } from "discourse/lib/body-scroll-lock";
import { applyBehaviorTransformer } from "discourse/lib/transformer";
-export function setupComposerPosition(editor) {
+export function setupComposerPosition(
+ editor,
+ { swipeToCollapse = false } = {}
+) {
// This component contains two composer positioning adjustments
// for Safari iOS/iPad and Firefox on Android
// The fixes here go together with styling in base/compose.css
@@ -76,7 +79,12 @@ export function setupComposerPosition(editor) {
const selection = window.getSelection();
if (notScrollable && selection.toString() === "") {
event.preventDefault();
- event.stopPropagation();
+
+ // stopPropagation would swallow the composer's swipe-to-dismiss gesture
+ // on an ancestor; preventDefault alone still blocks the body scroll
+ if (!swipeToCollapse) {
+ event.stopPropagation();
+ }
}
});
}
diff --git a/frontend/discourse/app/lib/swipe-events.js b/frontend/discourse/app/lib/swipe-events.js
index 3aab68b9d73..89ea3f62aa9 100644
--- a/frontend/discourse/app/lib/swipe-events.js
+++ b/frontend/discourse/app/lib/swipe-events.js
@@ -47,6 +47,49 @@ export function shouldCloseMenu(e, origin) {
return false;
}
+export function dampenedOverdrag(distance) {
+ return Math.max(0, 8 * (Math.log(distance + 1) - 2));
+}
+
+export function shouldDeferSwipeToContent(swipeState, container) {
+ if (swipeState.direction === "left" || swipeState.direction === "right") {
+ return true;
+ }
+
+ let element = swipeState.originalEvent?.target;
+
+ while (element && element !== container) {
+ if (element.scrollHeight > element.clientHeight) {
+ const style = window.getComputedStyle(element);
+
+ if (style.overflowY === "auto" || style.overflowY === "scroll") {
+ // column-reverse scrollers rest at scrollTop 0 and go negative when
+ // scrolled back, so normalize scrollTop to a distance from the top
+ // edge before checking for remaining room
+ const maxScroll = element.scrollHeight - element.clientHeight;
+ const reversed =
+ style.display.includes("flex") &&
+ style.flexDirection === "column-reverse";
+ const distanceFromTop = reversed
+ ? maxScroll + element.scrollTop
+ : element.scrollTop;
+
+ if (swipeState.direction === "down" && distanceFromTop > 0) {
+ return true;
+ }
+
+ if (swipeState.direction === "up" && distanceFromTop < maxScroll) {
+ return true;
+ }
+ }
+ }
+
+ element = element.parentElement;
+ }
+
+ return false;
+}
+
/**
Swipe events is a class that allows components to detect and respond to swipe gestures
It sets up custom events for swipestart, swipeend, and swipe for beginning swipe, end swipe, and during swipe. Event returns detail.state with swipe state, and the original event.
diff --git a/frontend/discourse/app/ui-kit/d-modal.gts b/frontend/discourse/app/ui-kit/d-modal.gts
index 328dc464365..1bab35123cf 100644
--- a/frontend/discourse/app/ui-kit/d-modal.gts
+++ b/frontend/discourse/app/ui-kit/d-modal.gts
@@ -11,7 +11,11 @@ import { modifier as modifierFn } from "ember-modifier";
import htmlClass from "discourse/helpers/html-class";
import { waitForAnimationEnd } from "discourse/lib/animation-utils";
import { lock, unlock } from "discourse/lib/body-scroll-lock";
-import { getMaxAnimationTimeMs } from "discourse/lib/swipe-events";
+import {
+ dampenedOverdrag,
+ getMaxAnimationTimeMs,
+ shouldDeferSwipeToContent,
+} from "discourse/lib/swipe-events";
import type Site from "discourse/models/site";
import type AppEventsService from "discourse/services/app-events";
import type { CapabilitiesService } from "discourse/services/capabilities";
@@ -37,11 +41,6 @@ const SWIPE_VELOCITY_THRESHOLD = 0.4;
const SWIPE_CLOSE_DISTANCE_RATIO = 0.25;
const SWIPE_SETTLE_EASING = "cubic-bezier(0.32, 0.72, 0, 1)";
-// progressive resistance when the modal is dragged past its resting position
-function dampenedOverdrag(distance: number) {
- return Math.max(0, 8 * (Math.log(distance + 1) - 2));
-}
-
// The consumer's close handler. DModal invokes it with an `initiatedBy` reason, but the
// closers consumers pass (the modal service's `close`, or a float that renders DModal as its
// mobile fallback) accept their own argument shapes, so this is a deliberately broad relay type.
@@ -263,7 +262,7 @@ export default class DModal extends Component<DModalSignature> {
@action
handleSwipeStart(swipeState: SwipeState, event: Event) {
- if (this.#shouldDeferSwipeToContent(swipeState)) {
+ if (shouldDeferSwipeToContent(swipeState, this.#modalContainer)) {
event.preventDefault();
}
}
@@ -417,48 +416,6 @@ export default class DModal extends Component<DModalSignature> {
return true;
}
- // lets inner content consume the gesture instead of dragging the modal:
- // horizontal swipes, and vertical swipes started within scrollable content
- // that can still scroll in the gesture's direction
- #shouldDeferSwipeToContent(swipeState: SwipeState) {
- if (swipeState.direction === "left" || swipeState.direction === "right") {
- return true;
- }
-
- let element = swipeState.originalEvent?.target as HTMLElement | null;
-
- while (element && element !== this.#modalContainer) {
- if (element.scrollHeight > element.clientHeight) {
- const style = window.getComputedStyle(element);
-
- if (style.overflowY === "auto" || style.overflowY === "scroll") {
- // column-reverse scrollers (e.g. chat messages) rest at scrollTop 0
- // and go negative when scrolled back, so normalize scrollTop to a
- // distance from the top edge before checking for remaining room
- const maxScroll = element.scrollHeight - element.clientHeight;
- const reversed =
- style.display.includes("flex") &&
- style.flexDirection === "column-reverse";
- const distanceFromTop = reversed
- ? maxScroll + element.scrollTop
- : element.scrollTop;
-
- if (swipeState.direction === "down" && distanceFromTop > 0) {
- return true;
- }
-
- if (swipeState.direction === "up" && distanceFromTop < maxScroll) {
- return true;
- }
- }
- }
-
- element = element.parentElement;
- }
-
- return false;
- }
-
#animateBackdropOpacity(position: number) {
const backdrop = this._wrapperElement?.nextElementSibling;
diff --git a/frontend/discourse/tests/acceptance/composer-swipe-to-collapse-test.js b/frontend/discourse/tests/acceptance/composer-swipe-to-collapse-test.js
new file mode 100644
index 00000000000..a7af210cb7a
--- /dev/null
+++ b/frontend/discourse/tests/acceptance/composer-swipe-to-collapse-test.js
@@ -0,0 +1,59 @@
+import { click, focus, triggerEvent, visit } from "@ember/test-helpers";
+import { test } from "qunit";
+import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+
+async function swipeDown(selector, { to = 120 } = {}) {
+ const at = (y) => ({
+ touches: [{ clientX: 0, clientY: y }],
+ changedTouches: [{ clientX: 0, clientY: y }],
+ });
+
+ await triggerEvent(selector, "touchstart", at(0));
+ await triggerEvent(selector, "touchmove", at(to / 2));
+ await triggerEvent(selector, "touchmove", at(to));
+ // settle at the final position so the release velocity is ~0 and the
+ // dismiss decision is distance-based, not a synthetic velocity spike
+ await triggerEvent(selector, "touchmove", at(to));
+ await triggerEvent(selector, "touchend", {
+ touches: [],
+ changedTouches: [{ clientX: 0, clientY: to }],
+ });
+}
+
+acceptance("Composer - swipe to collapse", function (needs) {
+ needs.user();
+ needs.mobileView();
+ needs.settings({ enable_composer_redesign: true });
+
+ test("swiping down anywhere on the composer blurs the editor", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click(".topic-post[data-post-number='1'] button.reply");
+ await focus(".d-editor-input");
+
+ assert.dom(".d-editor-textarea-wrapper").hasClass("in-focus");
+
+ await swipeDown(".composer-footer");
+
+ assert.dom(".d-editor-input").isNotFocused();
+ });
+
+ test("swiping down from inside the editor blurs it when nothing to scroll", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click(".topic-post[data-post-number='1'] button.reply");
+ await focus(".d-editor-input");
+
+ await swipeDown(".d-editor-input");
+
+ assert.dom(".d-editor-input").isNotFocused();
+ });
+
+ test("a short drag snaps back and keeps focus", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click(".topic-post[data-post-number='1'] button.reply");
+ await focus(".d-editor-input");
+
+ await swipeDown(".composer-footer", { to: 20 });
+
+ assert.dom(".d-editor-input").isFocused();
+ });
+});
diff --git a/frontend/discourse/tests/unit/lib/swipe-events-test.js b/frontend/discourse/tests/unit/lib/swipe-events-test.js
new file mode 100644
index 00000000000..fbd568adc94
--- /dev/null
+++ b/frontend/discourse/tests/unit/lib/swipe-events-test.js
@@ -0,0 +1,80 @@
+import { module, test } from "qunit";
+import { shouldDeferSwipeToContent } from "discourse/lib/swipe-events";
+
+function swipeState(direction, target) {
+ return {
+ direction,
+ originalEvent: { target },
+ goingDown: () => direction === "down",
+ goingUp: () => direction === "up",
+ };
+}
+
+module("Unit | Lib | swipe-events | shouldDeferSwipeToContent", function () {
+ // real elements so getComputedStyle and scroll metrics behave like the browser
+ function build() {
+ const container = document.createElement("div");
+ const scroller = document.createElement("div");
+ scroller.style.overflowY = "scroll";
+ scroller.style.height = "50px";
+ const content = document.createElement("div");
+ content.style.height = "500px";
+ scroller.appendChild(content);
+ container.appendChild(scroller);
+ document.getElementById("ember-testing").appendChild(container);
+ return { container, scroller, cleanup: () => container.remove() };
+ }
+
+ test("horizontal swipes are always deferred", function (assert) {
+ const { container, cleanup } = build();
+ assert.true(
+ shouldDeferSwipeToContent(swipeState("left", container), container)
+ );
+ assert.true(
+ shouldDeferSwipeToContent(swipeState("right", container), container)
+ );
+ cleanup();
+ });
+
+ test("swipe down defers when the content is scrolled away from the top", function (assert) {
+ const { container, scroller, cleanup } = build();
+ scroller.scrollTop = 30;
+
+ assert.true(
+ shouldDeferSwipeToContent(swipeState("down", scroller), container)
+ );
+ cleanup();
+ });
+
+ test("swipe down does not defer at the top edge", function (assert) {
+ const { container, scroller, cleanup } = build();
+ scroller.scrollTop = 0;
+
+ assert.false(
+ shouldDeferSwipeToContent(swipeState("down", scroller), container)
+ );
+ cleanup();
+ });
+
+ test("swipe up defers while there is room to scroll down", function (assert) {
+ const { container, scroller, cleanup } = build();
+ scroller.scrollTop = 0;
+
+ assert.true(
+ shouldDeferSwipeToContent(swipeState("up", scroller), container)
+ );
+ cleanup();
+ });
+
+ test("does not defer when nothing between target and container scrolls", function (assert) {
+ const container = document.createElement("div");
+ const child = document.createElement("div");
+ container.appendChild(child);
+ document.getElementById("ember-testing").appendChild(container);
+
+ assert.false(
+ shouldDeferSwipeToContent(swipeState("down", child), container)
+ );
+ container.remove();
+ });
+});