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
Let progress/preview controller inherit from the generic workpackage/dialog/preview controller again while keeping the special behaviour of focus/blur events.
Henriette Dargea7af3736cbf2
diff --git a/app/forms/work_packages/progress_form.rb b/app/forms/work_packages/progress_form.rbindex 5c9e8267944..bd486c99150 100644--- a/app/forms/work_packages/progress_form.rb+++ b/app/forms/work_packages/progress_form.rb@@ -197,7 +197,7 @@ class WorkPackages::ProgressForm < ApplicationFormenddef default_field_options(name)- data = { "work-packages--progress--preview-target": "progressInput",+ data = { "work-packages--progress--preview-target": "fieldInput",action: "work-packages--progress--preview#markFieldAsTouched" }if @focused_field == namediff --git a/frontend/src/stimulus/controllers/dynamic/work-packages/date-picker/preview.controller.ts b/frontend/src/stimulus/controllers/dynamic/work-packages/date-picker/preview.controller.tsindex 30454c71f45..3053be19883 100644--- a/frontend/src/stimulus/controllers/dynamic/work-packages/date-picker/preview.controller.ts+++ b/frontend/src/stimulus/controllers/dynamic/work-packages/date-picker/preview.controller.ts@@ -30,6 +30,10 @@import { DialogPreviewController } from '../dialog/preview.controller';import { TimezoneService } from 'core-app/core/datetime/timezone.service';+import {+ debounce,+ DebouncedFunc,+} from 'lodash';export default class PreviewController extends DialogPreviewController {static values = {@@ -51,7 +55,19 @@ export default class PreviewController extends DialogPreviewController {private handleFlatpickrDatesChangedBound = this.handleFlatpickrDatesChanged.bind(this);+ private debouncedDelayedPreview:DebouncedFunc<(input:HTMLInputElement) => void>;+ private debouncedImmediatePreview:DebouncedFunc<(input:HTMLInputElement) => void>;+async connect() {+ // if the debounce value is changed, the following test helper must be kept+ // in sync: `spec/support/edit_fields/progress_edit_field.rb`, method `#wait_for_preview_to_complete`+ this.debouncedDelayedPreview = debounce((input:HTMLInputElement) => {+ void this.preview(input);+ }, 200);+ this.debouncedImmediatePreview = debounce((input:HTMLInputElement) => {+ void this.preview(input);+ }, 0);+this.readInitialValues();super.connect();@@ -63,6 +79,10 @@ export default class PreviewController extends DialogPreviewController {disconnect() {document.removeEventListener('date-picker:flatpickr-dates-changed', this.handleFlatpickrDatesChangedBound);++ this.debouncedDelayedPreview.cancel();+ this.debouncedImmediatePreview.cancel();+super.disconnect();}@@ -70,7 +90,23 @@ export default class PreviewController extends DialogPreviewController {await super.preview(field, [{ key: 'date_mode', val: this.dateModeValue }]);}- inputChanged(event:Event) {+ registerFieldInputListeners() {+ this.fieldInputTargets.forEach((target) => {+ target.addEventListener('input', this.inputChanged.bind(this));++ if (target.dataset.focus === 'true') {+ this.focusAndSetCursorPositionToEndOfInput(target);+ }+ });+ }++ unregisterFieldInputListeners() {+ this.fieldInputTargets.forEach((target) => {+ target.removeEventListener('input', this.inputChanged.bind(this));+ });+ }++ private inputChanged(event:Event) {const field = event.target as HTMLInputElement;if (field.name === 'work_package[start_date]') {@@ -128,7 +164,7 @@ export default class PreviewController extends DialogPreviewController {}this.updateFlatpickrCalendar();if (fieldUpdatedWithUserValue) {- this.triggerImmediatePreview(fieldUpdatedWithUserValue);+ this.debouncedImmediatePreview(fieldUpdatedWithUserValue);}}diff --git a/frontend/src/stimulus/controllers/dynamic/work-packages/dialog/preview.controller.ts b/frontend/src/stimulus/controllers/dynamic/work-packages/dialog/preview.controller.tsindex 3508a7d2989..9d4f5ca535d 100644--- a/frontend/src/stimulus/controllers/dynamic/work-packages/dialog/preview.controller.ts+++ b/frontend/src/stimulus/controllers/dynamic/work-packages/dialog/preview.controller.ts@@ -29,10 +29,6 @@*/import { Controller } from '@hotwired/stimulus';-import {- debounce,- DebouncedFunc,-} from 'lodash';import Idiomorph from 'idiomorph/dist/idiomorph.cjs';interface TurboBeforeFrameRenderEventDetail {@@ -56,11 +52,9 @@ export abstract class DialogPreviewController extends Controller {declare readonly initialValueInputTargets:HTMLInputElement[];declare readonly touchedFieldInputTargets:HTMLInputElement[];- protected debouncedDelayedPreview:DebouncedFunc<(input:HTMLInputElement) => void>;- protected debouncedImmediatePreview:DebouncedFunc<(input:HTMLInputElement) => void>;- private frameMorphRenderer:(event:CustomEvent<TurboBeforeFrameRenderEventDetail>) => void;- private targetFieldName:string;- private touchedFields:Set<string>;+ protected frameMorphRenderer:(event:CustomEvent<TurboBeforeFrameRenderEventDetail>) => void;+ protected targetFieldName:string;+ protected touchedFields:Set<string>;connect() {this.touchedFields = new Set();@@ -71,15 +65,6 @@ export abstract class DialogPreviewController extends Controller {}});- // if the debounce value is changed, the following test helper must be kept- // in sync: `spec/support/edit_fields/progress_edit_field.rb`, method `#wait_for_preview_to_complete`- this.debouncedDelayedPreview = debounce((input:HTMLInputElement) => {- void this.preview(input);- }, 200);- this.debouncedImmediatePreview = debounce((input:HTMLInputElement) => {- void this.preview(input);- }, 0);-// Turbo supports morphing, by adding the <turbo-frame refresh="morph">// attribute. However, it does not work that well with primer input: when// adding "data-turbo-permanent" to keep value and focus on the active@@ -103,36 +88,24 @@ export abstract class DialogPreviewController extends Controller {};};- this.fieldInputTargets.forEach((target) => {- target.addEventListener('input', this.inputChanged.bind(this));-- if (target.dataset.focus === 'true') {- this.focusAndSetCursorPositionToEndOfInput(target);- }- });+ this.registerFieldInputListeners();const turboFrame = this.formTarget.closest('turbo-frame') as HTMLTurboFrameElement;turboFrame.addEventListener('turbo:before-frame-render', this.frameMorphRenderer);}disconnect() {- this.debouncedDelayedPreview.cancel();- this.debouncedImmediatePreview.cancel();- this.fieldInputTargets.forEach((target) => {- target.removeEventListener('input', this.inputChanged.bind(this));- });+ this.unregisterFieldInputListeners();const turboFrame = this.formTarget.closest('turbo-frame') as HTMLTurboFrameElement;if (turboFrame) {turboFrame.removeEventListener('turbo:before-frame-render', this.frameMorphRenderer);}}- // eslint-disable-next-line no-unused-vars,@typescript-eslint/no-unused-vars- inputChanged(event:Event) {+ registerFieldInputListeners() {}- protected triggerImmediatePreview(input:HTMLInputElement) {- this.debouncedImmediatePreview(input);+ unregisterFieldInputListeners() {}protected cancel():void {@@ -175,7 +148,7 @@ export abstract class DialogPreviewController extends Controller {}}- private focusAndSetCursorPositionToEndOfInput(field:HTMLInputElement) {+ protected focusAndSetCursorPositionToEndOfInput(field:HTMLInputElement) {field.focus();field.setSelectionRange(field.value.length,diff --git a/frontend/src/stimulus/controllers/dynamic/work-packages/progress/preview.controller.ts b/frontend/src/stimulus/controllers/dynamic/work-packages/progress/preview.controller.tsindex 1aa2b53c85b..c4d6e491eeb 100644--- a/frontend/src/stimulus/controllers/dynamic/work-packages/progress/preview.controller.ts+++ b/frontend/src/stimulus/controllers/dynamic/work-packages/progress/preview.controller.ts@@ -28,64 +28,35 @@* ++*/-import { Controller } from '@hotwired/stimulus';import { debounce, DebouncedFunc } from 'lodash';-import Idiomorph from 'idiomorph/dist/idiomorph.cjs';--interface TurboBeforeFrameRenderEventDetail {- render:(currentElement:HTMLElement, newElement:HTMLElement) => void;-}--interface HTMLTurboFrameElement extends HTMLElement {- src:string;-}--export default class PreviewController extends Controller {- static targets = [- 'form',- 'progressInput',- 'initialValueInput',- 'touchedFieldInput',- ];-- declare readonly progressInputTargets:HTMLInputElement[];- declare readonly formTarget:HTMLFormElement;- declare readonly initialValueInputTargets:HTMLInputElement[];- declare readonly touchedFieldInputTargets:HTMLInputElement[];+import { DialogPreviewController } from '../dialog/preview.controller';+export default class PreviewController extends DialogPreviewController {private debouncedPreview:DebouncedFunc<(event:Event) => void>;- private frameMorphRenderer:(event:CustomEvent<TurboBeforeFrameRenderEventDetail>) => void;- private targetFieldName:string;- private touchedFields:Set<string>;connect() {- this.touchedFields = new Set();- this.touchedFieldInputTargets.forEach((input) => {- const fieldName = input.dataset.referrerField;- if (fieldName && input.value === 'true') {- this.touchedFields.add(fieldName);+ this.debouncedPreview = debounce((event:Event) => {+ let field:HTMLInputElement;+ if (event.type === 'blur') {+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ field = (event as FocusEvent).relatedTarget as HTMLInputElement;+ } else {+ field = event.target as HTMLInputElement;}- });- // if the debounce value is changed, the following test helper must be kept- // in sync: `spec/support/edit_fields/progress_edit_field.rb`, method `#wait_for_preview_to_complete`- this.debouncedPreview = debounce((event:Event) => { void this.preview(event); }, 200);+ void this.preview(field);+ }, 100);++ super.connect();+ }- // Turbo supports morphing, by adding the <turbo-frame refresh="morph">- // attribute. However, it does not work that well with primer input: when- // adding "data-turbo-permanent" to keep value and focus on the active- // element, it also keeps the `aria-describedby` attribute which references- // caption and validation element ids. As these elements are morphed and get- // new ids, the ids referenced by `aria-describedby` are stale. This makes- // caption and validation message unaccessible for screen readers and other- // assistive technologies. This is why morph cannot be used here.- this.frameMorphRenderer = (event:CustomEvent<TurboBeforeFrameRenderEventDetail>) => {- event.detail.render = (currentElement:HTMLElement, newElement:HTMLElement) => {- Idiomorph.morph(currentElement, newElement, { ignoreActiveValue: true });- };- };+ disconnect() {+ this.debouncedPreview.cancel();+ super.disconnect();+ }- this.progressInputTargets.forEach((target) => {+ registerFieldInputListeners() {+ this.fieldInputTargets.forEach((target) => {if (target.tagName.toLowerCase() === 'select') {target.addEventListener('change', this.debouncedPreview);} else {@@ -97,14 +68,10 @@ export default class PreviewController extends Controller {this.focusAndSetCursorPositionToEndOfInput(target);}});-- const turboFrame = this.formTarget.closest('turbo-frame') as HTMLTurboFrameElement;- turboFrame.addEventListener('turbo:before-frame-render', this.frameMorphRenderer);}- disconnect() {- this.debouncedPreview.cancel();- this.progressInputTargets.forEach((target) => {+ unregisterFieldInputListeners() {+ this.fieldInputTargets.forEach((target) => {if (target.tagName.toLowerCase() === 'select') {target.removeEventListener('change', this.debouncedPreview);} else {@@ -112,60 +79,15 @@ export default class PreviewController extends Controller {}target.removeEventListener('blur', this.debouncedPreview);});- const turboFrame = this.formTarget.closest('turbo-frame') as HTMLTurboFrameElement;- if (turboFrame) {- turboFrame.removeEventListener('turbo:before-frame-render', this.frameMorphRenderer);- }- }-- markFieldAsTouched(event:{ target:HTMLInputElement }) {- this.targetFieldName = event.target.name.replace(/^work_package\[([^\]]+)\]$/, '$1');- this.markTouched(this.targetFieldName);-- if (this.isWorkBasedMode()) {- this.keepWorkValue();- }- }-- async preview(event:Event) {- let field:HTMLInputElement;- if (event.type === 'blur') {- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access- field = (event as FocusEvent).relatedTarget as HTMLInputElement;- } else {- field = event.target as HTMLInputElement;- }-- const form = this.formTarget;- const formData = new FormData(form) as unknown as undefined;- const formParams = new URLSearchParams(formData);-- const wpParams = Array.from(formParams.entries())- .filter(([key, _]) => key.startsWith('work_package'));- wpParams.push(['field', field?.name ?? '']);-- const wpPath = this.ensureValidPathname(form.action);- const wpAction = wpPath.endsWith('/work_packages/new/progress') ? 'new' : 'edit';-- const editUrl = `${wpPath}/${wpAction}?${new URLSearchParams(wpParams).toString()}`;- const turboFrame = this.formTarget.closest('turbo-frame') as HTMLTurboFrameElement;-- if (turboFrame) {- turboFrame.src = editUrl;- }}- private focusAndSetCursorPositionToEndOfInput(field:HTMLInputElement) {- field.focus();- field.setSelectionRange(- field.value.length,- field.value.length,- );+ afterRendering():void {+ // Do nothing;}// Ensures that on create forms, there is an "id" for the un-persisted// work package when sending requests to the edit action for previews.- private ensureValidPathname(formAction:string):string {+ ensureValidPathname(formAction:string):string {const wpPath = new URL(formAction);if (wpPath.pathname.endsWith('/work_packages/progress')) {@@ -176,126 +98,20 @@ export default class PreviewController extends Controller {return wpPath.toString();}- private isWorkBasedMode() {- return this.findValueInput('done_ratio') !== undefined;+ ensureValidWpAction(wpPath:string):string {+ return wpPath.endsWith('/work_packages/new/progress') ? 'new' : 'edit';}- private keepWorkValue() {- if (this.isInitialValueEmpty('estimated_hours') && !this.isTouched('estimated_hours')) {- // let work be derived- return;- }-- if (this.isBeingEdited('estimated_hours')) {- this.untouchFieldsWhenWorkIsEdited();- } else if (this.isBeingEdited('remaining_hours')) {- this.untouchFieldsWhenRemainingWorkIsEdited();- } else if (this.isBeingEdited('done_ratio')) {- this.untouchFieldsWhenPercentCompleteIsEdited();- }- }-- private untouchFieldsWhenWorkIsEdited() {- if (this.areBothTouched('remaining_hours', 'done_ratio')) {- if (this.isValueEmpty('done_ratio') && this.isValueEmpty('remaining_hours')) {- return;- }- if (this.isValueEmpty('done_ratio')) {- this.markUntouched('done_ratio');- } else {- this.markUntouched('remaining_hours');- }- } else if (this.isTouchedAndEmpty('remaining_hours') && this.isValueSet('done_ratio')) {- // force remaining work derivation- this.markUntouched('remaining_hours');- this.markTouched('done_ratio');- } else if (this.isTouchedAndEmpty('done_ratio') && this.isValueSet('remaining_hours')) {- // force % complete derivation- this.markUntouched('done_ratio');- this.markTouched('remaining_hours');- }- }-- private untouchFieldsWhenRemainingWorkIsEdited() {- if (this.isTouchedAndEmpty('estimated_hours') && this.isValueSet('done_ratio')) {- // force work derivation- this.markUntouched('estimated_hours');- this.markTouched('done_ratio');- } else if (this.isValueSet('estimated_hours')) {- this.markUntouched('done_ratio');- }- }+ markFieldAsTouched(event:{ target:HTMLInputElement }) {+ this.targetFieldName = event.target.name.replace(/^work_package\[([^\]]+)\]$/, '$1');+ this.markTouched(this.targetFieldName);- private untouchFieldsWhenPercentCompleteIsEdited() {- if (this.isValueSet('estimated_hours')) {- this.markUntouched('remaining_hours');+ if (this.isWorkBasedMode()) {+ this.keepFieldValueWithPriority('estimated_hours', 'remaining_hours', 'done_ratio');}}- private areBothTouched(fieldName1:string, fieldName2:string) {- return this.isTouched(fieldName1) && this.isTouched(fieldName2);- }-- private isBeingEdited(fieldName:string) {- return fieldName === this.targetFieldName;- }-- // Finds the hidden initial value input based on a field name.- //- // The initial value input field holds the initial value of the work package- // before being set by the user or derived.- private findInitialValueInput(fieldName:string):HTMLInputElement|undefined {- return this.initialValueInputTargets.find((input) =>- (input.dataset.referrerField === fieldName));- }-- // Finds the value field input based on a field name.- //- // The value field input holds the current value of a progress field.- private findValueInput(fieldName:string):HTMLInputElement|undefined {- return this.progressInputTargets.find((input) =>- (input.name === fieldName) || (input.name === `work_package[${fieldName}]`));- }-- private isTouchedAndEmpty(fieldName:string) {- return this.isTouched(fieldName) && this.isValueEmpty(fieldName);- }-- private isTouched(fieldName:string) {- return this.touchedFields.has(fieldName);- }-- private isInitialValueEmpty(fieldName:string) {- const valueInput = this.findInitialValueInput(fieldName);- return valueInput?.value === '';- }-- private isValueEmpty(fieldName:string) {- const valueInput = this.findValueInput(fieldName);- return valueInput?.value === '';- }-- private isValueSet(fieldName:string) {- const valueInput = this.findValueInput(fieldName);- return valueInput !== undefined && valueInput.value !== '';- }-- private markTouched(fieldName:string) {- this.touchedFields.add(fieldName);- this.updateTouchedFieldHiddenInputs();- }-- private markUntouched(fieldName:string) {- this.touchedFields.delete(fieldName);- this.updateTouchedFieldHiddenInputs();- }-- private updateTouchedFieldHiddenInputs() {- this.touchedFieldInputTargets.forEach((input) => {- const fieldName = input.dataset.referrerField;- if (fieldName) {- input.value = this.isTouched(fieldName) ? 'true' : 'false';- }- });+ private isWorkBasedMode() {+ return this.findValueInput('done_ratio') !== undefined;}}