Skip to content

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

FIX: Video thumbnail uploads interfering with subsequent uploads (#23216)

Martin Brennane8a6079c29f1
diff --git a/app/assets/javascripts/discourse/app/components/composer-editor.js b/app/assets/javascripts/discourse/app/components/composer-editor.js
index fefde08feb3..cee2e5f20d8 100644
--- a/app/assets/javascripts/discourse/app/components/composer-editor.js
+++ b/app/assets/javascripts/discourse/app/components/composer-editor.js
@@ -27,7 +27,6 @@ import discourseLater from "discourse-common/lib/later";
import Component from "@ember/component";
import Composer from "discourse/models/composer";
import ComposerUploadUppy from "discourse/mixins/composer-upload-uppy";
-import ComposerVideoThumbnailUppy from "discourse/mixins/composer-video-thumbnail-uppy";
import EmberObject from "@ember/object";
import I18n from "I18n";
import { ajax } from "discourse/lib/ajax";
@@ -100,444 +99,449 @@ export function addComposerUploadMarkdownResolver(resolver) {
export function cleanUpComposerUploadMarkdownResolver() {
uploadMarkdownResolvers = [];
}
-export default Component.extend(
- ComposerUploadUppy,
- ComposerVideoThumbnailUppy,
- {
- classNameBindings: ["showToolbar:toolbar-visible", ":wmd-controls"],
-
- editorClass: ".d-editor",
- fileUploadElementId: "file-uploader",
- mobileFileUploaderId: "mobile-file-upload",
-
- composerEventPrefix: "composer",
- uploadType: "composer",
- uppyId: "composer-editor-uppy",
- composerModel: alias("composer"),
- composerModelContentKey: "reply",
- editorInputClass: ".d-editor-input",
- shouldBuildScrollMap: true,
- scrollMap: null,
- processPreview: true,
-
- uploadMarkdownResolvers,
- uploadPreProcessors,
- uploadHandlers,
-
- init() {
- this._super(...arguments);
- this.warnedCannotSeeMentions = [];
- this.warnedGroupMentions = [];
- },
-
- @discourseComputed("composer.requiredCategoryMissing")
- replyPlaceholder(requiredCategoryMissing) {
- if (requiredCategoryMissing) {
- return "composer.reply_placeholder_choose_category";
- } else {
- const key = authorizesOneOrMoreImageExtensions(
- this.currentUser.staff,
- this.siteSettings
- )
- ? "reply_placeholder"
- : "reply_placeholder_no_images";
- return `composer.${key}`;
- }
- },
-
- @discourseComputed
- showLink() {
- return (
- this.currentUser && this.currentUser.link_posting_access !== "none"
- );
- },
-
- @observes("focusTarget")
- setFocus() {
- if (this.focusTarget === "editor") {
- putCursorAtEnd(this.element.querySelector("textarea"));
- }
- },
-
- @discourseComputed
- markdownOptions() {
- return {
- previewing: true,
-
- formatUsername,
+export default Component.extend(ComposerUploadUppy, {
+ classNameBindings: ["showToolbar:toolbar-visible", ":wmd-controls"],
+
+ editorClass: ".d-editor",
+ fileUploadElementId: "file-uploader",
+ mobileFileUploaderId: "mobile-file-upload",
+
+ composerEventPrefix: "composer",
+ uploadType: "composer",
+ uppyId: "composer-editor-uppy",
+ composerModel: alias("composer"),
+ composerModelContentKey: "reply",
+ editorInputClass: ".d-editor-input",
+ shouldBuildScrollMap: true,
+ scrollMap: null,
+ processPreview: true,
+
+ uploadMarkdownResolvers,
+ uploadPreProcessors,
+ uploadHandlers,
+
+ init() {
+ this._super(...arguments);
+ this.warnedCannotSeeMentions = [];
+ this.warnedGroupMentions = [];
+ },
+
+ @discourseComputed("composer.requiredCategoryMissing")
+ replyPlaceholder(requiredCategoryMissing) {
+ if (requiredCategoryMissing) {
+ return "composer.reply_placeholder_choose_category";
+ } else {
+ const key = authorizesOneOrMoreImageExtensions(
+ this.currentUser.staff,
+ this.siteSettings
+ )
+ ? "reply_placeholder"
+ : "reply_placeholder_no_images";
+ return `composer.${key}`;
+ }
+ },
+
+ @discourseComputed
+ showLink() {
+ return this.currentUser && this.currentUser.link_posting_access !== "none";
+ },
+
+ @observes("focusTarget")
+ setFocus() {
+ if (this.focusTarget === "editor") {
+ putCursorAtEnd(this.element.querySelector("textarea"));
+ }
+ },
+
+ @discourseComputed
+ markdownOptions() {
+ return {
+ previewing: true,
+
+ formatUsername,
+
+ lookupAvatarByPostNumber: (postNumber, topicId) => {
+ const topic = this.topic;
+ if (!topic) {
+ return;
+ }
- lookupAvatarByPostNumber: (postNumber, topicId) => {
- const topic = this.topic;
- if (!topic) {
- return;
+ const posts = topic.get("postStream.posts");
+ if (posts && topicId === topic.get("id")) {
+ const quotedPost = posts.findBy("post_number", postNumber);
+ if (quotedPost) {
+ return tinyAvatar(quotedPost.get("avatar_template"));
}
+ }
+ },
- const posts = topic.get("postStream.posts");
- if (posts && topicId === topic.get("id")) {
- const quotedPost = posts.findBy("post_number", postNumber);
- if (quotedPost) {
- return tinyAvatar(quotedPost.get("avatar_template"));
- }
- }
- },
+ lookupPrimaryUserGroupByPostNumber: (postNumber, topicId) => {
+ const topic = this.topic;
+ if (!topic) {
+ return;
+ }
- lookupPrimaryUserGroupByPostNumber: (postNumber, topicId) => {
- const topic = this.topic;
- if (!topic) {
- return;
+ const posts = topic.get("postStream.posts");
+ if (posts && topicId === topic.get("id")) {
+ const quotedPost = posts.findBy("post_number", postNumber);
+ if (quotedPost) {
+ return quotedPost.primary_group_name;
}
+ }
+ },
- const posts = topic.get("postStream.posts");
- if (posts && topicId === topic.get("id")) {
- const quotedPost = posts.findBy("post_number", postNumber);
- if (quotedPost) {
- return quotedPost.primary_group_name;
- }
- }
+ hashtagTypesInPriorityOrder:
+ this.site.hashtag_configurations["topic-composer"],
+ hashtagIcons: this.site.hashtag_icons,
+ };
+ },
+
+ @bind
+ _afterMentionComplete(value) {
+ this.composer.set("reply", value);
+
+ // ensures textarea scroll position is correct
+ schedule("afterRender", () => {
+ const input = this.element.querySelector(".d-editor-input");
+ input?.blur();
+ input?.focus();
+ });
+ },
+
+ @on("didInsertElement")
+ _composerEditorInit() {
+ const $input = $(this.element.querySelector(".d-editor-input"));
+
+ if (this.siteSettings.enable_mentions) {
+ $input.autocomplete({
+ template: findRawTemplate("user-selector-autocomplete"),
+ dataSource: (term) => {
+ destroyUserStatuses();
+ return userSearch({
+ term,
+ topicId: this.topic?.id,
+ categoryId: this.topic?.category_id || this.composer?.categoryId,
+ includeGroups: true,
+ }).then((result) => {
+ initUserStatusHtml(result.users);
+ return result;
+ });
},
-
- hashtagTypesInPriorityOrder:
- this.site.hashtag_configurations["topic-composer"],
- hashtagIcons: this.site.hashtag_icons,
- };
- },
-
- @bind
- _afterMentionComplete(value) {
- this.composer.set("reply", value);
-
- // ensures textarea scroll position is correct
- schedule("afterRender", () => {
- const input = this.element.querySelector(".d-editor-input");
- input?.blur();
- input?.focus();
+ onRender: (options) => {
+ renderUserStatusHtml(options);
+ },
+ key: "@",
+ transformComplete: (v) => v.username || v.name,
+ afterComplete: this._afterMentionComplete,
+ triggerRule: (textarea) =>
+ !inCodeBlock(textarea.value, caretPosition(textarea)),
+ onClose: destroyUserStatuses,
});
- },
-
- @on("didInsertElement")
- _composerEditorInit() {
- const $input = $(this.element.querySelector(".d-editor-input"));
-
- if (this.siteSettings.enable_mentions) {
- $input.autocomplete({
- template: findRawTemplate("user-selector-autocomplete"),
- dataSource: (term) => {
- destroyUserStatuses();
- return userSearch({
- term,
- topicId: this.topic?.id,
- categoryId: this.topic?.category_id || this.composer?.categoryId,
- includeGroups: true,
- }).then((result) => {
- initUserStatusHtml(result.users);
- return result;
- });
- },
- onRender: (options) => {
- renderUserStatusHtml(options);
- },
- key: "@",
- transformComplete: (v) => v.username || v.name,
- afterComplete: this._afterMentionComplete,
- triggerRule: (textarea) =>
- !inCodeBlock(textarea.value, caretPosition(textarea)),
- onClose: destroyUserStatuses,
- });
- }
-
- this.element
- .querySelector(".d-editor-input")
- ?.addEventListener("scroll", this._throttledSyncEditorAndPreviewScroll);
-
- // Focus on the body unless we have a title
- if (!this.get("composer.canEditTitle")) {
- putCursorAtEnd(this.element.querySelector(".d-editor-input"));
+ }
+
+ this.element
+ .querySelector(".d-editor-input")
+ ?.addEventListener("scroll", this._throttledSyncEditorAndPreviewScroll);
+
+ // Focus on the body unless we have a title
+ if (!this.get("composer.canEditTitle")) {
+ putCursorAtEnd(this.element.querySelector(".d-editor-input"));
+ }
+
+ if (this.allowUpload) {
+ this._bindUploadTarget();
+ this._bindMobileUploadButton();
+ }
+
+ this.appEvents.trigger(`${this.composerEventPrefix}:will-open`);
+ },
+
+ @discourseComputed(
+ "composer.reply",
+ "composer.replyLength",
+ "composer.missingReplyCharacters",
+ "composer.minimumPostLength",
+ "lastValidatedAt"
+ )
+ validation(
+ reply,
+ replyLength,
+ missingReplyCharacters,
+ minimumPostLength,
+ lastValidatedAt
+ ) {
+ const postType = this.get("composer.post.post_type");
+ if (postType === this.site.get("post_types.small_action")) {
+ return;
+ }
+
+ let reason;
+ if (replyLength < 1) {
+ reason = I18n.t("composer.error.post_missing");
+ } else if (missingReplyCharacters > 0) {
+ reason = I18n.t("composer.error.post_length", {
+ count: minimumPostLength,
+ });
+ const tl = this.get("currentUser.trust_level");
+ if (tl === 0 || tl === 1) {
+ reason +=
+ "<br/>" +
+ I18n.t("composer.error.try_like", {
+ heart: iconHTML("heart", {
+ label: I18n.t("likes_lowercase", { count: 1 }),
+ }),
+ });
}
+ }
- if (this.allowUpload) {
- this._bindUploadTarget();
- this._bindMobileUploadButton();
- }
+ if (reason) {
+ return EmberObject.create({
+ failed: true,
+ reason,
+ lastShownAt: lastValidatedAt,
+ });
+ }
+ },
- this.appEvents.trigger(`${this.composerEventPrefix}:will-open`);
- },
+ _resetShouldBuildScrollMap() {
+ this.set("shouldBuildScrollMap", true);
+ },
- @discourseComputed(
- "composer.reply",
- "composer.replyLength",
- "composer.missingReplyCharacters",
- "composer.minimumPostLength",
- "lastValidatedAt"
- )
- validation(
- reply,
- replyLength,
- missingReplyCharacters,
- minimumPostLength,
- lastValidatedAt
- ) {
- const postType = this.get("composer.post.post_type");
- if (postType === this.site.get("post_types.small_action")) {
- return;
- }
+ @bind
+ _handleInputInteraction(event) {
+ const preview = this.element.querySelector(".d-editor-preview-wrapper");
- let reason;
- if (replyLength < 1) {
- reason = I18n.t("composer.error.post_missing");
- } else if (missingReplyCharacters > 0) {
- reason = I18n.t("composer.error.post_length", {
- count: minimumPostLength,
- });
- const tl = this.get("currentUser.trust_level");
- if (tl === 0 || tl === 1) {
- reason +=
- "<br/>" +
- I18n.t("composer.error.try_like", {
- heart: iconHTML("heart", {
- label: I18n.t("likes_lowercase", { count: 1 }),
- }),
- });
+ if (!$(preview).is(":visible")) {
+ return;
+ }
+
+ preview.removeEventListener("scroll", this._handleInputOrPreviewScroll);
+ event.target.addEventListener("scroll", this._handleInputOrPreviewScroll);
+ },
+
+ @bind
+ _handleInputOrPreviewScroll(event) {
+ this._syncScroll(
+ this._syncEditorAndPreviewScroll,
+ $(event.target),
+ $(this.element.querySelector(".d-editor-preview-wrapper"))
+ );
+ },
+
+ @bind
+ _handlePreviewInteraction(event) {
+ this.element
+ .querySelector(".d-editor-input")
+ ?.removeEventListener("scroll", this._handleInputOrPreviewScroll);
+
+ event.target?.addEventListener("scroll", this._handleInputOrPreviewScroll);
+ },
+
+ _syncScroll($callback, $input, $preview) {
+ if (!this.scrollMap || this.shouldBuildScrollMap) {
+ this.set("scrollMap", this._buildScrollMap($input, $preview));
+ this.set("shouldBuildScrollMap", false);
+ }
+
+ throttle(this, $callback, $input, $preview, this.scrollMap, 20);
+ },
+
+ // Adapted from https://github.com/markdown-it/markdown-it.github.io
+ _buildScrollMap($input, $preview) {
+ let sourceLikeDiv = $("<div />")
+ .css({
+ position: "absolute",
+ height: "auto",
+ visibility: "hidden",
+ width: $input[0].clientWidth,
+ "font-size": $input.css("font-size"),
+ "font-family": $input.css("font-family"),
+ "line-height": $input.css("line-height"),
+ "white-space": $input.css("white-space"),
+ })
+ .appendTo("body");
+
+ const linesMap = [];
+ let numberOfLines = 0;
+
+ $input
+ .val()
+ .split("\n")
+ .forEach((text) => {
+ linesMap.push(numberOfLines);
+
+ if (text.length === 0) {
+ numberOfLines++;
+ } else {
+ sourceLikeDiv.text(text);
+
+ let height;
+ let lineHeight;
+ height = parseFloat(sourceLikeDiv.css("height"));
+ lineHeight = parseFloat(sourceLikeDiv.css("line-height"));
+ numberOfLines += Math.round(height / lineHeight);
}
- }
+ });
- if (reason) {
- return EmberObject.create({
- failed: true,
- reason,
- lastShownAt: lastValidatedAt,
- });
+ linesMap.push(numberOfLines);
+ sourceLikeDiv.remove();
+
+ const previewOffsetTop = $preview.offset().top;
+ const offset =
+ $preview.scrollTop() -
+ previewOffsetTop -
+ ($input.offset().top - previewOffsetTop);
+ const nonEmptyList = [];
+ const scrollMap = [];
+ for (let i = 0; i < numberOfLines; i++) {
+ scrollMap.push(-1);
+ }
+
+ nonEmptyList.push(0);
+ scrollMap[0] = 0;
+
+ $preview.find(".preview-sync-line").each((_, element) => {
+ let $element = $(element);
+ let lineNumber = $element.data("line-number");
+ let linesToTop = linesMap[lineNumber];
+ if (linesToTop !== 0) {
+ nonEmptyList.push(linesToTop);
}
- },
+ scrollMap[linesToTop] = Math.round($element.offset().top + offset);
+ });
- _resetShouldBuildScrollMap() {
- this.set("shouldBuildScrollMap", true);
- },
+ nonEmptyList.push(numberOfLines);
+ scrollMap[numberOfLines] = $preview[0].scrollHeight;
- @bind
- _handleInputInteraction(event) {
- const preview = this.element.querySelector(".d-editor-preview-wrapper");
+ let position = 0;
- if (!$(preview).is(":visible")) {
- return;
+ for (let i = 1; i < numberOfLines; i++) {
+ if (scrollMap[i] !== -1) {
+ position++;
+ continue;
}
- preview.removeEventListener("scroll", this._handleInputOrPreviewScroll);
- event.target.addEventListener("scroll", this._handleInputOrPreviewScroll);
- },
+ let top = nonEmptyList[position];
+ let bottom = nonEmptyList[position + 1];
- @bind
- _handleInputOrPreviewScroll(event) {
- this._syncScroll(
- this._syncEditorAndPreviewScroll,
- $(event.target),
- $(this.element.querySelector(".d-editor-preview-wrapper"))
- );
- },
+ scrollMap[i] = (
+ (scrollMap[bottom] * (i - top) + scrollMap[top] * (bottom - i)) /
+ (bottom - top)
+ ).toFixed(2);
+ }
- @bind
- _handlePreviewInteraction(event) {
- this.element
- .querySelector(".d-editor-input")
- ?.removeEventListener("scroll", this._handleInputOrPreviewScroll);
+ return scrollMap;
+ },
- event.target?.addEventListener(
- "scroll",
- this._handleInputOrPreviewScroll
- );
- },
-
- _syncScroll($callback, $input, $preview) {
- if (!this.scrollMap || this.shouldBuildScrollMap) {
- this.set("scrollMap", this._buildScrollMap($input, $preview));
- this.set("shouldBuildScrollMap", false);
- }
+ @bind
+ _throttledSyncEditorAndPreviewScroll(event) {
+ const $preview = $(this.element.querySelector(".d-editor-preview-wrapper"));
- throttle(this, $callback, $input, $preview, this.scrollMap, 20);
- },
+ throttle(
+ this,
+ this._syncEditorAndPreviewScroll,
+ $(event.target),
+ $preview,
+ 20
+ );
+ },
- // Adapted from https://github.com/markdown-it/markdown-it.github.io
- _buildScrollMap($input, $preview) {
- let sourceLikeDiv = $("<div />")
- .css({
- position: "absolute",
- height: "auto",
- visibility: "hidden",
- width: $input[0].clientWidth,
- "font-size": $input.css("font-size"),
- "font-family": $input.css("font-family"),
- "line-height": $input.css("line-height"),
- "white-space": $input.css("white-space"),
- })
- .appendTo("body");
-
- const linesMap = [];
- let numberOfLines = 0;
-
- $input
- .val()
- .split("\n")
- .forEach((text) => {
- linesMap.push(numberOfLines);
-
- if (text.length === 0) {
- numberOfLines++;
- } else {
- sourceLikeDiv.text(text);
-
- let height;
- let lineHeight;
- height = parseFloat(sourceLikeDiv.css("height"));
- lineHeight = parseFloat(sourceLikeDiv.css("line-height"));
- numberOfLines += Math.round(height / lineHeight);
- }
- });
+ _syncEditorAndPreviewScroll($input, $preview) {
+ if (!$input) {
+ return;
+ }
- linesMap.push(numberOfLines);
- sourceLikeDiv.remove();
-
- const previewOffsetTop = $preview.offset().top;
- const offset =
- $preview.scrollTop() -
- previewOffsetTop -
- ($input.offset().top - previewOffsetTop);
- const nonEmptyList = [];
- const scrollMap = [];
- for (let i = 0; i < numberOfLines; i++) {
- scrollMap.push(-1);
- }
+ if ($input.scrollTop() === 0) {
+ $preview.scrollTop(0);
+ return;
+ }
- nonEmptyList.push(0);
- scrollMap[0] = 0;
+ const inputHeight = $input[0].scrollHeight;
+ const previewHeight = $preview[0].scrollHeight;
- $preview.find(".preview-sync-line").each((_, element) => {
- let $element = $(element);
- let lineNumber = $element.data("line-number");
- let linesToTop = linesMap[lineNumber];
- if (linesToTop !== 0) {
- nonEmptyList.push(linesToTop);
- }
- scrollMap[linesToTop] = Math.round($element.offset().top + offset);
+ if ($input.height() + $input.scrollTop() + 100 > inputHeight) {
+ // cheat, special case for bottom
+ $preview.scrollTop(previewHeight);
+ return;
+ }
+
+ const scrollPosition = $input.scrollTop();
+ const factor = previewHeight / inputHeight;
+ const desired = scrollPosition * factor;
+ $preview.scrollTop(desired + 50);
+ },
+
+ _renderUnseenMentions(preview, unseen) {
+ fetchUnseenMentions({
+ names: unseen,
+ topicId: this.get("composer.topic.id"),
+ allowedNames: this.get("composer.targetRecipients")?.split(","),
+ }).then((response) => {
+ linkSeenMentions(preview, this.siteSettings);
+ this._warnMentionedGroups(preview);
+ this._warnCannotSeeMention(preview);
+ this._warnHereMention(response.here_count);
+ });
+ },
+
+ _renderUnseenHashtags(preview) {
+ const hashtagContext = this.site.hashtag_configurations["topic-composer"];
+ const unseen = linkSeenHashtagsInContext(hashtagContext, preview);
+ if (unseen.length > 0) {
+ fetchUnseenHashtagsInContext(hashtagContext, unseen).then(() => {
+ linkSeenHashtagsInContext(hashtagContext, preview);
});
+ }
+ },
- nonEmptyList.push(numberOfLines);
- scrollMap[numberOfLines] = $preview[0].scrollHeight;
-
- let position = 0;
-
- for (let i = 1; i < numberOfLines; i++) {
- if (scrollMap[i] !== -1) {
- position++;
- continue;
- }
-
- let top = nonEmptyList[position];
- let bottom = nonEmptyList[position + 1];
-
- scrollMap[i] = (
- (scrollMap[bottom] * (i - top) + scrollMap[top] * (bottom - i)) /
- (bottom - top)
- ).toFixed(2);
- }
-
- return scrollMap;
- },
-
- @bind
- _throttledSyncEditorAndPreviewScroll(event) {
- const $preview = $(
- this.element.querySelector(".d-editor-preview-wrapper")
- );
-
- throttle(
- this,
- this._syncEditorAndPreviewScroll,
- $(event.target),
- $preview,
- 20
- );
- },
-
- _syncEditorAndPreviewScroll($input, $preview) {
- if (!$input) {
- return;
- }
-
- if ($input.scrollTop() === 0) {
- $preview.scrollTop(0);
- return;
- }
+ @debounce(2000)
+ _warnMentionedGroups(preview) {
+ schedule("afterRender", () => {
+ preview
+ .querySelectorAll(".mention-group[data-mentionable-user-count]")
+ .forEach((mention) => {
+ const { name } = mention.dataset;
+ if (
+ this.warnedGroupMentions.includes(name) ||
+ this._isInQuote(mention)
+ ) {
+ return;
+ }
- const inputHeight = $input[0].scrollHeight;
- const previewHeight = $preview[0].scrollHeight;
+ this.warnedGroupMentions.push(name);
+ this.groupsMentioned({
+ name,
+ userCount: mention.dataset.mentionableUserCount,
+ maxMentions: mention.dataset.maxMentions,
+ });
+ });
+ });
+ },
+
+ // add a delay to allow for typing, so you don't open the warning right away
+ // previously we would warn after @bob even if you were about to mention @bob2
+ @debounce(2000)
+ _warnCannotSeeMention(preview) {
+ if (this.composer.draftKey === Composer.NEW_PRIVATE_MESSAGE_KEY) {
+ return;
+ }
- if ($input.height() + $input.scrollTop() + 100 > inputHeight) {
- // cheat, special case for bottom
- $preview.scrollTop(previewHeight);
+ preview.querySelectorAll(".mention[data-reason]").forEach((mention) => {
+ const { name } = mention.dataset;
+ if (this.warnedCannotSeeMentions.includes(name)) {
return;
}
- const scrollPosition = $input.scrollTop();
- const factor = previewHeight / inputHeight;
- const desired = scrollPosition * factor;
- $preview.scrollTop(desired + 50);
- },
-
- _renderUnseenMentions(preview, unseen) {
- fetchUnseenMentions({
- names: unseen,
- topicId: this.get("composer.topic.id"),
- allowedNames: this.get("composer.targetRecipients")?.split(","),
- }).then((response) => {
- linkSeenMentions(preview, this.siteSettings);
- this._warnMentionedGroups(preview);
- this._warnCannotSeeMention(preview);
- this._warnHereMention(response.here_count);
+ this.warnedCannotSeeMentions.push(name);
+ this.cannotSeeMention({
+ name,
+ reason: mention.dataset.reason,
});
- },
-
- _renderUnseenHashtags(preview) {
- const hashtagContext = this.site.hashtag_configurations["topic-composer"];
- const unseen = linkSeenHashtagsInContext(hashtagContext, preview);
- if (unseen.length > 0) {
- fetchUnseenHashtagsInContext(hashtagContext, unseen).then(() => {
- linkSeenHashtagsInContext(hashtagContext, preview);
- });
- }
- },
+ });
- @debounce(2000)
- _warnMentionedGroups(preview) {
- schedule("afterRender", () => {
- preview
- .querySelectorAll(".mention-group[data-mentionable-user-count]")
- .forEach((mention) => {
- const { name } = mention.dataset;
- if (
- this.warnedGroupMentions.includes(name) ||
- this._isInQuote(mention)
- ) {
- return;
- }
-
- this.warnedGroupMentions.push(name);
- this.groupsMentioned({
- name,
- userCount: mention.dataset.mentionableUserCount,
- maxMentions: mention.dataset.maxMentions,
- });
- });
- });
- },
-
- // add a delay to allow for typing, so you don't open the warning right away
- // previously we would warn after @bob even if you were about to mention @bob2
- @debounce(2000)
- _warnCannotSeeMention(preview) {
- if (this.composer.draftKey === Composer.NEW_PRIVATE_MESSAGE_KEY) {
- return;
- }
-
- preview.querySelectorAll(".mention[data-reason]").forEach((mention) => {
+ preview
+ .querySelectorAll(".mention-group[data-reason]")
+ .forEach((mention) => {
const { name } = mention.dataset;
if (this.warnedCannotSeeMentions.includes(name)) {
return;
@@ -547,430 +551,404 @@ export default Component.extend(
this.cannotSeeMention({
name,
reason: mention.dataset.reason,
+ notifiedCount: mention.dataset.notifiedUserCount,
+ isGroup: true,
});
});
+ },
- preview
- .querySelectorAll(".mention-group[data-reason]")
- .forEach((mention) => {
- const { name } = mention.dataset;
- if (this.warnedCannotSeeMentions.includes(name)) {
- return;
- }
+ _warnHereMention(hereCount) {
+ if (!hereCount || hereCount === 0) {
+ return;
+ }
- this.warnedCannotSeeMentions.push(name);
- this.cannotSeeMention({
- name,
- reason: mention.dataset.reason,
- notifiedCount: mention.dataset.notifiedUserCount,
- isGroup: true,
- });
- });
- },
+ this.hereMention(hereCount);
+ },
- _warnHereMention(hereCount) {
- if (!hereCount || hereCount === 0) {
- return;
- }
+ @bind
+ _handleImageScaleButtonClick(event) {
+ if (!event.target.classList.contains("scale-btn")) {
+ return;
+ }
- this.hereMention(hereCount);
- },
+ const index = parseInt(
+ event.target.closest(".button-wrapper").dataset.imageIndex,
+ 10
+ );
- @bind
- _handleImageScaleButtonClick(event) {
- if (!event.target.classList.contains("scale-btn")) {
- return;
- }
+ const scale = event.target.dataset.scale;
+ const matchingPlaceholder =
+ this.get("composer.reply").match(IMAGE_MARKDOWN_REGEX);
- const index = parseInt(
- event.target.closest(".button-wrapper").dataset.imageIndex,
- 10
- );
+ if (matchingPlaceholder) {
+ const match = matchingPlaceholder[index];
- const scale = event.target.dataset.scale;
- const matchingPlaceholder =
- this.get("composer.reply").match(IMAGE_MARKDOWN_REGEX);
-
- if (matchingPlaceholder) {
- const match = matchingPlaceholder[index];
-
- if (match) {
- const replacement = match.replace(
- IMAGE_MARKDOWN_REGEX,
- `![$1|$2, ${scale}%$4]($5)`
- );
-
- this.appEvents.trigger(
- `${this.composerEventPrefix}:replace-text`,
- matchingPlaceholder[index],
- replacement,
- { regex: IMAGE_MARKDOWN_REGEX, index }
- );
- }
- }
+ if (match) {
+ const replacement = match.replace(
+ IMAGE_MARKDOWN_REGEX,
+ `![$1|$2, ${scale}%$4]($5)`
+ );
- event.preventDefault();
- return;
- },
+ this.appEvents.trigger(
+ `${this.composerEventPrefix}:replace-text`,
+ matchingPlaceholder[index],
+ replacement,
+ { regex: IMAGE_MARKDOWN_REGEX, index }
+ );
+ }
+ }
- resetImageControls(buttonWrapper) {
- const imageResize = buttonWrapper.querySelector(".scale-btn-container");
- const imageDelete = buttonWrapper.querySelector(".delete-image-button");
+ event.preventDefault();
+ return;
+ },
- const readonlyContainer = buttonWrapper.querySelector(
- ".alt-text-readonly-container"
- );
- const editContainer = buttonWrapper.querySelector(
- ".alt-text-edit-container"
- );
+ resetImageControls(buttonWrapper) {
+ const imageResize = buttonWrapper.querySelector(".scale-btn-container");
+ const imageDelete = buttonWrapper.querySelector(".delete-image-button");
- imageResize.removeAttribute("hidden");
- imageDelete.removeAttribute("hidden");
+ const readonlyContainer = buttonWrapper.querySelector(
+ ".alt-text-readonly-container"
+ );
+ const editContainer = buttonWrapper.querySelector(
+ ".alt-text-edit-container"
+ );
- readonlyContainer.removeAttribute("hidden");
- buttonWrapper.removeAttribute("editing");
- editContainer.setAttribute("hidden", "true");
- },
+ imageResize.removeAttribute("hidden");
+ imageDelete.removeAttribute("hidden");
+
+ readonlyContainer.removeAttribute("hidden");
+ buttonWrapper.removeAttribute("editing");
+ editContainer.setAttribute("hidden", "true");
+ },
+
+ commitAltText(buttonWrapper) {
+ const index = parseInt(buttonWrapper.getAttribute("data-image-index"), 10);
+ const matchingPlaceholder =
+ this.get("composer.reply").match(IMAGE_MARKDOWN_REGEX);
+ const match = matchingPlaceholder[index];
+ const input = buttonWrapper.querySelector("input.alt-text-input");
+ const replacement = match.replace(
+ IMAGE_MARKDOWN_REGEX,
+ `![${input.value}|$2$3$4]($5)`
+ );
- commitAltText(buttonWrapper) {
- const index = parseInt(
- buttonWrapper.getAttribute("data-image-index"),
- 10
- );
- const matchingPlaceholder =
- this.get("composer.reply").match(IMAGE_MARKDOWN_REGEX);
- const match = matchingPlaceholder[index];
- const input = buttonWrapper.querySelector("input.alt-text-input");
- const replacement = match.replace(
- IMAGE_MARKDOWN_REGEX,
- `![${input.value}|$2$3$4]($5)`
- );
+ this.appEvents.trigger(
+ `${this.composerEventPrefix}:replace-text`,
+ match,
+ replacement
+ );
- this.appEvents.trigger(
- `${this.composerEventPrefix}:replace-text`,
- match,
- replacement
- );
+ this.resetImageControls(buttonWrapper);
+ },
- this.resetImageControls(buttonWrapper);
- },
+ @bind
+ _handleAltTextInputKeypress(event) {
+ if (!event.target.classList.contains("alt-text-input")) {
+ return;
+ }
- @bind
- _handleAltTextInputKeypress(event) {
- if (!event.target.classList.contains("alt-text-input")) {
- return;
- }
+ if (event.key === "[" || event.key === "]") {
+ event.preventDefault();
+ }
- if (event.key === "[" || event.key === "]") {
- event.preventDefault();
- }
+ if (event.key === "Enter") {
+ const buttonWrapper = event.target.closest(".button-wrapper");
+ this.commitAltText(buttonWrapper);
+ }
+ },
- if (event.key === "Enter") {
- const buttonWrapper = event.target.closest(".button-wrapper");
- this.commitAltText(buttonWrapper);
- }
- },
+ @bind
+ _handleAltTextEditButtonClick(event) {
+ if (!event.target.classList.contains("alt-text-edit-btn")) {
+ return;
+ }
- @bind
- _handleAltTextEditButtonClick(event) {
- if (!event.target.classList.contains("alt-text-edit-btn")) {
- return;
- }
+ const buttonWrapper = event.target.closest(".button-wrapper");
+ const imageResize = buttonWrapper.querySelector(".scale-btn-container");
+ const imageDelete = buttonWrapper.querySelector(".delete-image-button");
- const buttonWrapper = event.target.closest(".button-wrapper");
- const imageResize = buttonWrapper.querySelector(".scale-btn-container");
- const imageDelete = buttonWrapper.querySelector(".delete-image-button");
+ const readonlyContainer = buttonWrapper.querySelector(
+ ".alt-text-readonly-container"
+ );
+ const altText = readonlyContainer.querySelector(".alt-text");
- const readonlyContainer = buttonWrapper.querySelector(
- ".alt-text-readonly-container"
- );
- const altText = readonlyContainer.querySelector(".alt-text");
+ const editContainer = buttonWrapper.querySelector(
+ ".alt-text-edit-container"
+ );
+ const editContainerInput = editContainer.querySelector(".alt-text-input");
+
+ buttonWrapper.setAttribute("editing", "true");
+ imageResize.setAttribute("hidden", "true");
+ imageDelete.setAttribute("hidden", "true");
+ readonlyContainer.setAttribute("hidden", "true");
+ editContainerInput.value = altText.textContent;
+ editContainer.removeAttribute("hidden");
+ editContainerInput.focus();
+ event.preventDefault();
+ },
+
+ @bind
+ _handleAltTextOkButtonClick(event) {
+ if (!event.target.classList.contains("alt-text-edit-ok")) {
+ return;
+ }
- const editContainer = buttonWrapper.querySelector(
- ".alt-text-edit-container"
- );
- const editContainerInput = editContainer.querySelector(".alt-text-input");
-
- buttonWrapper.setAttribute("editing", "true");
- imageResize.setAttribute("hidden", "true");
- imageDelete.setAttribute("hidden", "true");
- readonlyContainer.setAttribute("hidden", "true");
- editContainerInput.value = altText.textContent;
- editContainer.removeAttribute("hidden");
- editContainerInput.focus();
- event.preventDefault();
- },
+ const buttonWrapper = event.target.closest(".button-wrapper");
+ this.commitAltText(buttonWrapper);
+ },
- @bind
- _handleAltTextOkButtonClick(event) {
- if (!event.target.classList.contains("alt-text-edit-ok")) {
- return;
- }
+ @bind
+ _handleAltTextCancelButtonClick(event) {
+ if (!event.target.classList.contains("alt-text-edit-cancel")) {
+ return;
+ }
- const buttonWrapper = event.target.closest(".button-wrapper");
- this.commitAltText(buttonWrapper);
- },
+ const buttonWrapper = event.target.closest(".button-wrapper");
+ this.resetImageControls(buttonWrapper);
+ },
- @bind
- _handleAltTextCancelButtonClick(event) {
- if (!event.target.classList.contains("alt-text-edit-cancel")) {
- return;
- }
+ @bind
+ _handleImageDeleteButtonClick(event) {
+ if (!event.target.classList.contains("delete-image-button")) {
+ return;
+ }
+ const index = parseInt(
+ event.target.closest(".button-wrapper").dataset.imageIndex,
+ 10
+ );
+ const matchingPlaceholder =
+ this.get("composer.reply").match(IMAGE_MARKDOWN_REGEX);
+ this.appEvents.trigger(
+ `${this.composerEventPrefix}:replace-text`,
+ matchingPlaceholder[index],
+ "",
+ { regex: IMAGE_MARKDOWN_REGEX, index }
+ );
+ },
- const buttonWrapper = event.target.closest(".button-wrapper");
- this.resetImageControls(buttonWrapper);
- },
+ @bind
+ _handleImageGridButtonClick(event) {
+ if (!event.target.classList.contains("wrap-image-grid-button")) {
+ return;
+ }
- @bind
- _handleImageDeleteButtonClick(event) {
- if (!event.target.classList.contains("delete-image-button")) {
- return;
- }
- const index = parseInt(
- event.target.closest(".button-wrapper").dataset.imageIndex,
- 10
+ const index = parseInt(
+ event.target.closest(".button-wrapper").dataset.imageIndex,
+ 10
+ );
+ const reply = this.get("composer.reply");
+ const matches = reply.match(IMAGE_MARKDOWN_REGEX);
+ const closingIndex =
+ index + parseInt(event.target.dataset.imageCount, 10) - 1;
+
+ const textArea = this.element.querySelector(".d-editor-input");
+ textArea.selectionStart = reply.indexOf(matches[index]);
+ textArea.selectionEnd =
+ reply.indexOf(matches[closingIndex]) + matches[closingIndex].length;
+
+ this.appEvents.trigger(
+ `${this.composerEventPrefix}:apply-surround`,
+ "[grid]",
+ "[/grid]",
+ "grid_surround",
+ { useBlockMode: true }
+ );
+ },
+
+ _registerImageAltTextButtonClick(preview) {
+ preview.addEventListener("click", this._handleAltTextEditButtonClick);
+ preview.addEventListener("click", this._handleAltTextOkButtonClick);
+ preview.addEventListener("click", this._handleAltTextCancelButtonClick);
+ preview.addEventListener("click", this._handleImageDeleteButtonClick);
+ preview.addEventListener("keypress", this._handleAltTextInputKeypress);
+ preview.addEventListener("click", this._handleImageGridButtonClick);
+ },
+
+ @on("willDestroyElement")
+ _composerClosed() {
+ this._unbindMobileUploadButton();
+ this.appEvents.trigger(`${this.composerEventPrefix}:will-close`);
+ next(() => {
+ // need to wait a bit for the "slide down" transition of the composer
+ discourseLater(
+ () => this.appEvents.trigger(`${this.composerEventPrefix}:closed`),
+ isTesting() ? 0 : 400
);
- const matchingPlaceholder =
- this.get("composer.reply").match(IMAGE_MARKDOWN_REGEX);
- this.appEvents.trigger(
- `${this.composerEventPrefix}:replace-text`,
- matchingPlaceholder[index],
- "",
- { regex: IMAGE_MARKDOWN_REGEX, index }
+ });
+
+ this.element
+ .querySelector(".d-editor-input")
+ ?.removeEventListener(
+ "scroll",
+ this._throttledSyncEditorAndPreviewScroll
);
- },
- @bind
- _handleImageGridButtonClick(event) {
- if (!event.target.classList.contains("wrap-image-grid-button")) {
- return;
+ const preview = this.element.querySelector(".d-editor-preview-wrapper");
+ preview?.removeEventListener("click", this._handleImageScaleButtonClick);
+ preview?.removeEventListener("click", this._handleAltTextEditButtonClick);
+ preview?.removeEventListener("click", this._handleAltTextOkButtonClick);
+ preview?.removeEventListener("click", this._handleImageDeleteButtonClick);
+ preview?.removeEventListener("click", this._handleImageGridButtonClick);
+ preview?.removeEventListener("click", this._handleAltTextCancelButtonClick);
+ preview?.removeEventListener("keypress", this._handleAltTextInputKeypress);
+ },
+
+ onExpandPopupMenuOptions(toolbarEvent) {
+ const selected = toolbarEvent.selected;
+ toolbarEvent.selectText(selected.start, selected.end - selected.start);
+ this.storeToolbarState(toolbarEvent);
+ },
+
+ showPreview() {
+ this.send("togglePreview");
+ },
+
+ _isInQuote(element) {
+ let parent = element.parentElement;
+ while (parent && !this._isPreviewRoot(parent)) {
+ if (this._isQuote(parent)) {
+ return true;
}
- const index = parseInt(
- event.target.closest(".button-wrapper").dataset.imageIndex,
- 10
- );
- const reply = this.get("composer.reply");
- const matches = reply.match(IMAGE_MARKDOWN_REGEX);
- const closingIndex =
- index + parseInt(event.target.dataset.imageCount, 10) - 1;
-
- const textArea = this.element.querySelector(".d-editor-input");
- textArea.selectionStart = reply.indexOf(matches[index]);
- textArea.selectionEnd =
- reply.indexOf(matches[closingIndex]) + matches[closingIndex].length;
-
- this.appEvents.trigger(
- `${this.composerEventPrefix}:apply-surround`,
- "[grid]",
- "[/grid]",
- "grid_surround",
- { useBlockMode: true }
- );
- },
+ parent = parent.parentElement;
+ }
- _registerImageAltTextButtonClick(preview) {
- preview.addEventListener("click", this._handleAltTextEditButtonClick);
- preview.addEventListener("click", this._handleAltTextOkButtonClick);
- preview.addEventListener("click", this._handleAltTextCancelButtonClick);
- preview.addEventListener("click", this._handleImageDeleteButtonClick);
- preview.addEventListener("keypress", this._handleAltTextInputKeypress);
- preview.addEventListener("click", this._handleImageGridButtonClick);
- },
+ return false;
+ },
- @on("willDestroyElement")
- _composerClosed() {
- this._unbindMobileUploadButton();
- this.appEvents.trigger(`${this.composerEventPrefix}:will-close`);
- next(() => {
- // need to wait a bit for the "slide down" transition of the composer
- discourseLater(
- () => this.appEvents.trigger(`${this.composerEventPrefix}:closed`),
- isTesting() ? 0 : 400
- );
- });
+ _isPreviewRoot(element) {
+ return (
+ element.tagName === "DIV" &&
+ element.classList.contains("d-editor-preview")
+ );
+ },
+
+ _isQuote(element) {
+ return element.tagName === "ASIDE" && element.classList.contains("quote");
+ },
+
+ _cursorIsOnEmptyLine() {
+ const textArea = this.element.querySelector(".d-editor-input");
+ const selectionStart = textArea.selectionStart;
+ if (selectionStart === 0) {
+ return true;
+ } else if (textArea.value.charAt(selectionStart - 1) === "\n") {
+ return true;
+ } else {
+ return false;
+ }
+ },
- this.element
- .querySelector(".d-editor-input")
- ?.removeEventListener(
- "scroll",
- this._throttledSyncEditorAndPreviewScroll
- );
+ _findMatchingUploadHandler(fileName) {
+ return this.uploadHandlers.find((handler) => {
+ const ext = handler.extensions.join("|");
+ const regex = new RegExp(`\\.(${ext})$`, "i");
+ return regex.test(fileName);
+ });
+ },
- const preview = this.element.querySelector(".d-editor-preview-wrapper");
- preview?.removeEventListener("click", this._handleImageScaleButtonClick);
- preview?.removeEventListener("click", this._handleAltTextEditButtonClick);
- preview?.removeEventListener("click", this._handleAltTextOkButtonClick);
- preview?.removeEventListener("click", this._handleImageDeleteButtonClick);
- preview?.removeEventListener("click", this._handleImageGridButtonClick);
- preview?.removeEventListener(
- "click",
- this._handleAltTextCancelButtonClick
- );
- preview?.removeEventListener(
- "keypress",
- this._handleAltTextInputKeypress
- );
+ actions: {
+ importQuote(toolbarEvent) {
+ this.importQuote(toolbarEvent);
},
onExpandPopupMenuOptions(toolbarEvent) {
- const selected = toolbarEvent.selected;
- toolbarEvent.selectText(selected.start, selected.end - selected.start);
- this.storeToolbarState(toolbarEvent);
- },
-
- showPreview() {
- this.send("togglePreview");
+ this.onExpandPopupMenuOptions(toolbarEvent);
},
- _isInQuote(element) {
- let parent = element.parentElement;
- while (parent && !this._isPreviewRoot(parent)) {
- if (this._isQuote(parent)) {
- return true;
- }
-
- parent = parent.parentElement;
- }
-
- return false;
- },
-
- _isPreviewRoot(element) {
- return (
- element.tagName === "DIV" &&
- element.classList.contains("d-editor-preview")
- );
+ togglePreview() {
+ this.togglePreview();
},
- _isQuote(element) {
- return element.tagName === "ASIDE" && element.classList.contains("quote");
- },
+ extraButtons(toolbar) {
+ toolbar.addButton({
+ id: "quote",
+ group: "fontStyles",
+ icon: "far-comment",
+ sendAction: this.importQuote,
+ title: "composer.quote_post_title",
+ unshift: true,
+ });
- _cursorIsOnEmptyLine() {
- const textArea = this.element.querySelector(".d-editor-input");
- const selectionStart = textArea.selectionStart;
- if (selectionStart === 0) {
- return true;
- } else if (textArea.value.charAt(selectionStart - 1) === "\n") {
- return true;
- } else {
- return false;
+ if (this.allowUpload && this.uploadIcon && !this.site.mobileView) {
+ toolbar.addButton({
+ id: "upload",
+ group: "insertions",
+ icon: this.uploadIcon,
+ title: "upload",
+ sendAction: this.showUploadModal,
+ });
}
- },
- _findMatchingUploadHandler(fileName) {
- return this.uploadHandlers.find((handler) => {
- const ext = handler.extensions.join("|");
- const regex = new RegExp(`\\.(${ext})$`, "i");
- return regex.test(fileName);
+ toolbar.addButton({
+ id: "options",
+ group: "extras",
+ icon: "cog",
+ title: "composer.options",
+ sendAction: this.onExpandPopupMenuOptions.bind(this),
+ popupMenu: true,
});
},
- actions: {
- importQuote(toolbarEvent) {
- this.importQuote(toolbarEvent);
- },
-
- onExpandPopupMenuOptions(toolbarEvent) {
- this.onExpandPopupMenuOptions(toolbarEvent);
- },
+ previewUpdated(preview) {
+ // cache jquery objects for functions still using jquery
+ const $preview = $(preview);
- togglePreview() {
- this.togglePreview();
- },
+ // Paint mentions
+ const unseenMentions = linkSeenMentions(preview, this.siteSettings);
+ if (unseenMentions.length) {
+ discourseDebounce(
+ this,
+ this._renderUnseenMentions,
+ preview,
+ unseenMentions,
+ 450
+ );
+ }
- extraButtons(toolbar) {
- toolbar.addButton({
- id: "quote",
- group: "fontStyles",
- icon: "far-comment",
- sendAction: this.importQuote,
- title: "composer.quote_post_title",
- unshift: true,
- });
+ this._warnMentionedGroups(preview);
+ this._warnCannotSeeMention(preview);
- if (this.allowUpload && this.uploadIcon && !this.site.mobileView) {
- toolbar.addButton({
- id: "upload",
- group: "insertions",
- icon: this.uploadIcon,
- title: "upload",
- sendAction: this.showUploadModal,
- });
- }
+ // Paint category, tag, and other data source hashtags
+ const hashtagContext = this.site.hashtag_configurations["topic-composer"];
+ if (linkSeenHashtagsInContext(hashtagContext, preview).length > 0) {
+ discourseDebounce(this, this._renderUnseenHashtags, preview, 450);
+ }
- toolbar.addButton({
- id: "options",
- group: "extras",
- icon: "cog",
- title: "composer.options",
- sendAction: this.onExpandPopupMenuOptions.bind(this),
- popupMenu: true,
- });
- },
+ // Paint oneboxes
+ const paintFunc = () => {
+ const post = this.get("composer.post");
+ let refresh = false;
- previewUpdated(preview) {
- // cache jquery objects for functions still using jquery
- const $preview = $(preview);
-
- // Paint mentions
- const unseenMentions = linkSeenMentions(preview, this.siteSettings);
- if (unseenMentions.length) {
- discourseDebounce(
- this,
- this._renderUnseenMentions,
- preview,
- unseenMentions,
- 450
- );
+ //If we are editing a post, we'll refresh its contents once.
+ if (post && !post.get("refreshedPost")) {
+ refresh = true;
}
- this._warnMentionedGroups(preview);
- this._warnCannotSeeMention(preview);
+ const paintedCount = loadOneboxes(
+ preview,
+ ajax,
+ this.get("composer.topic.id"),
+ this.get("composer.category.id"),
+ this.siteSettings.max_oneboxes_per_post,
+ refresh
+ );
- // Paint category, tag, and other data source hashtags
- const hashtagContext =
- this.site.hashtag_configurations["topic-composer"];
- if (linkSeenHashtagsInContext(hashtagContext, preview).length > 0) {
- discourseDebounce(this, this._renderUnseenHashtags, preview, 450);
+ if (refresh && paintedCount > 0) {
+ post.set("refreshedPost", true);
}
+ };
- // Paint oneboxes
- const paintFunc = () => {
- const post = this.get("composer.post");
- let refresh = false;
-
- //If we are editing a post, we'll refresh its contents once.
- if (post && !post.get("refreshedPost")) {
- refresh = true;
- }
-
- const paintedCount = loadOneboxes(
- preview,
- ajax,
- this.get("composer.topic.id"),
- this.get("composer.category.id"),
- this.siteSettings.max_oneboxes_per_post,
- refresh
- );
-
- if (refresh && paintedCount > 0) {
- post.set("refreshedPost", true);
- }
- };
-
- discourseDebounce(this, paintFunc, 450);
+ discourseDebounce(this, paintFunc, 450);
- // Short upload urls need resolution
- resolveAllShortUrls(ajax, this.siteSettings, preview);
+ // Short upload urls need resolution
+ resolveAllShortUrls(ajax, this.siteSettings, preview);
- preview.addEventListener("click", this._handleImageScaleButtonClick);
- this._registerImageAltTextButtonClick(preview);
+ preview.addEventListener("click", this._handleImageScaleButtonClick);
+ this._registerImageAltTextButtonClick(preview);
- this.trigger("previewRefreshed", preview);
- this.afterRefresh($preview);
- },
+ this.trigger("previewRefreshed", preview);
+ this.afterRefresh($preview);
},
- }
-);
+ },
+});
diff --git a/app/assets/javascripts/discourse/app/mixins/composer-upload-uppy.js b/app/assets/javascripts/discourse/app/mixins/composer-upload-uppy.js
index b0a7ac5fef5..30c52e25046 100644
--- a/app/assets/javascripts/discourse/app/mixins/composer-upload-uppy.js
+++ b/app/assets/javascripts/discourse/app/mixins/composer-upload-uppy.js
@@ -1,4 +1,5 @@
import Mixin from "@ember/object/mixin";
+import { getOwner } from "@ember/application";
import ExtendableUploader from "discourse/mixins/extendable-uploader";
import EmberObject from "@ember/object";
import UppyS3Multipart from "discourse/mixins/uppy-s3-multipart";
@@ -11,6 +12,7 @@ import { warn } from "@ember/debug";
import I18n from "I18n";
import getURL from "discourse-common/lib/get-url";
import { clipboardHelpers } from "discourse/lib/utilities";
+import ComposerVideoThumbnailUppy from "discourse/mixins/composer-video-thumbnail-uppy";
import { bind, observes, on } from "discourse-common/utils/decorators";
import {
bindFileInputChangeListener,
@@ -325,28 +327,32 @@ export default Mixin.create(ExtendableUploader, UppyS3Multipart, {
cacheShortUploadUrl(upload.short_url, upload);
- this._generateVideoThumbnail(file, upload.url, () => {
- if (this.useUploadPlaceholders) {
+ new ComposerVideoThumbnailUppy(getOwner(this)).generateVideoThumbnail(
+ file,
+ upload.url,
+ () => {
+ if (this.useUploadPlaceholders) {
+ this.appEvents.trigger(
+ `${this.composerEventPrefix}:replace-text`,
+ this.placeholders[file.id].uploadPlaceholder.trim(),
+ markdown
+ );
+ }
+ this._resetUpload(file, { removePlaceholder: false });
this.appEvents.trigger(
- `${this.composerEventPrefix}:replace-text`,
- this.placeholders[file.id].uploadPlaceholder.trim(),
- markdown
+ `${this.composerEventPrefix}:upload-success`,
+ file.name,
+ upload
);
- }
- this._resetUpload(file, { removePlaceholder: false });
- this.appEvents.trigger(
- `${this.composerEventPrefix}:upload-success`,
- file.name,
- upload
- );
- if (this.inProgressUploads.length === 0) {
- this.appEvents.trigger(
- `${this.composerEventPrefix}:all-uploads-complete`
- );
- this._reset();
+ if (this.inProgressUploads.length === 0) {
+ this.appEvents.trigger(
+ `${this.composerEventPrefix}:all-uploads-complete`
+ );
+ this._reset();
+ }
}
- });
+ );
});
});
diff --git a/app/assets/javascripts/discourse/app/mixins/composer-video-thumbnail-uppy.js b/app/assets/javascripts/discourse/app/mixins/composer-video-thumbnail-uppy.js
index 7781149d38d..d78ac59a783 100644
--- a/app/assets/javascripts/discourse/app/mixins/composer-video-thumbnail-uppy.js
+++ b/app/assets/javascripts/discourse/app/mixins/composer-video-thumbnail-uppy.js
@@ -1,30 +1,52 @@
-import Mixin from "@ember/object/mixin";
-import ExtendableUploader from "discourse/mixins/extendable-uploader";
-import UppyS3Multipart from "discourse/mixins/uppy-s3-multipart";
+import { setOwner } from "@ember/application";
+import { isVideo } from "discourse/lib/uploads";
+import { tracked } from "@glimmer/tracking";
+import UppyUploadMixin from "discourse/mixins/uppy-upload";
+import EmberObject from "@ember/object";
import Uppy from "@uppy/core";
-import DropTarget from "@uppy/drop-target";
-import XHRUpload from "@uppy/xhr-upload";
import { warn } from "@ember/debug";
import I18n from "I18n";
-import getURL from "discourse-common/lib/get-url";
-import { bind } from "discourse-common/utils/decorators";
import { inject as service } from "@ember/service";
-export default Mixin.create(ExtendableUploader, UppyS3Multipart, {
- dialog: service(),
- uploadRootPath: "/uploads",
- uploadTargetBound: false,
- useUploadPlaceholders: true,
-
- @bind
- _generateVideoThumbnail(videoFile, uploadUrl, callback) {
+// It is not ideal that this is a class extending a mixin, but in the case
+// where this is needed (a second background uppy uploader on a class that
+// already has an uppyInstance) then it is acceptable for now.
+//
+// Ideally, this would be refactored into an uppy postprocessor and support
+// for that would be added to the ExtendableUploader. Generally, we want to
+// move away from these Mixins in future.
+//
+// Video thumbnail is attached to the post/topic here:
+//
+// https://github.com/discourse/discourse/blob/110a3025dbf5c7205cec498c7d83dc258d994cfe/app/models/post.rb#L1013-L1035
+export default class ComposerVideoThumbnailUppy extends EmberObject.extend(
+ UppyUploadMixin
+) {
+ @service dialog;
+ @service siteSettings;
+ @service session;
+
+ @tracked uploading;
+
+ uploadRootPath = "/uploads";
+ uploadTargetBound = false;
+ useUploadPlaceholders = true;
+
+ constructor(owner) {
+ super(...arguments);
+ setOwner(this, owner);
+ }
+
+ generateVideoThumbnail(videoFile, uploadUrl, callback) {
if (!this.siteSettings.video_thumbnails_enabled) {
return callback();
}
- if (videoFile.type.split("/")[0] !== "video") {
+
+ if (!isVideo(videoFile.name)) {
return callback();
}
- let video = document.createElement("video");
+
+ const video = document.createElement("video");
video.src = URL.createObjectURL(videoFile.data);
// These attributes are needed for thumbnail generation on mobile.
@@ -40,8 +62,8 @@ export default Mixin.create(ExtendableUploader, UppyS3Multipart, {
// Wait for the video element to load, otherwise the canvas will be empty.
// iOS Safari prefers onloadedmetadata over oncanplay.
video.onloadedmetadata = () => {
- let canvas = document.createElement("canvas");
- let ctx = canvas.getContext("2d");
+ const canvas = document.createElement("canvas");
+ const ctx = canvas.getContext("2d");
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
@@ -54,8 +76,8 @@ export default Mixin.create(ExtendableUploader, UppyS3Multipart, {
this._uppyInstance = new Uppy({
id: "video-thumbnail",
meta: {
- upload_type: `thumbnail`,
videoSha1,
+ upload_type: "thumbnail",
},
autoProceed: true,
});
@@ -69,14 +91,13 @@ export default Mixin.create(ExtendableUploader, UppyS3Multipart, {
} else {
this._useXHRUploads();
}
- this._uppyInstance.use(DropTarget, { target: this.element });
this._uppyInstance.on("upload", () => {
- this.set("uploading", true);
+ this.uploading = true;
});
this._uppyInstance.on("upload-success", () => {
- this.set("uploading", false);
+ this.uploading = false;
callback();
});
@@ -88,13 +109,13 @@ export default Mixin.create(ExtendableUploader, UppyS3Multipart, {
// eslint-disable-next-line no-console
console.error(message);
- this.set("uploading", false);
+ this.uploading = false;
callback();
});
try {
this._uppyInstance.addFile({
- source: `${this.id} thumbnail`,
+ source: `${this.id}-video-thumbnail`,
name: `${videoSha1}`,
type: blob.type,
data: blob,
@@ -107,19 +128,5 @@ export default Mixin.create(ExtendableUploader, UppyS3Multipart, {
});
}, 100);
};
- },
-
- // This should be overridden in a child component if you need to
- // hook into uppy events and be sure that everything is already
- // set up for _uppyInstance.
- _uppyReady() {},
-
- _useXHRUploads() {
- this._uppyInstance.use(XHRUpload, {
- endpoint: getURL(`/uploads.json?client_id=${this.messageBus.clientId}`),
- headers: {
- "X-CSRF-Token": this.session.csrfToken,
- },
- });
- },
-});
+ }
+}
diff --git a/spec/system/composer_uploads_spec.rb b/spec/system/composer_uploads_spec.rb
new file mode 100644
index 00000000000..dab2f4b4676
--- /dev/null
+++ b/spec/system/composer_uploads_spec.rb
@@ -0,0 +1,74 @@
+# frozen_string_literal: true
+
+describe "Uploading files in the composer", type: :system, js: true do
+ fab!(:current_user) { Fabricate(:user) }
+
+ let(:modal) { PageObjects::Modals::Base.new }
+ let(:composer) { PageObjects::Components::Composer.new }
+ let(:topic) { PageObjects::Pages::Topic.new }
+
+ before { sign_in(current_user) }
+
+ it "uploads multiple files at once" do
+ sign_in(current_user)
+
+ visit "/new-topic"
+ expect(composer).to be_opened
+
+ file_path_1 = file_from_fixtures("logo.png", "images").path
+ file_path_2 = file_from_fixtures("logo.jpg", "images").path
+ attach_file([file_path_1, file_path_2]) { composer.click_toolbar_button("upload") }
+
+ expect(composer).to have_no_in_progress_uploads
+ expect(composer.preview).to have_css(".image-wrapper", count: 2)
+ end
+
+ it "allows cancelling uploads" do
+ sign_in(current_user)
+
+ visit "/new-topic"
+ expect(composer).to be_opened
+
+ page.driver.browser.network_conditions = { latency: 20_000 }
+
+ file_path_1 = file_from_fixtures("logo.png", "images").path
+ attach_file(file_path_1) { composer.click_toolbar_button("upload") }
+ expect(composer).to have_in_progress_uploads
+ find("#cancel-file-upload").click
+
+ expect(composer).to have_no_in_progress_uploads
+ expect(composer.preview).to have_no_css(".image-wrapper")
+ ensure
+ page.driver.browser.network_conditions = { latency: 0 }
+ end
+
+ context "when video thumbnails are enabled" do
+ before do
+ SiteSetting.video_thumbnails_enabled = true
+ SiteSetting.authorized_extensions += "|mp4"
+ end
+
+ # TODO (martin): Video streaming is not yet available in Chrome for Testing,
+ # we need to come back to this in a few months and try again.
+ #
+ # c.f. https://groups.google.com/g/chromedriver-users/c/1SMbByMfO2U
+ xit "generates a thumbnail for the video" do
+ sign_in(current_user)
+
+ visit "/new-topic"
+ expect(composer).to be_opened
+ topic.fill_in_composer_title("Video upload test")
+
+ file_path_1 = file_from_fixtures("small.mp4", "media").path
+ attach_file(file_path_1) { composer.click_toolbar_button("upload") }
+
+ expect(composer).to have_no_in_progress_uploads
+ expect(composer.preview).to have_css(".video-container")
+
+ composer.submit
+
+ expect(find("#topic-title")).to have_content("Video upload test")
+ expect(topic.image_upload_id).to eq(Upload.last.id)
+ end
+ end
+end
diff --git a/spec/system/page_objects/components/composer.rb b/spec/system/page_objects/components/composer.rb
index 60837c43029..da6ebe59605 100644
--- a/spec/system/page_objects/components/composer.rb
+++ b/spec/system/page_objects/components/composer.rb
@@ -200,10 +200,22 @@ module PageObjects
JS
end
+ def submit
+ find("#{COMPOSER_ID} .save-or-cancel .create").click
+ end
+
def close
find("#{COMPOSER_ID} .save-or-cancel .cancel").click
end
+ def has_no_in_progress_uploads?
+ find("#{COMPOSER_ID}").has_no_css?("#file-uploading")
+ end
+
+ def has_in_progress_uploads?
+ find("#{COMPOSER_ID}").has_css?("#file-uploading")
+ end
+
private
def emoji_preview_selector(emoji)
diff --git a/spec/system/s3_uploads_spec.rb b/spec/system/s3_uploads_spec.rb
index 2df55a0d63c..92b1bc84e18 100644
--- a/spec/system/s3_uploads_spec.rb
+++ b/spec/system/s3_uploads_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-describe "Uploading files to S3", type: :system do
+describe "Uploading files in the composer to S3", type: :system do
fab!(:current_user) { Fabricate(:admin) }
let(:modal) { PageObjects::Modals::Base.new }