Skip to content

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

FIX: improves post toolbar behavior (#33342)

Joffrey JAFFEUX2dcfb49de382
diff --git a/app/assets/javascripts/discourse/app/components/post-text-selection-toolbar.gjs b/app/assets/javascripts/discourse/app/components/post-text-selection-toolbar.gjs
index b3c86583eee..bfd3d0b9430 100644
--- a/app/assets/javascripts/discourse/app/components/post-text-selection-toolbar.gjs
+++ b/app/assets/javascripts/discourse/app/components/post-text-selection-toolbar.gjs
@@ -1,32 +1,17 @@
import Component from "@glimmer/component";
-import { tracked } from "@glimmer/tracking";
import { fn } from "@ember/helper";
import { on } from "@ember/modifier";
import { action } from "@ember/object";
import { service } from "@ember/service";
-import { modifier } from "ember-modifier";
import DButton from "discourse/components/d-button";
-import FastEdit from "discourse/components/fast-edit";
-import FastEditModal from "discourse/components/modal/fast-edit";
import PluginOutlet from "discourse/components/plugin-outlet";
import concatClass from "discourse/helpers/concat-class";
import lazyHash from "discourse/helpers/lazy-hash";
-import { ajax } from "discourse/lib/ajax";
import { getAbsoluteURL } from "discourse/lib/get-url";
import Sharing from "discourse/lib/sharing";
-import {
- clipboardCopy,
- postUrl,
- setCaretPosition,
-} from "discourse/lib/utilities";
+import { clipboardCopy, postUrl } from "discourse/lib/utilities";
import { i18n } from "discourse-i18n";
-export function fixQuotes(str) {
- // u+201c, u+201d = “ ”
- // u+2018, u+2019 = ‘ ’
- return str.replace(/[\u201C\u201D]/g, '"').replace(/[\u2018\u2019]/g, "'");
-}
-
export default class PostTextSelectionToolbar extends Component {
@service currentUser;
@service modal;
@@ -35,16 +20,6 @@ export default class PostTextSelectionToolbar extends Component {
@service appEvents;
@service toasts;
- @tracked isFastEditing = false;
-
- appEventsListeners = modifier(() => {
- this.appEvents.on("quote-button:edit", this, "toggleFastEdit");
-
- return () => {
- this.appEvents.off("quote-button:edit", this, "toggleFastEdit");
- };
- });
-
get topic() {
return this.args.data.topic;
}
@@ -98,94 +73,17 @@ export default class PostTextSelectionToolbar extends Component {
);
}
- @action
- trapEvents(event) {
- event.stopPropagation();
- }
-
@action
async copyQuoteToClipboard() {
const text = await this.args.data.buildQuote();
clipboardCopy(text);
this.toasts.success({
- duration: 3000,
+ duration: "short",
data: { message: i18n("post.quote_copied_to_clibboard") },
});
await this.args.data.hideToolbar();
}
- @action
- async closeFastEdit() {
- this.isFastEditing = false;
- await this.args.data.hideToolbar();
- }
-
- @action
- async toggleFastEdit() {
- if (this.args.data.supportsFastEdit) {
- if (this.site.desktopView) {
- this.isFastEditing = !this.isFastEditing;
- } else {
- this.modal.show(FastEditModal, {
- model: {
- initialValue: this.args.data.quoteState.buffer,
- post: this.post,
- },
- });
- this.args.data.hideToolbar();
- }
- } else {
- const result = await ajax(`/posts/${this.post.id}`);
-
- if (this.isDestroying || this.isDestroyed) {
- return;
- }
-
- let bestIndex = 0;
- const rows = result.raw.split("\n");
-
- // selecting even a part of the text of a list item will include
- // "* " at the beginning of the buffer, we remove it to be able
- // to find it in row
- const buffer = fixQuotes(
- this.args.data.quoteState.buffer.split("\n")[0].replace(/^\* /, "")
- );
-
- rows.some((row, index) => {
- if (row.length && row.includes(buffer)) {
- bestIndex = index;
- return true;
- }
- });
-
- this.args.data.editPost(this.post);
-
- document
- .querySelector("#reply-control")
- ?.addEventListener("transitionend", () => {
- const textarea = document.querySelector(".d-editor-input");
- if (!textarea || this.isDestroyed || this.isDestroying) {
- return;
- }
-
- // best index brings us to one row before as slice start from 1
- // we add 1 to be at the beginning of next line, unless we start from top
- setCaretPosition(
- textarea,
- rows.slice(0, bestIndex).join("\n").length + (bestIndex > 0 ? 1 : 0)
- );
-
- // ensures we correctly scroll to caret and reloads composer
- // if we do another selection/edit
- textarea.blur();
- textarea.focus();
- });
-
- this.args.data.hideToolbar();
- return;
- }
- }
-
@action
share(source) {
Sharing.shareSource(source, {
@@ -196,18 +94,7 @@ export default class PostTextSelectionToolbar extends Component {
}
<template>
- {{! template-lint-disable no-invalid-interactive }}
- {{! template-lint-disable no-pointer-down-event-binding }}
- <div
- {{on "mousedown" this.trapEvents}}
- {{on "mouseup" this.trapEvents}}
- class={{concatClass
- "quote-button"
- "visible"
- (if this.isFastEditing "fast-editing")
- }}
- {{this.appEventsListeners}}
- >
+ <div class={{concatClass "quote-button" "visible"}}>
<div class="buttons">
<PluginOutlet
@name="post-text-buttons"
@@ -230,7 +117,10 @@ export default class PostTextSelectionToolbar extends Component {
@label="post.quote_edit"
@title="post.quote_edit_shortcut"
class="btn-flat quote-edit-label"
- {{on "click" this.toggleFastEdit}}
+ {{on
+ "click"
+ (fn @data.toggleFastEdit this.quoteState @data.supportsFastEdit)
+ }}
/>
{{/if}}
@@ -282,14 +172,6 @@ export default class PostTextSelectionToolbar extends Component {
</div>
<div class="extra">
- {{#if this.isFastEditing}}
- <FastEdit
- @initialValue={{@data.quoteState.buffer}}
- @post={{this.post}}
- @close={{this.closeFastEdit}}
- />
- {{/if}}
-
<PluginOutlet @name="quote-button-after" @connectorTagName="div" />
</div>
</div>
diff --git a/app/assets/javascripts/discourse/app/components/post-text-selection.gjs b/app/assets/javascripts/discourse/app/components/post-text-selection.gjs
index 6dcaca3ad7c..49b50bf8d3b 100644
--- a/app/assets/javascripts/discourse/app/components/post-text-selection.gjs
+++ b/app/assets/javascripts/discourse/app/components/post-text-selection.gjs
@@ -1,25 +1,33 @@
import Component from "@glimmer/component";
-import { cached, tracked } from "@glimmer/tracking";
+import { cached } from "@glimmer/tracking";
import { action } from "@ember/object";
-import { cancel, debounce } from "@ember/runloop";
+import { cancel } from "@ember/runloop";
import { service } from "@ember/service";
import { modifier } from "ember-modifier";
+import FastEditModal from "discourse/components/modal/fast-edit";
import PostTextSelectionToolbar from "discourse/components/post-text-selection-toolbar";
+import { ajax } from "discourse/lib/ajax";
import discourseDebounce from "discourse/lib/debounce";
import { bind } from "discourse/lib/decorators";
import { INPUT_DELAY } from "discourse/lib/environment";
import escapeRegExp from "discourse/lib/escape-regexp";
import isElementInViewport from "discourse/lib/is-element-in-viewport";
import toMarkdown from "discourse/lib/to-markdown";
-import { applyValueTransformer } from "discourse/lib/transformer";
import {
getElement,
selectedNode,
selectedRange,
selectedText,
+ setCaretPosition,
} from "discourse/lib/utilities";
import virtualElementFromTextRange from "discourse/lib/virtual-element-from-text-range";
+export function fixQuotes(str) {
+ // u+201c, u+201d = “ ”
+ // u+2018, u+2019 = ‘ ’
+ return str.replace(/[\u201C\u201D]/g, '"').replace(/[\u2018\u2019]/g, "'");
+}
+
function getQuoteTitle(element) {
const titleEl = element.querySelector(".title");
if (!titleEl) {
@@ -48,162 +56,98 @@ export default class PostTextSelection extends Component {
@service site;
@service siteSettings;
@service menu;
+ @service modal;
- @tracked isSelecting = false;
- @tracked preventClose = applyValueTransformer(
- "post-text-selection-prevent-close",
- false
- );
-
- prevSelectedText;
-
- runLoopHandlers = modifier(() => {
- return () => {
- cancel(this.selectionChangeHandler);
- };
- });
-
- documentListeners = modifier(() => {
- document.addEventListener("mousedown", this.mousedown, { passive: true });
- document.addEventListener("mouseup", this.mouseup, { passive: true });
- document.addEventListener("selectionchange", this.onSelectionChanged);
-
- return () => {
- document.removeEventListener("mousedown", this.mousedown);
- document.removeEventListener("mouseup", this.mouseup);
- document.removeEventListener("selectionchange", this.onSelectionChanged);
- };
- });
-
- appEventsListeners = modifier(() => {
- this.appEvents.on("topic:current-post-scrolled", this, "handleTopicScroll");
+ setup = modifier(() => {
+ document.addEventListener("selectionchange", this.selectionChange);
this.appEvents.on("quote-button:quote", this, "insertQuote");
+ this.appEvents.on("quote-button:edit", this, "toggleHeadlessFastEdit");
return () => {
- this.appEvents.off(
- "topic:current-post-scrolled",
- this,
- "handleTopicScroll"
- );
+ cancel(this.debouncedSelectionChangeHandler);
+ document.removeEventListener("selectionchange", this.selectionChange);
this.appEvents.off("quote-button:quote", this, "insertQuote");
+ this.appEvents.off("quote-button:edit", this, "toggleHeadlessFastEdit");
+ this.menuInstance?.close();
};
});
- willDestroy() {
- super.willDestroy(...arguments);
-
- cancel(this.debouncedSelectionChanged);
- this.menuInstance?.close();
- }
-
@bind
- async hideToolbar() {
- if (this.preventClose) {
+ async toggleHeadlessFastEdit() {
+ const cooked = this.computeCurrentCooked();
+ if (!cooked) {
return;
}
- this.args.quoteState.clear();
- await this.menuInstance?.close();
- }
- async selectionChanged(options = {}) {
- if (this.isSelecting) {
- return;
- }
-
- const _selectedText = selectedText();
-
- const selection = window.getSelection();
- if (selection.isCollapsed || _selectedText === "") {
- if (!this.menuInstance?.expanded) {
- this.args.quoteState.clear();
- }
- return;
- }
-
- // avoid hard loops in quote selection unconditionally
- // this can happen if you triple click text in firefox
- // it's also generally unecessary work to go
- // through this if the selection hasn't changed
- if (
- !options.force &&
- this.menuInstance?.expanded &&
- this.prevSelectedText === _selectedText
- ) {
- return;
- }
-
- this.prevSelectedText = _selectedText;
-
- // ensure we selected content inside 1 post *only*
- let postId;
- for (let r = 0; r < selection.rangeCount; r++) {
- const range = selection.getRangeAt(r);
- const selectionStart = getElement(range.startContainer);
- const ancestor = getElement(range.commonAncestorContainer);
-
- if (!selectionStart.closest(".cooked")) {
- return await this.hideToolbar();
- }
-
- postId ||= ancestor.closest(".boxed, .reply")?.dataset?.postId;
-
- if (!ancestor.closest(".contents") || !postId) {
- return await this.hideToolbar();
- }
- }
-
- const _selectedElement = getElement(selectedNode());
- const cooked =
- _selectedElement.querySelector(".cooked") ||
- _selectedElement.closest(".cooked");
+ const quoteState = this.computeQuoteState(cooked);
+ const supportsFastEdit = this.computeSupportsFastEdit(cooked, quoteState);
- // computing markdown takes a lot of time on long posts
- // this code attempts to compute it only when we can't fast track
- let opts = {
- full:
- selectedRange().startOffset > 0
- ? false
- : _selectedText === toMarkdown(cooked.innerHTML),
- };
+ await this.toggleFastEdit(quoteState, supportsFastEdit);
+ }
- for (
- let element = _selectedElement;
- element && element.tagName !== "ARTICLE";
- element = element.parentElement
- ) {
- if (element.tagName === "ASIDE" && element.classList.contains("quote")) {
- opts.username = element.dataset.username || getQuoteTitle(element);
- opts.post = element.dataset.post;
- opts.topic = element.dataset.topic;
- break;
+ @bind
+ async toggleFastEdit(quoteState, supportsFastEdit) {
+ if (supportsFastEdit) {
+ this.modal.show(FastEditModal, {
+ model: {
+ initialValue: quoteState.buffer,
+ post: this.post,
+ },
+ });
+ } else {
+ const result = await ajax(`/posts/${this.post.id}`);
+
+ if (this.isDestroying || this.isDestroyed) {
+ return;
}
- }
- const quoteState = this.args.quoteState;
- quoteState.selected(postId, _selectedText, opts);
-
- let supportsFastEdit = this.canEditPost;
+ let bestIndex = 0;
+ const rows = result.raw.split("\n");
- const start = getElement(selection.getRangeAt(0).startContainer);
+ // selecting even a part of the text of a list item will include
+ // "* " at the beginning of the buffer, we remove it to be able
+ // to find it in row
+ const buffer = fixQuotes(
+ quoteState.buffer.split("\n")[0].replace(/^\* /, "")
+ );
- if (!start || start.closest(CSS_TO_DISABLE_FAST_EDIT)) {
- supportsFastEdit = false;
+ rows.some((row, index) => {
+ if (row.length && row.includes(buffer)) {
+ bestIndex = index;
+ return true;
+ }
+ });
+
+ this.args.editPost(this.post);
+
+ document
+ .querySelector("#reply-control")
+ ?.addEventListener("transitionend", () => {
+ const textarea = document.querySelector(".d-editor-input");
+ if (!textarea || this.isDestroyed || this.isDestroying) {
+ return;
+ }
+
+ // best index brings us to one row before as slice start from 1
+ // we add 1 to be at the beginning of next line, unless we start from top
+ setCaretPosition(
+ textarea,
+ rows.slice(0, bestIndex).join("\n").length + (bestIndex > 0 ? 1 : 0)
+ );
+
+ // ensures we correctly scroll to caret and reloads composer
+ // if we do another selection/edit
+ textarea.blur();
+ textarea.focus();
+ });
}
- if (supportsFastEdit) {
- const regexp = new RegExp(escapeRegExp(quoteState.buffer), "gi");
- const matches = cooked.innerHTML.match(regexp);
+ this.hideToolbar();
+ }
- if (
- quoteState.buffer.length === 0 ||
- quoteState.buffer.includes("|") || // tables are too complex
- quoteState.buffer.match(/\n/g) || // linebreaks are too complex
- quoteState.buffer.match(/[‚‘’„“”«»‹›™±…→←↔¶]/g) || // typopgraphic characters are too complex
- matches?.length !== 1 // duplicates are too complex
- ) {
- supportsFastEdit = false;
- }
- }
+ @bind
+ async showToolbar(cooked) {
+ const quoteState = this.computeQuoteState(cooked);
let offset = 3;
if (this.shouldRenderUnder) {
@@ -236,20 +180,19 @@ export default class PostTextSelection extends Component {
trapTab: false,
closeOnScroll: false,
data: {
+ supportsFastEdit: this.computeSupportsFastEdit(cooked, quoteState),
canEditPost: this.canEditPost,
canCopyQuote: this.canCopyQuote,
- editPost: this.args.editPost,
- supportsFastEdit,
topic: this.args.topic,
quoteState,
insertQuote: this.insertQuote,
buildQuote: this.buildQuote,
hideToolbar: this.hideToolbar,
+ toggleFastEdit: this.toggleFastEdit,
+ editPost: this.args.editPost,
},
};
- await this.menuInstance?.destroy();
-
this.menuInstance = await this.menu.show(
virtualElementFromTextRange(),
menuOptions
@@ -257,29 +200,48 @@ export default class PostTextSelection extends Component {
}
@bind
- onSelectionChanged() {
- if (this.isSelecting) {
- return;
- }
+ async hideToolbar() {
+ await this.menuInstance?.close();
+ await this.menuInstance?.destroy();
+ }
- const { isIOS, isWinphone, isAndroid } = this.capabilities;
- const wait = isIOS || isWinphone || isAndroid ? INPUT_DELAY : 25;
- this.selectionChangeHandler = discourseDebounce(
- this,
- this.selectionChanged,
- wait
+ @bind
+ async selectionChange() {
+ await this.hideToolbar();
+ this.debouncedSelectionChangeHandler = discourseDebounce(
+ this.selectionChangeHandler,
+ INPUT_DELAY
);
}
@bind
- mousedown() {
- this.isSelecting = true;
+ async selectionChangeHandler() {
+ const cooked = this.computeCurrentCooked();
+ if (cooked) {
+ await this.showToolbar(cooked);
+ } else {
+ await this.hideToolbar();
+ }
}
- @bind
- mouseup() {
- this.isSelecting = false;
- this.onSelectionChanged();
+ computeCurrentCooked() {
+ const range = selectedRange();
+
+ if (!range) {
+ return;
+ }
+
+ // ensures triple click selection works
+ if (range.endContainer?.classList?.contains?.("cooked-selection-barrier")) {
+ range.setEndBefore(range.endContainer);
+ return; // we changed the range here, so we want to go through the selection change handler again
+ }
+
+ if (!selectedText()?.length) {
+ return;
+ }
+
+ return getElement(range.commonAncestorContainer)?.closest?.(".cooked");
}
get post() {
@@ -300,21 +262,14 @@ export default class PostTextSelection extends Component {
// on Mobile, shows the bar at the end of the selection
@cached
get shouldRenderUnder() {
- const { isIOS, isAndroid, isOpera } = this.capabilities;
- return this.site.isMobileDevice || isIOS || isAndroid || isOpera;
- }
-
- @action
- handleTopicScroll() {
- if (this.site.mobileView) {
- this.debouncedSelectionChanged = debounce(
- this,
- this.selectionChanged,
- { force: true },
- 250,
- false
- );
- }
+ const { isIOS, isAndroid, isOpera, isFirefox, touch } = this.capabilities;
+ return (
+ this.site.isMobileDevice ||
+ isIOS ||
+ isAndroid ||
+ isOpera ||
+ (touch && isFirefox)
+ );
}
@action
@@ -328,11 +283,67 @@ export default class PostTextSelection extends Component {
return await this.args.buildQuoteMarkdown();
}
+ computeSupportsFastEdit(cooked, quoteState) {
+ const selection = window.getSelection();
+ let supportsFastEdit = this.canEditPost;
+
+ const start = getElement(selection.getRangeAt(0).startContainer);
+
+ if (!start || start.closest(CSS_TO_DISABLE_FAST_EDIT)) {
+ supportsFastEdit = false;
+ }
+
+ if (supportsFastEdit) {
+ const regexp = new RegExp(escapeRegExp(quoteState.buffer), "gi");
+ const matches = cooked.innerHTML.match(regexp);
+
+ if (
+ quoteState.buffer.length === 0 ||
+ quoteState.buffer.includes("|") || // tables are too complex
+ quoteState.buffer.match(/\n/g) || // linebreaks are too complex
+ quoteState.buffer.match(/[‚‘’„“”«»‹›™±…→←↔¶]/g) || // typopgraphic characters are too complex
+ matches?.length !== 1 // duplicates are too complex
+ ) {
+ supportsFastEdit = false;
+ }
+ }
+
+ return supportsFastEdit;
+ }
+
+ computeQuoteState(cooked) {
+ const _selectedText = selectedText();
+ const _selectedElement = getElement(selectedNode());
+ const postId = cooked.closest(".boxed, .reply")?.dataset?.postId;
+
+ // computing markdown takes a lot of time on long posts
+ // this code attempts to compute it only when we can't fast track
+ let opts = {
+ full:
+ selectedRange().startOffset > 0
+ ? false
+ : _selectedText === toMarkdown(cooked.innerHTML),
+ };
+
+ for (
+ let element = _selectedElement;
+ element && element.tagName !== "ARTICLE";
+ element = element.parentElement
+ ) {
+ if (element.tagName === "ASIDE" && element.classList.contains("quote")) {
+ opts.username = element.dataset.username || getQuoteTitle(element);
+ opts.post = element.dataset.post;
+ opts.topic = element.dataset.topic;
+ break;
+ }
+ }
+
+ const quoteState = this.args.quoteState;
+ quoteState.selected(postId, _selectedText, opts);
+ return quoteState;
+ }
+
<template>
- <div
- {{this.documentListeners}}
- {{this.appEventsListeners}}
- {{this.runLoopHandlers}}
- ></div>
+ <div {{this.setup}}></div>
</template>
}
diff --git a/app/assets/javascripts/discourse/app/lib/transformer/registry.js b/app/assets/javascripts/discourse/app/lib/transformer/registry.js
index 91027444789..b6a977452c5 100644
--- a/app/assets/javascripts/discourse/app/lib/transformer/registry.js
+++ b/app/assets/javascripts/discourse/app/lib/transformer/registry.js
@@ -53,7 +53,6 @@ export const VALUE_TRANSFORMERS = Object.freeze([
"post-small-action-class",
"post-small-action-custom-component",
"post-small-action-icon",
- "post-text-selection-prevent-close",
"poster-name-class",
"site-setting-enable-welcome-banner",
"site-setting-search-experience",
diff --git a/app/assets/javascripts/discourse/app/lib/utilities.js b/app/assets/javascripts/discourse/app/lib/utilities.js
index 54b81bdf8f8..2e30ad2dc1a 100644
--- a/app/assets/javascripts/discourse/app/lib/utilities.js
+++ b/app/assets/javascripts/discourse/app/lib/utilities.js
@@ -122,12 +122,6 @@ export function selectedText() {
? range.commonAncestorContainer
: range.commonAncestorContainer.parentElement;
- // ensure we never quote text in the post menu area
- const postMenuArea = ancestor.querySelector(".post-menu-area");
- if (postMenuArea) {
- range.setEndBefore(postMenuArea);
- }
-
const oneboxTest = ancestor.closest("aside.onebox[data-onebox-src]");
const codeBlockTest = ancestor.closest("pre");
if (codeBlockTest) {
diff --git a/app/assets/stylesheets/common/base/topic-post.scss b/app/assets/stylesheets/common/base/topic-post.scss
index 894a08be038..0fe63e800df 100644
--- a/app/assets/stylesheets/common/base/topic-post.scss
+++ b/app/assets/stylesheets/common/base/topic-post.scss
@@ -742,10 +742,6 @@ aside.quote {
opacity: 0.4;
}
-.fk-d-menu[data-identifier="post-text-selection-toolbar"] {
- @include user-select(none);
-}
-
.quote-button {
flex-direction: column;