OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub
Ruby agile-developmentangularbcfboardsbug-trackerganttgantt-chartifcissue-trackerjira-alternativekanbanopenprojectproduct-managementproject-managementproject-planningroadmaprubyscrumtimelineworkflows
close editor on blur and keep editor open after submit for a more chat like interface as requested by @wielinde
Jonas Jabaria1a25779009d
diff --git a/app/controllers/work_packages/activities_tab_controller.rb b/app/controllers/work_packages/activities_tab_controller.rbindex a8fdc66e115..986839f641b 100644--- a/app/controllers/work_packages/activities_tab_controller.rb+++ b/app/controllers/work_packages/activities_tab_controller.rb@@ -98,7 +98,7 @@ class WorkPackages::ActivitiesTabController < ApplicationController### taken from ActivitiesByWorkPackageAPIcall = AddWorkPackageNoteService.new(user: User.current,- work_package: @work_package)+ work_package: @work_package).call(journal_params[:notes],send_notifications: !(params.has_key?(:notify) && params[:notify] == "false"))###@@ -107,7 +107,7 @@ class WorkPackages::ActivitiesTabController < ApplicationControllergenerate_time_based_update_streams(params[:last_update_timestamp], params[:filter])end- clear_form_via_turbo_stream+ # clear_form_via_turbo_streamrespond_with_turbo_streamsenddiff --git a/frontend/src/app/shared/components/editor/components/ckeditor/op-ckeditor.component.ts b/frontend/src/app/shared/components/editor/components/ckeditor/op-ckeditor.component.tsindex dc3a772d790..239c43c31de 100644--- a/frontend/src/app/shared/components/editor/components/ckeditor/op-ckeditor.component.ts+++ b/frontend/src/app/shared/components/editor/components/ckeditor/op-ckeditor.component.ts@@ -247,7 +247,7 @@ export class OpCkeditorComponent implements OnInit, OnDestroy {if ((data.ctrlKey || data.metaKey) && data.keyCode === KeyCodes.ENTER) {debugLog('Sending save request from CKEditor.');this.saveRequested.emit();- evt.stop();+ // evt.stop();}},{ priority: 'highest' },diff --git a/frontend/src/stimulus/controllers/dynamic/work-packages/activities-tab/index.controller.ts b/frontend/src/stimulus/controllers/dynamic/work-packages/activities-tab/index.controller.tsindex b6522cbd275..f464f20da61 100644--- a/frontend/src/stimulus/controllers/dynamic/work-packages/activities-tab/index.controller.ts+++ b/frontend/src/stimulus/controllers/dynamic/work-packages/activities-tab/index.controller.ts@@ -1,38 +1,9 @@-/*- * -- copyright- * OpenProject is an open source project management software.- * Copyright (C) 2023 the OpenProject GmbH- *- * This program is free software; you can redistribute it and/or- * modify it under the terms of the GNU General Public License version 3.- *- * OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:- * Copyright (C) 2006-2013 Jean-Philippe Lang- * Copyright (C) 2010-2013 the ChiliProject Team- *- * This program is free software; you can redistribute it and/or- * modify it under the terms of the GNU General Public License- * as published by the Free Software Foundation; either version 2- * of the License, or (at your option) any later version.- *- * This program is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU General Public License for more details.- *- * You should have received a copy of the GNU General Public License- * along with this program; if not, write to the Free Software- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.- *- * See COPYRIGHT and LICENSE files for more details.- * ++- */-import * as Turbo from '@hotwired/turbo';import { Controller } from '@hotwired/stimulus';import {ICKEditorInstance,} from 'core-app/shared/components/editor/components/ckeditor/ckeditor.types';+import { KeyCodes } from 'core-app/shared/helpers/keyCodes.enum';export default class IndexController extends Controller {static values = {@@ -58,33 +29,36 @@ export default class IndexController extends Controller {connect() {this.setLastUpdateTimestamp();+ this.setupEventListeners();+ this.handleInitialScroll();+ this.intervallId = this.pollForUpdates();+ }++ disconnect() {+ document.removeEventListener('work-package-updated', this.handleWorkPackageUpdate);+ window.clearInterval(this.intervallId);+ }++ private setupEventListeners() {this.handleWorkPackageUpdate = this.handleWorkPackageUpdate.bind(this);document.addEventListener('work-package-updated', this.handleWorkPackageUpdate);+ }+ private handleInitialScroll() {if (window.location.hash.includes('#activity-')) {this.scrollToActivity();} else if (this.sortingValue === 'asc') {this.scrollToBottom();}-- this.intervallId = this.pollForUpdates();- }-- disconnect() {- document.removeEventListener('work-package-updated', this.handleWorkPackageUpdate);- window.clearInterval(this.intervallId);}- scrollToActivity() {+ private scrollToActivity() {const activityId = window.location.hash.replace('#activity-', '');const activityElement = document.getElementById(`activity-${activityId}`);- if (activityElement) {- activityElement.scrollIntoView({ behavior: 'smooth' });- }+ activityElement?.scrollIntoView({ behavior: 'smooth' });}- scrollToBottom():void {- // copied from frontend/src/app/features/work-packages/components/work-package-comment/work-package-comment.component.ts+ private scrollToBottom() {const scrollableContainer = jQuery(this.element).scrollParent()[0];if (scrollableContainer) {setTimeout(() => {@@ -94,9 +68,7 @@ export default class IndexController extends Controller {}async handleWorkPackageUpdate(event:Event) {- setTimeout(() => {- this.updateActivitiesList();- }, 2000); // TODO: wait dynamically for persisted change before updating the activities list+ setTimeout(() => this.updateActivitiesList(), 2000);}async updateActivitiesList() {@@ -104,17 +76,7 @@ export default class IndexController extends Controller {url.searchParams.append('last_update_timestamp', this.lastUpdateTimestamp);url.searchParams.append('filter', this.filterValue);- const response = await fetch(- url,- {- method: 'GET',- headers: {- 'X-CSRF-Token': (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement).content,- Accept: 'text/vnd.turbo-stream.html',- },- credentials: 'same-origin',- },- );+ const response = await this.fetchWithCSRF(url, 'GET');if (response.ok) {const text = await response.text();@@ -123,91 +85,101 @@ export default class IndexController extends Controller {}}- pollForUpdates() {- // protypical implementation of polling for updates in order to evaluate if we want to have this feature- return window.setInterval(() => {- this.updateActivitiesList();- }, this.pollingIntervalInMsValue);+ private pollForUpdates() {+ return window.setInterval(() => this.updateActivitiesList(), this.pollingIntervalInMsValue);}- setFilterToOnlyComments() {- this.filterValue = 'only_comments';- }+ setFilterToOnlyComments() { this.filterValue = 'only_comments'; }+ setFilterToOnlyChanges() { this.filterValue = 'only_changes'; }+ unsetFilter() { this.filterValue = ''; }- setFilterToOnlyChanges() {- this.filterValue = 'only_changes';+ private getCkEditorElement():HTMLElement | null {+ return this.formRowTarget.querySelectorAll('.document-editor__editable')[0] as HTMLElement;}- unsetFilter() {- this.filterValue = '';+ private getCkEditorInstance():ICKEditorInstance | null {+ const AngularCkEditorElement = this.element.querySelector('opce-ckeditor-augmented-textarea');+ return AngularCkEditorElement ? jQuery(AngularCkEditorElement).data('editor') as ICKEditorInstance : null;}- getCkEditorElement() {- return this.formRowTarget.querySelectorAll('.document-editor__editable')[0] as HTMLElement;+ private addEventListenersToCkEditorInstance() {+ const editor = this.getCkEditorInstance();+ if (editor) {+ this.addKeydownListener(editor);+ this.addKeyupListener(editor);+ this.addBlurListener(editor);+ }}- addEventListenerToCkEditorElement(ckEditorElement:HTMLElement) {- ckEditorElement.addEventListener('keydown', (event) => {- this.onCtrlEnter(event);- });- ckEditorElement.addEventListener('keyup', () => {- this.adjustJournalContainerMargin();- });+ private addKeydownListener(editor:ICKEditorInstance) {+ editor.listenTo(+ editor.editing.view.document,+ 'keydown',+ (event, data) => {+ if ((data.ctrlKey || data.metaKey) && data.keyCode === KeyCodes.ENTER) {+ this.onSubmit();+ event.stop();+ }+ },+ { priority: 'highest' },+ );}- adjustJournalContainerMargin() {- this.journalsContainerTarget.style.marginBottom = `${this.formRowTarget.clientHeight + 40}px`;+ private addKeyupListener(editor:ICKEditorInstance) {+ editor.listenTo(+ editor.editing.view.document,+ 'keyup',+ (event) => {+ this.adjustJournalContainerMargin();+ event.stop();+ },+ { priority: 'highest' },+ );}- onCtrlEnter(event:KeyboardEvent) {- if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {- this.onSubmit(event);- }+ private addBlurListener(editor:ICKEditorInstance) {+ editor.listenTo(+ editor.editing.view.document,+ 'blur',+ () => this.hideEditorIfEmpty(),+ { priority: 'highest' },+ );}- scrollJournalContainerToBottom(journalsContainer:HTMLElement) {- const scrollableContainer = jQuery(journalsContainer).scrollParent()[0];- if (scrollableContainer) {- scrollableContainer.scrollTop = scrollableContainer.scrollHeight;- }+ private adjustJournalContainerMargin() {+ this.journalsContainerTarget.style.marginBottom = `${this.formRowTarget.clientHeight + 40}px`;}- scrollJournalContainerToTop(journalsContainer:HTMLElement) {+ private scrollJournalContainer(journalsContainer:HTMLElement, toBottom:boolean) {const scrollableContainer = jQuery(journalsContainer).scrollParent()[0];if (scrollableContainer) {- scrollableContainer.scrollTop = 0;+ scrollableContainer.scrollTop = toBottom ? scrollableContainer.scrollHeight : 0;}}showForm() {this.buttonRowTarget.classList.add('d-none');this.formRowTarget.classList.remove('d-none');+ this.journalsContainerTarget?.classList.add('with-input-compensation');- if (this.journalsContainerTarget) {- this.journalsContainerTarget.classList.add('with-input-compensation');- }+ this.addEventListenersToCkEditorInstance();const ckEditorElement = this.getCkEditorElement();if (ckEditorElement) {- this.addEventListenerToCkEditorElement(ckEditorElement);-- setTimeout(() => {- if (ckEditorElement) {- ckEditorElement.focus();- }- }, 10);+ setTimeout(() => ckEditorElement.focus(), 10);}}quote(event:Event) {event.preventDefault();- const userName = (event.currentTarget as HTMLElement).dataset.userNameParam as string;- const content = (event.currentTarget as HTMLElement).dataset.contentParam as string;+ const target = event.currentTarget as HTMLElement;+ const userName = target.dataset.userNameParam as string;+ const content = target.dataset.contentParam as string;this.openEditorWithQuotedText(this.quotedText(content, userName));}- quotedText(rawComment:string, userName:string) {+ private quotedText(rawComment:string, userName:string) {const quoted = rawComment.split('\n').map((line:string) => `\n> ${line}`).join('');@@ -217,41 +189,41 @@ export default class IndexController extends Controller {openEditorWithQuotedText(quotedText:string) {this.showForm();- const AngularCkEditorElement = this.element.querySelector('opce-ckeditor-augmented-textarea');- if (AngularCkEditorElement) {- const ckeditorInstance = jQuery(AngularCkEditorElement).data('editor') as ICKEditorInstance;- if (ckeditorInstance) {- const currentData = ckeditorInstance.getData({ trim: false });- // only quote if the editor is empty- if (currentData.length === 0) {- ckeditorInstance.setData(quotedText);- }+ const ckEditorInstance = this.getCkEditorInstance();+ if (ckEditorInstance && ckEditorInstance.getData({ trim: false }).length === 0) {+ ckEditorInstance.setData(quotedText);+ }+ }++ clearEditor() {+ this.getCkEditorInstance()?.setData('');+ }++ hideEditorIfEmpty() {+ const ckEditorInstance = this.getCkEditorInstance();+ if (ckEditorInstance && ckEditorInstance.getData({ trim: false }).length === 0) {+ this.buttonRowTarget.classList.remove('d-none');+ this.formRowTarget.classList.add('d-none');++ if (this.journalsContainerTarget) {+ this.journalsContainerTarget.style.marginBottom = '';+ this.journalsContainerTarget.classList.add('with-initial-input-compensation');+ this.journalsContainerTarget.classList.remove('with-input-compensation');}}}- async onSubmit(event:Event) {- event.preventDefault(); // Prevent the native form submission+ async onSubmit(event:Event | null = null) {+ event?.preventDefault();+ const ckEditorInstance = this.getCkEditorInstance();+ const data = ckEditorInstance ? ckEditorInstance.getData({ trim: false }) : '';- const form = this.formTarget;- const formData = new FormData(form);+ const formData = new FormData(this.formTarget);formData.append('last_update_timestamp', this.lastUpdateTimestamp);formData.append('filter', this.filterValue);+ formData.append('journal[notes]', data);- const action = form.action;-- const response = await fetch(- action,- {- method: 'POST',- body: formData,- headers: {- 'X-CSRF-Token': (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement).content,- Accept: 'text/vnd.turbo-stream.html',- },- credentials: 'same-origin',- },- );+ const response = await this.fetchWithCSRF(this.formTarget.action, 'POST', formData);if (response.ok) {this.setLastUpdateTimestamp();@@ -259,20 +231,29 @@ export default class IndexController extends Controller {Turbo.renderStreamMessage(text);if (this.journalsContainerTarget) {+ this.clearEditor();setTimeout(() => {- this.journalsContainerTarget.style.marginBottom = '';- this.journalsContainerTarget.classList.add('with-initial-input-compensation');- this.journalsContainerTarget.classList.remove('with-input-compensation');- if (this.sortingValue === 'asc') {- this.scrollJournalContainerToBottom(this.journalsContainerTarget);- } else {- this.scrollJournalContainerToTop(this.journalsContainerTarget);- }+ this.scrollJournalContainer(+ this.journalsContainerTarget,+ this.sortingValue === 'asc',+ );}, 100);}}}+ private async fetchWithCSRF(url:string | URL, method:string, body?:FormData) {+ return fetch(url, {+ method,+ body,+ headers: {+ 'X-CSRF-Token': (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement).content,+ Accept: 'text/vnd.turbo-stream.html',+ },+ credentials: 'same-origin',+ });+ }+setLastUpdateTimestamp() {this.lastUpdateTimestamp = new Date().toISOString();}