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
Use documented method to get CKEditor instance
Alexander Brandon Coles6398c4f66546
diff --git a/frontend/src/app/core/setup/globals/global-listeners/settings.ts b/frontend/src/app/core/setup/globals/global-listeners/settings.tsindex ca224ba4362..c66e32155d3 100644--- a/frontend/src/app/core/setup/globals/global-listeners/settings.ts+++ b/frontend/src/app/core/setup/globals/global-listeners/settings.ts@@ -1,4 +1,5 @@-import { ICKEditorInstance } from 'core-app/shared/components/editor/components/ckeditor/ckeditor.types';+import { retrieveCkEditorInstance } from 'core-app/shared/helpers/ckeditor-helpers';+import invariant from 'tiny-invariant';/*** Move from legacy app/assets/javascripts/application.js.erb@@ -29,15 +30,17 @@ export function listenToSettingChanges() {});/* Javascript for Settings::TextSettingComponent */- const langSelectSwitchData = function (select:any) {- const self = jQuery(select);- const id:string = self.attr('id') || '';+ const langSelectSwitchData = (select:HTMLSelectElement) => {+ const id = select.getAttribute('id') || '';const settingName = id.replace('lang-for-', '');- const newLang = self.val() as string;+ const newLang = select.value;const textAreaId = `settings-${settingName}`;- const textArea = jQuery(`#${textAreaId}`);- const augmentedTextarea = jQuery(`opce-ckeditor-augmented-textarea[data-text-area-id='"${textAreaId}"']`);- const editor = augmentedTextarea.data('editor') as ICKEditorInstance;+ const textArea = document.getElementById(textAreaId);+ invariant(textArea, `Expected textarea "${textAreaId}"`);+ const ckEditor = document.querySelector<HTMLElement>(`opce-ckeditor-augmented-textarea[data-text-area-id='"${textAreaId}"'`);+ invariant(ckEditor, `Expected ckEditor for augmented textarea "${textAreaId}"`);+ const editor = retrieveCkEditorInstance(ckEditor);+ invariant(editor, `Expected ckEditorInstance for augmented textarea "${textAreaId}"`);return {id, settingName, newLang, textArea, editor,@@ -50,19 +53,26 @@ export function listenToSettingChanges() {// * get the current value from the hidden field for that lang and set the editor text to that value.// * Set the name of the textarea to reflect the current lang so that the value stored in the hidden field// is overwritten.- jQuery('.lang-select-switch')- .focus(function () {- const data = langSelectSwitchData(this);- jQuery(`#${data.id}-${data.newLang}`).val(data.editor.getData());- })- .change(function () {- const data = langSelectSwitchData(this);+ const langSelectSwitchFocusListener = (ev:Event) => {+ const select = ev.currentTarget as HTMLSelectElement;+ const { id, newLang, editor } = langSelectSwitchData(select);+ const hiddenInput = document.querySelector<HTMLInputElement>(`#${id}-${newLang}`)!;+ hiddenInput.value = editor.getData();+ };- const storedValue = jQuery(`#${data.id}-${data.newLang}`).val()!.toString();+ const langSelectSwitchChangeListener = (ev:Event) => {+ const select = ev.currentTarget as HTMLSelectElement;+ const { id, settingName, newLang, textArea, editor } = langSelectSwitchData(select);+ const hiddenInput = document.querySelector<HTMLInputElement>(`#${id}-${newLang}`)!;+ editor.setData(hiddenInput.value);+ textArea.setAttribute('name', `settings[${settingName}][${newLang}]`);+ };- data.editor.setData(storedValue);- data.textArea.attr('name', `settings[${data.settingName}][${data.newLang}]`);+ document.querySelectorAll<HTMLSelectElement>('.lang-select-switch')+ .forEach((selectSwitch) => {+ selectSwitch.addEventListener('focus', langSelectSwitchFocusListener);+ selectSwitch.addEventListener('change', langSelectSwitchChangeListener);});/* end Javascript for Settings::TextSettingComponent */diff --git a/frontend/src/app/shared/components/editor/components/ckeditor-augmented-textarea/ckeditor-augmented-textarea.component.ts b/frontend/src/app/shared/components/editor/components/ckeditor-augmented-textarea/ckeditor-augmented-textarea.component.tsindex 1738891635d..caecc60da7d 100644--- a/frontend/src/app/shared/components/editor/components/ckeditor-augmented-textarea/ckeditor-augmented-textarea.component.ts+++ b/frontend/src/app/shared/components/editor/components/ckeditor-augmented-textarea/ckeditor-augmented-textarea.component.ts@@ -212,10 +212,6 @@ export class CkeditorAugmentedTextareaComponent extends UntilDestroyedMixin impl}public setup(editor:ICKEditorInstance) {- // Have a hacky way to access the editor from outside of angular.- // This is e.g. employed to set the text from outside to reuse the same editor for different languages.- jQuery(this.element).data('editor', editor);-this.setupMarkingReadonlyWhenTextareaIsDisabled(editor);if (this.halResource?.attachments) {diff --git a/frontend/src/app/shared/components/editor/components/ckeditor/ckeditor.types.ts b/frontend/src/app/shared/components/editor/components/ckeditor/ckeditor.types.tsindex 5366f8ec447..3c4d95580d8 100644--- a/frontend/src/app/shared/components/editor/components/ckeditor/ckeditor.types.ts+++ b/frontend/src/app/shared/components/editor/components/ckeditor/ckeditor.types.ts@@ -107,3 +107,9 @@ export interface ICKEditorContext {// disabled specific mentionsdisabledMentions?:['user'|'work_package'];}++declare global {+ interface HTMLElement {+ ckeditorInstance?:ICKEditorInstance;+ }+}diff --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 344b233e563..f485bc304ab 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@@ -83,9 +83,9 @@ export class OpCkeditorComponent extends UntilDestroyedMixin implements OnInit,@Output() editorFocus = new EventEmitter<string>();// View container of the replacement used to initialize CKEditor5- @ViewChild('opCkeditorReplacementContainer', { static: true }) opCkeditorReplacementContainer:ElementRef;+ @ViewChild('opCkeditorReplacementContainer', { static: true }) opCkeditorReplacementContainer:ElementRef<HTMLDivElement>;- @ViewChild('codeMirrorPane') codeMirrorPane:ElementRef;+ @ViewChild('codeMirrorPane') codeMirrorPane:ElementRef<HTMLDivElement>;// CKEditor instance once initializedpublic watchdog:ICKEditorWatchdog;@@ -118,10 +118,8 @@ export class OpCkeditorComponent extends UntilDestroyedMixin implements OnInit,{ leading: true },);- private $element:JQuery;-constructor(- private readonly elementRef:ElementRef,+ private readonly elementRef:ElementRef<HTMLElement>,private readonly Notifications:ToastService,private readonly I18n:I18nService,private readonly configurationService:ConfigurationService,@@ -223,9 +221,7 @@ export class OpCkeditorComponent extends UntilDestroyedMixin implements OnInit,}private initializeEditor() {- this.$element = jQuery(this.elementRef.nativeElement);-- const editorPromise = this.ckEditorSetup+ void this.ckEditorSetup.create(this.opCkeditorReplacementContainer.nativeElement,this.context,@@ -262,8 +258,6 @@ export class OpCkeditorComponent extends UntilDestroyedMixin implements OnInit,this.initializeDone.emit(watchdog.editor);return watchdog.editor;});-- this.$element.data('editor', editorPromise);}private interceptModifiedEnterKeystrokes(editor:ICKEditorInstance) {@@ -338,7 +332,7 @@ export class OpCkeditorComponent extends UntilDestroyedMixin implements OnInit,const current = this.getRawData();const cmMode = 'gfm';- Promise+ void Promise.all([import('codemirror'),import(/* webpackChunkName: "codemirror-mode" */ `codemirror/mode/${cmMode}/${cmMode}.js`),@@ -346,7 +340,7 @@ export class OpCkeditorComponent extends UntilDestroyedMixin implements OnInit,.then((imported:any[]) => {const CodeMirror = imported[0].default;this.codeMirrorInstance = CodeMirror(- this.$element.find('.ck-editor__source')[0],+ this.elementRef.nativeElement.querySelector('.ck-editor__source'),{lineNumbers: true,smartIndent: true,diff --git a/frontend/src/app/shared/helpers/ckeditor-helpers.ts b/frontend/src/app/shared/helpers/ckeditor-helpers.tsnew file mode 100644index 00000000000..b731d1f7ccb--- /dev/null+++ b/frontend/src/app/shared/helpers/ckeditor-helpers.ts@@ -0,0 +1,39 @@+/*+ * -- 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 { ICKEditorInstance } from 'core-app/shared/components/editor/components/ckeditor/ckeditor.types';++export function retrieveCkEditorInstance(element:HTMLElement):ICKEditorInstance|undefined {+ return getEditableElement(element)?.ckeditorInstance;+}++function getEditableElement(element:HTMLElement):HTMLElement|null {+ return element.querySelector<HTMLElement>('.ck-editor__editable_inline');+}diff --git a/frontend/src/stimulus/controllers/ckeditor-focus.controller.ts b/frontend/src/stimulus/controllers/ckeditor-focus.controller.tsindex c9c3e0c8e27..5456db50de4 100644--- a/frontend/src/stimulus/controllers/ckeditor-focus.controller.ts+++ b/frontend/src/stimulus/controllers/ckeditor-focus.controller.ts@@ -29,7 +29,7 @@*/import { Controller } from '@hotwired/stimulus';-import { ICKEditorInstance } from 'core-app/shared/components/editor/components/ckeditor/ckeditor.types';+import { retrieveCkEditorInstance } from 'core-app/shared/helpers/ckeditor-helpers';export default class extends Controller {static values = { autofocus: Boolean };@@ -46,14 +46,6 @@ export default class extends Controller {focusInput():void {this.element.scrollIntoView({ block: 'center' });-- const ckeditorField = this.editorTarget.querySelector('op-ckeditor') as HTMLElement;- // eslint-disable-next-line @typescript-eslint/no-unsafe-call- void jQuery(ckeditorField)- .data('editor')- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access- .then((editor:ICKEditorInstance) => {- editor.editing.view.focus();- });+ retrieveCkEditorInstance(this.editorTarget)?.editing.view.focus();}}diff --git a/frontend/src/stimulus/controllers/dynamic/forum-messages.controller.ts b/frontend/src/stimulus/controllers/dynamic/forum-messages.controller.tsindex 693b517f69f..dba8d1a9d43 100644--- a/frontend/src/stimulus/controllers/dynamic/forum-messages.controller.ts+++ b/frontend/src/stimulus/controllers/dynamic/forum-messages.controller.ts@@ -29,7 +29,7 @@*/import { Controller } from '@hotwired/stimulus';-import { ICKEditorInstance } from 'core-app/shared/components/editor/components/ckeditor/ckeditor.types';+import { retrieveCkEditorInstance } from 'core-app/shared/helpers/ckeditor-helpers';interface QuoteResult {subject:string;@@ -49,21 +49,19 @@ export default class ForumMessagesController extends Controller {public quote(event:MouseEvent) {event.preventDefault();- const link = (event.target as HTMLElement).closest('a') as HTMLAnchorElement;- const href = link.href;-- void jQuery.getJSON(href)- .done((result:QuoteResult) => this.insertQuoteInReply(result));+ const { href } = (event.target as HTMLElement).closest('a')!;+ void fetch(href, {+ headers: {+ Accept: 'application/json',+ 'X-Authentication-Scheme': 'Session',+ },+ })+ .then((response) => response.json())+ .then((result:QuoteResult) => this.insertQuoteInReply(result));}- private insertQuoteInReply(result:QuoteResult):void {- this.subjectTarget.value = result.subject;-- const ckeditorField = this.replyTarget.querySelector('op-ckeditor') as HTMLElement;-- // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access- void jQuery(ckeditorField)- .data('editor')- .then((editor:ICKEditorInstance) => editor.setData(result.content));+ private insertQuoteInReply({ subject, content }:QuoteResult):void {+ this.subjectTarget.value = subject;+ retrieveCkEditorInstance(this.replyTarget)?.setData(content);}}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 6621b6d96cf..adb94f44ff0 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@@ -35,6 +35,7 @@ import {import { TurboRequestsService } from 'core-app/core/turbo/turbo-requests.service';import { ApiV3Service } from 'core-app/core/apiv3/api-v3.service';import { useMeta } from 'stimulus-use';+import { retrieveCkEditorInstance } from 'core-app/shared/helpers/ckeditor-helpers';enum AnchorType {Comment = 'comment',@@ -48,7 +49,7 @@ interface CustomEventWithIdParam extends Event {};}-export default class IndexController extends Controller {+export default class IndexController extends Controller<HTMLElement> {static values = {updateStreamsPath: String,sorting: String,@@ -130,12 +131,12 @@ export default class IndexController extends Controller {private markAsConnected() {// used in specs for timing- (this.element as HTMLElement).dataset.stimulusControllerConnected = 'true';+ this.element.dataset.stimulusControllerConnected = 'true';}private markAsDisconnected() {// used in specs for timing- (this.element as HTMLElement).dataset.stimulusControllerConnected = 'false';+ this.element.dataset.stimulusControllerConnected = 'false';}private setLocalStorageKeys() {@@ -402,12 +403,9 @@ export default class IndexController extends Controller {}private rescueEditorContent() {- const ckEditorInstance = this.getCkEditorInstance();- if (ckEditorInstance) {- const data = ckEditorInstance.getData({ trim: false });- if (data.length > 0) {- localStorage.setItem(this.rescuedEditorDataKey, data);- }+ const data = this.ckEditorInstance?.getData({ trim: false });+ if (data) {+ localStorage.setItem(this.rescuedEditorDataKey, data);}}@@ -519,13 +517,12 @@ export default class IndexController extends Controller {window.location.hash = `#${anchorName}-${activityId}`;}- private getCkEditorElement():HTMLElement | null {+ private get ckEditorAugmentedTextarea():HTMLElement | null {return this.element.querySelector('opce-ckeditor-augmented-textarea');}- getCkEditorInstance():ICKEditorInstance | null {- const AngularCkEditorElement = this.getCkEditorElement();- return AngularCkEditorElement ? jQuery(AngularCkEditorElement).data('editor') as ICKEditorInstance : null;+ get ckEditorInstance():ICKEditorInstance | undefined {+ return retrieveCkEditorInstance(this.element);}private getInputContainer():HTMLElement | null {@@ -587,7 +584,7 @@ export default class IndexController extends Controller {},};- const editorElement = this.getCkEditorElement();+ const editorElement = this.ckEditorAugmentedTextarea;if (editorElement) {editorElement.addEventListener('editorEscape', handlers.onEscapeEditor, { signal });editorElement.addEventListener('editorKeyup', handlers.adjustMargin, { signal });@@ -667,7 +664,7 @@ export default class IndexController extends Controller {}focusEditor(timeout:number = 10) {- const ckEditorInstance = this.getCkEditorInstance();+ const ckEditorInstance = this.ckEditorInstance;if (ckEditorInstance) {setTimeout(() => ckEditorInstance.editing.view.focus(), timeout);}@@ -675,14 +672,13 @@ export default class IndexController extends Controller {openEditorWithInitialData(quotedText:string) {this.showForm();- const ckEditorInstance = this.getCkEditorInstance();- if (ckEditorInstance && ckEditorInstance.getData({ trim: false }).length === 0) {- ckEditorInstance.setData(quotedText);+ if (this.isEditorEmpty()) {+ this.ckEditorInstance!.setData(quotedText);}}clearEditor() {- this.getCkEditorInstance()?.setData('');+ this.ckEditorInstance?.setData('');}hideEditor() {@@ -728,9 +724,7 @@ export default class IndexController extends Controller {}private isEditorEmpty():boolean {- const ckEditorInstance = this.getCkEditorInstance();-- return !!(ckEditorInstance?.getData({ trim: false }).length === 0);+ return this.ckEditorInstance?.getData({ trim: false }) === '';}private handleTurboSubmitStart(_event:Event) {@@ -769,15 +763,12 @@ export default class IndexController extends Controller {}private setCKEditorReadonlyMode(disabled:boolean) {- const ckEditorInstance = this.getCkEditorInstance();const editorLockID = 'work-packages-activities-tab-index-component';- if (ckEditorInstance) {- if (disabled) {- ckEditorInstance.enableReadOnlyMode(editorLockID);- } else {- ckEditorInstance.disableReadOnlyMode(editorLockID);- }+ if (disabled) {+ this.ckEditorInstance?.enableReadOnlyMode(editorLockID);+ } else {+ this.ckEditorInstance?.disableReadOnlyMode(editorLockID);}}diff --git a/frontend/src/stimulus/controllers/dynamic/work-packages/activities-tab/internal-comment.controller.ts b/frontend/src/stimulus/controllers/dynamic/work-packages/activities-tab/internal-comment.controller.tsindex cf40b7d7cbc..f1278f7e865 100644--- a/frontend/src/stimulus/controllers/dynamic/work-packages/activities-tab/internal-comment.controller.ts+++ b/frontend/src/stimulus/controllers/dynamic/work-packages/activities-tab/internal-comment.controller.ts@@ -158,6 +158,6 @@ export default class InternalCommentController extends Controller {}private get ckEditorInstance() {- return this.workPackagesActivitiesTabIndexOutlet.getCkEditorInstance();+ return this.workPackagesActivitiesTabIndexOutlet.ckEditorInstance;}}diff --git a/frontend/src/stimulus/controllers/dynamic/work-packages/activities-tab/quote-comment.controller.ts b/frontend/src/stimulus/controllers/dynamic/work-packages/activities-tab/quote-comment.controller.tsindex 5ab07e806f8..c1ec4b62648 100644--- a/frontend/src/stimulus/controllers/dynamic/work-packages/activities-tab/quote-comment.controller.ts+++ b/frontend/src/stimulus/controllers/dynamic/work-packages/activities-tab/quote-comment.controller.ts@@ -92,7 +92,7 @@ export default class QuoteCommentController extends Controller {}private get ckEditorInstance() {- return this.workPackagesActivitiesTabIndexOutlet.getCkEditorInstance();+ return this.workPackagesActivitiesTabIndexOutlet.ckEditorInstance;}private get isFormVisible():boolean {