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
Extract logic of the progress modal to be reused for the datepicker modal as well
Henriette Dargec597e9155aeb
diff --git a/app/components/work_packages/date_picker/dialog_content_component.html.erb b/app/components/work_packages/date_picker/dialog_content_component.html.erbindex def051400c9..879997787d5 100644--- a/app/components/work_packages/date_picker/dialog_content_component.html.erb+++ b/app/components/work_packages/date_picker/dialog_content_component.html.erb@@ -1,98 +1,83 @@<%=- component_wrapper do- component_collection do |collection|- if show_banner?- collection.with_component(WorkPackages::DatePicker::BannerComponent.new(work_package:, manually_scheduled:))- end+ content_tag("turbo-frame", id: "wp-datepicker-dialog--content") do+ component_wrapper do+ component_collection do |collection|+ if show_banner?+ collection.with_component(WorkPackages::DatePicker::BannerComponent.new(work_package:, manually_scheduled:))+ end- collection.with_component(Primer::Alpha::Dialog::Body.new) do- primer_form_with(- model: work_package,- url: work_package_datepicker_dialog_content_path,- method: :put,- id: DIALOG_FORM_ID,- html: { autocomplete: "off" },- ) do |f|- flex_layout do |body|- body.with_row(mb: 3) do- flex_layout(align_items: :flex_end, justify_content: :space_between) do |first_row|- first_row.with_column do- render(Primer::Alpha::FormControl.new(label: I18n.t("work_packages.datepicker_modal.mode.title"))) do |component|- component.with_input do- render(Primer::Alpha::SegmentedControl.new("aria-label": I18n.t("work_packages.datepicker_modal.mode.title"))) do |control|- control.with_item(tag: :a,- href: work_package_datepicker_dialog_content_path(manually_scheduled: true),- data: { turbo_stream: true },- label: I18n.t("work_packages.datepicker_modal.mode.manual"),- title: I18n.t("work_packages.datepicker_modal.mode.manual"),- selected: manually_scheduled)- control.with_item(tag: :a,- href: work_package_datepicker_dialog_content_path(manually_scheduled: false),- data: { turbo_stream: true },- label: I18n.t("work_packages.datepicker_modal.mode.automatic"),- title: I18n.t("work_packages.datepicker_modal.mode.automatic"),- selected: !manually_scheduled)+ collection.with_component(Primer::Alpha::Dialog::Body.new) do+ primer_form_with(+ model: work_package,+ url: work_package_datepicker_dialog_content_path,+ method: :put,+ id: DIALOG_FORM_ID,+ data: { "application-target": "dynamic",+ "work-packages--date-picker--preview-target": "form",+ controller: "work-packages--date-picker--preview" },+ html: { autocomplete: "off" },+ ) do |f|+ flex_layout do |body|+ body.with_row(mb: 3) do+ flex_layout(align_items: :flex_end, justify_content: :space_between) do |first_row|+ first_row.with_column do+ render(Primer::Alpha::FormControl.new(label: I18n.t("work_packages.datepicker_modal.mode.title"))) do |component|+ component.with_input do+ render(Primer::Alpha::SegmentedControl.new("aria-label": I18n.t("work_packages.datepicker_modal.mode.title"))) do |control|+ control.with_item(tag: :a,+ href: work_package_datepicker_dialog_content_path(manually_scheduled: true),+ data: { turbo_stream: true },+ label: I18n.t("work_packages.datepicker_modal.mode.manual"),+ title: I18n.t("work_packages.datepicker_modal.mode.manual"),+ selected: manually_scheduled)+ control.with_item(tag: :a,+ href: work_package_datepicker_dialog_content_path(manually_scheduled: false),+ data: { turbo_stream: true },+ label: I18n.t("work_packages.datepicker_modal.mode.automatic"),+ title: I18n.t("work_packages.datepicker_modal.mode.automatic"),+ selected: !manually_scheduled)+ endendendend- end- first_row.with_column(mb: 1) do- render(Primer::Alpha::CheckBox.new(name: "ignore_non_working_days",- label: I18n.t("work_packages.datepicker_modal.ignore_non_working_days.title"),- checked: work_package.ignore_non_working_days))+ first_row.with_column(mb: 1) do+ render(Primer::Alpha::CheckBox.new(name: "ignore_non_working_days",+ label: I18n.t("work_packages.datepicker_modal.ignore_non_working_days.title"),+ checked: work_package.ignore_non_working_days))+ endendend- end- body.with_row(mb: 3) do- flex_layout(justify_content: :space_between) do |second_row|- second_row.with_column(mr: 3) do- render(Primer::Alpha::TextField.new(name: :start_date,- label: I18n.t("attributes.start_date"),- data: {- focus: focused_field == :start_date,- },- value: work_package.start_date))- end- second_row.with_column(mr: 3) do- render(Primer::Alpha::TextField.new(name: :due_date,- label: I18n.t("attributes.due_date"),- data: {- focus: focused_field == :start_date,- },- value: work_package.due_date))- end- second_row.with_column do- render(Primer::Alpha::TextField.new(name: :duration,- type: "number",- label: I18n.t("activerecord.attributes.work_package.duration"),- value: work_package.duration))- end+ body.with_row(mb: 3) do+ render(WorkPackages::DatePicker::Form.new(f,+ work_package:,+ focused_field:,+ touched_field_map:))end- end- body.with_row(mb: 3) do- helpers.angular_component_tag "opce-wp-modal-date-picker",- inputs: {- start_date: work_package.start_date,- due_date: work_package.due_date,- ignore_non_working_days: work_package.ignore_non_working_days,- schedule_manually: manually_scheduled- }+ body.with_row(mb: 3) do+ helpers.angular_component_tag "opce-wp-modal-date-picker",+ inputs: {+ start_date: work_package.start_date,+ due_date: work_package.due_date,+ ignore_non_working_days: work_package.ignore_non_working_days,+ schedule_manually: manually_scheduled+ }+ endendendend- end- collection.with_component(Primer::Alpha::Dialog::Footer.new) do- component_collection do |footer|- footer.with_component(Primer::ButtonComponent.new) do- I18n.t("button_cancel")- end+ collection.with_component(Primer::Alpha::Dialog::Footer.new) do+ component_collection do |footer|+ footer.with_component(Primer::ButtonComponent.new) do+ I18n.t("button_cancel")+ end- footer.with_component(Primer::ButtonComponent.new(scheme: :primary, type: :submit, form: DIALOG_FORM_ID)) do- I18n.t("button_submit")+ footer.with_component(Primer::ButtonComponent.new(scheme: :primary, type: :submit, form: DIALOG_FORM_ID)) do+ I18n.t("button_submit")+ endendendenddiff --git a/app/controllers/work_packages/date_picker_controller.rb b/app/controllers/work_packages/date_picker_controller.rbindex b8837108fd0..6ea9fb32309 100644--- a/app/controllers/work_packages/date_picker_controller.rb+++ b/app/controllers/work_packages/date_picker_controller.rb@@ -38,7 +38,7 @@ class WorkPackages::DatePickerController < ApplicationControllerlayout falsebefore_action :find_work_package- authorization_checked! :show, :update+ authorization_checked! :show, :update, :editattr_accessor :work_package@@ -59,6 +59,12 @@ class WorkPackages::DatePickerController < ApplicationControllerendend+ def edit+ set_date_attributes_to_work_package++ render datepicker_modal_component+ end+def update# Todoparams[:duration] = params[:duration].to_i@@ -91,7 +97,9 @@ class WorkPackages::DatePickerController < ApplicationControllerprivatedef datepicker_modal_component- WorkPackages::DatePicker::DialogContentComponent.new(work_package: @work_package, manually_scheduled:, focused_field:,+ WorkPackages::DatePicker::DialogContentComponent.new(work_package: @work_package,+ manually_scheduled:,+ focused_field:,touched_field_map:)end@@ -104,7 +112,8 @@ class WorkPackages::DatePickerController < ApplicationControllerenddef touched_field_map- params.slice("schedule_manually_touched",+ params.require(:work_package)+ .slice("schedule_manually_touched","ignore_non_working_days_touched","start_date_touched","due_date_touched",@@ -122,19 +131,28 @@ class WorkPackages::DatePickerController < ApplicationControllerenddef work_package_datepicker_params- params.slice(*allowed_params)+ params.require(:work_package)+ .slice(*allowed_touched_params).permit!end- # def allowed_touched_params- # allowed_params.filter { touched?(_1) }- # end+ def allowed_touched_params+ allowed_params.filter { touched?(_1) }+ enddef allowed_params%i[schedule_manually ignore_non_working_days start_date due_date duration]end- # def touched?(field)- # touched_field_map[:"#{field}_touched"]- # end+ def touched?(field)+ touched_field_map[:"#{field}_touched"]+ end++ def set_date_attributes_to_work_package+ WorkPackages::SetAttributesService+ .new(user: current_user,+ model: @work_package,+ contract_class: WorkPackages::CreateContract)+ .call(work_package_datepicker_params)+ endenddiff --git a/app/forms/work_packages/date_picker/form.rb b/app/forms/work_packages/date_picker/form.rbnew file mode 100644index 00000000000..7854e155114--- /dev/null+++ b/app/forms/work_packages/date_picker/form.rb@@ -0,0 +1,150 @@+# -- copyright+# OpenProject is an open source project management software.+# Copyright (C) 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.+# ++++module WorkPackages+ module DatePicker+ class Form < ApplicationForm+ ##+ # Primer::Forms::BaseComponent or ApplicationForm will always autofocus the+ # first input field with an error present on it. Despite this behavior being+ # a11y-friendly, it breaks the modal's UX when an invalid input field+ # is rendered.+ #+ # The reason for this is since we're implementing a "format on blur", when+ # we make a request to the server that will set an input field in an invalid+ # state and it is returned as such, any time we blur this autofocused field,+ # we'll perform another request that will still have the input in an invalid+ # state causing it to autofocus again and preventing us from leaving this+ # "limbo state".+ ##+ def before_render+ # no-op+ end++ attr_reader :work_package++ def initialize(work_package:,+ focused_field: :start_date,+ touched_field_map: {})+ super()++ @work_package = work_package+ @focused_field = focused_field_by_selection(focused_field)+ @touched_field_map = touched_field_map+ end++ form do |query_form|+ query_form.group(layout: :horizontal) do |group|+ text_field(group, name: :start_date, label: I18n.t("attributes.start_date"))+ text_field(group, name: :due_date, label: I18n.t("attributes.due_date"))+ text_field(group, name: :duration, label: I18n.t("activerecord.attributes.work_package.duration"))++ hidden_touched_field(group, name: :start_date)+ hidden_touched_field(group, name: :due_date)+ hidden_touched_field(group, name: :duration)++ group.fields_for(:initial) do |builder|+ WorkPackages::DatePicker::InitialValuesForm.new(builder, work_package:)+ end+ end+ end++ private++ def focused_field_by_selection(field)+ field+ end++ def text_field(group,+ name:,+ label:)+ text_field_options = default_field_options(name).merge(+ name:,+ value: field_value(name),+ label:,+ validation_message: validation_message(name)+ )++ group.text_field(**text_field_options)+ end++ def readonly_text_field(group,+ name:,+ label:,+ placeholder: true)+ text_field_options = default_field_options(name).merge(+ name:,+ value: field_value(name),+ label:,+ readonly: true,+ classes: "input--readonly",+ placeholder: ("-" if placeholder)+ )++ group.text_field(**text_field_options)+ end++ def hidden_touched_field(group, name:)+ group.hidden(name: :"#{name}_touched",+ value: touched(name),+ data: { "work-packages--date-picker--preview-target": "touchedFieldInput",+ "referrer-field": name })+ end++ def touched(name)+ @touched_field_map["#{name}_touched"] || false+ end++ def field_value(name)+ errors = @work_package.errors.where(name)+ if (user_value = errors.map { |error| error.options[:value] }.find { !_1.nil? })+ user_value+ else+ # TODO+ @work_package.public_send(name)+ end+ end++ def validation_message(name)+ # it's ok to take the first error only, that's how primer_view_component does it anyway.+ message = @work_package.errors.messages_for(name).first+ message&.upcase_first+ end++ def default_field_options(name)+ data = { "work-packages--date-picker--preview-target": "fieldInput",+ action: "work-packages--date-picker--preview#markFieldAsTouched" }++ if @focused_field == name+ data[:focus] = "true"+ end+ { data: }+ end+ end+ end+enddiff --git a/app/forms/work_packages/date_picker/initial_values_form.rb b/app/forms/work_packages/date_picker/initial_values_form.rbnew file mode 100644index 00000000000..f25ab2891e1--- /dev/null+++ b/app/forms/work_packages/date_picker/initial_values_form.rb@@ -0,0 +1,56 @@+# -- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2010-2024 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.+# ++++module WorkPackages+ module DatePicker+ class InitialValuesForm < ApplicationForm+ attr_reader :work_package++ def initialize(work_package:)+ super()++ @work_package = work_package+ end++ form do |form|+ hidden_initial_field(form, name: :start_date)+ hidden_initial_field(form, name: :due_date)+ hidden_initial_field(form, name: :duration)+ end++ private++ def hidden_initial_field(form, name:)+ form.hidden(name:,+ value: work_package.public_send(:"#{name}_was"),+ data: { "work-packages--date-pick--preview-target": "initialValueInput",+ "referrer-field": name })+ end+ end+ end+enddiff --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/app/views/work_packages/date_picker/show.html.erb b/app/views/work_packages/date_picker/show.html.erbindex 41f3b4acece..99b8728d991 100644--- a/app/views/work_packages/date_picker/show.html.erb+++ b/app/views/work_packages/date_picker/show.html.erb@@ -1,5 +1 @@-<%=- content_tag("turbo-frame", id: "wp-datepicker-dialog--content") do- render(WorkPackages::DatePicker::DialogContentComponent.new(work_package:, manually_scheduled:))- end-%>+<%= render(WorkPackages::DatePicker::DialogContentComponent.new(work_package:, manually_scheduled:))%>diff --git a/config/routes.rb b/config/routes.rbindex 9135b56335e..435f8007db3 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -656,6 +656,18 @@ Rails.application.routes.draw docontroller: "work_packages/progress",as: :work_package_progressend+ resource :datepicker_dialog_content,+ only: %i[show new edit update],+ controller: "work_packages/date_picker",+ on: :member,+ as: "datepicker_dialog_content"+ collection do+ resource :progress,+ only: :create,+ controller: "work_packages/date_picker",+ as: :work_package_progress+ end+resources :relations_tab, only: %i[index], controller: "work_package_relations_tab"resources :relations, only: %i[new create edit update destroy], controller: "work_package_relations"@@ -668,8 +680,6 @@ Rails.application.routes.draw doget "/export_dialog" => "work_packages#export_dialog", on: :collection, as: "export_dialog"get :show_conflict_flash_message, on: :collection # we don't need a specific work package for this- resource :datepicker_dialog_content, controller: "work_packages/date_picker", on: :member, as: "datepicker_dialog_content"-get "/split_view/update_counter" => "work_packages/split_view#update_counter",on: :memberdiff --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.tsnew file mode 100644index 00000000000..31571af169c--- /dev/null+++ b/frontend/src/stimulus/controllers/dynamic/work-packages/date-picker/preview.controller.ts@@ -0,0 +1,54 @@+/*+ * -- copyright+ * OpenProject is an open source project management software.+ * Copyright (C) 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 { DialogPreviewController } from '../dialog/preview.controller';++export default class PreviewController extends DialogPreviewController {+ markFieldAsTouched(event:{ target:HTMLInputElement }) {+ super.markFieldAsTouched(event);+ }++ // Ensures that on create forms, there is an "id" for the un-persisted+ // work package when sending requests to the edit action for previews.+ ensureValidPathname(formAction:string):string {+ const wpPath = new URL(formAction);++ if (wpPath.pathname.endsWith('/work_packages/date_picker')) {+ // Replace /work_packages/date_picker with /work_packages/new/date_picker+ wpPath.pathname = wpPath.pathname.replace('/work_packages/date_picker', '/work_packages/new/date_picker');+ }++ return wpPath.toString();+ }++ ensureValidWpAction(wpPath:string):string {+ return wpPath.endsWith('/work_packages/new/date_picker') ? 'new' : 'edit';+ }+}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.tsnew file mode 100644index 00000000000..e30d4b1e4f4--- /dev/null+++ b/frontend/src/stimulus/controllers/dynamic/work-packages/dialog/preview.controller.ts@@ -0,0 +1,226 @@+/*+ * -- copyright+ * OpenProject is an open source project management software.+ * Copyright (C) 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 { 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 abstract class DialogPreviewController extends Controller {+ static targets = [+ 'form',+ 'fieldInput',+ 'initialValueInput',+ 'touchedFieldInput',+ ];++ declare readonly fieldInputTargets:HTMLInputElement[];+ declare readonly formTarget:HTMLFormElement;+ declare readonly initialValueInputTargets:HTMLInputElement[];+ declare readonly touchedFieldInputTargets:HTMLInputElement[];++ 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) => { void this.preview(event); }, 100);++ // 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 });+ };+ };++ this.fieldInputTargets.forEach((target) => {+ if (target.tagName.toLowerCase() === 'select') {+ target.addEventListener('change', this.debouncedPreview);+ } else {+ target.addEventListener('input', this.debouncedPreview);+ }+ target.addEventListener('blur', this.debouncedPreview);++ if (target.dataset.focus === 'true') {+ 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.fieldInputTargets.forEach((target) => {+ if (target.tagName.toLowerCase() === 'select') {+ target.removeEventListener('change', this.debouncedPreview);+ } else {+ target.removeEventListener('input', this.debouncedPreview);+ }+ 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);+ }++ 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 = this.ensureValidWpAction(wpPath);++ 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,+ );+ }++ abstract ensureValidPathname(formAction:string):string;++ abstract ensureValidWpAction(path:string):string;++ protected 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.+ protected findValueInput(fieldName:string):HTMLInputElement|undefined {+ return this.fieldInputTargets.find((input) =>+ (input.name === fieldName) || (input.name === `work_package[${fieldName}]`));+ }++ protected isTouchedAndEmpty(fieldName:string):boolean {+ return this.isTouched(fieldName) && this.isValueEmpty(fieldName);+ }++ protected isTouched(fieldName:string):boolean {+ return this.touchedFields.has(fieldName);+ }++ protected isInitialValueEmpty(fieldName:string):boolean {+ const valueInput = this.findInitialValueInput(fieldName);+ return valueInput?.value === '';+ }++ protected isValueEmpty(fieldName:string):boolean {+ const valueInput = this.findValueInput(fieldName);+ return valueInput?.value === '';+ }++ protected isValueSet(fieldName:string):boolean {+ const valueInput = this.findValueInput(fieldName);+ return valueInput !== undefined && valueInput.value !== '';+ }++ protected markTouched(fieldName:string):void {+ this.touchedFields.add(fieldName);+ this.updateTouchedFieldHiddenInputs();+ }++ protected markUntouched(fieldName:string):void {+ this.touchedFields.delete(fieldName);+ this.updateTouchedFieldHiddenInputs();+ }++ private updateTouchedFieldHiddenInputs():void {+ this.touchedFieldInputTargets.forEach((input) => {+ const fieldName = input.dataset.referrerField;+ if (fieldName) {+ input.value = this.isTouched(fieldName) ? 'true' : 'false';+ }+ });+ }+}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 61b253b88b7..415b20788f6 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,142 +28,20 @@* ++*/-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[];-- 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) => { void this.preview(event); }, 100);-- // 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 });- };- };-- this.progressInputTargets.forEach((target) => {- if (target.tagName.toLowerCase() === 'select') {- target.addEventListener('change', this.debouncedPreview);- } else {- target.addEventListener('input', this.debouncedPreview);- }- target.addEventListener('blur', this.debouncedPreview);-- if (target.dataset.focus === 'true') {- 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) => {- if (target.tagName.toLowerCase() === 'select') {- target.removeEventListener('change', this.debouncedPreview);- } else {- target.removeEventListener('input', this.debouncedPreview);- }- target.removeEventListener('blur', this.debouncedPreview);- });- const turboFrame = this.formTarget.closest('turbo-frame') as HTMLTurboFrameElement;- if (turboFrame) {- turboFrame.removeEventListener('turbo:before-frame-render', this.frameMorphRenderer);- }- }+import { DialogPreviewController } from '../dialog/preview.controller';+export default class PreviewController extends DialogPreviewController {markFieldAsTouched(event:{ target:HTMLInputElement }) {- this.targetFieldName = event.target.name.replace(/^work_package\[([^\]]+)\]$/, '$1');- this.markTouched(this.targetFieldName);+ super.markFieldAsTouched(event);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,- );- }-// 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')) {@@ -174,126 +52,67 @@ export default class PreviewController extends Controller {return wpPath.toString();}+ ensureValidWpAction(wpPath:string):string {+ return wpPath.endsWith('/work_packages/new/progress') ? 'new' : 'edit';+ }+private isWorkBasedMode() {- return this.findValueInput('done_ratio') !== undefined;+ return super.findValueInput('done_ratio') !== undefined;}private keepWorkValue() {- if (this.isInitialValueEmpty('estimated_hours') && !this.isTouched('estimated_hours')) {+ if (super.isInitialValueEmpty('estimated_hours') && !super.isTouched('estimated_hours')) {// let work be derivedreturn;}- if (this.isBeingEdited('estimated_hours')) {+ if (super.isBeingEdited('estimated_hours')) {this.untouchFieldsWhenWorkIsEdited();- } else if (this.isBeingEdited('remaining_hours')) {+ } else if (super.isBeingEdited('remaining_hours')) {this.untouchFieldsWhenRemainingWorkIsEdited();- } else if (this.isBeingEdited('done_ratio')) {+ } else if (super.isBeingEdited('done_ratio')) {this.untouchFieldsWhenPercentCompleteIsEdited();}}private untouchFieldsWhenWorkIsEdited() {if (this.areBothTouched('remaining_hours', 'done_ratio')) {- if (this.isValueEmpty('done_ratio') && this.isValueEmpty('remaining_hours')) {+ if (super.isValueEmpty('done_ratio') && super.isValueEmpty('remaining_hours')) {return;}- if (this.isValueEmpty('done_ratio')) {- this.markUntouched('done_ratio');+ if (super.isValueEmpty('done_ratio')) {+ super.markUntouched('done_ratio');} else {- this.markUntouched('remaining_hours');+ super.markUntouched('remaining_hours');}- } else if (this.isTouchedAndEmpty('remaining_hours') && this.isValueSet('done_ratio')) {+ } else if (super.isTouchedAndEmpty('remaining_hours') && super.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')) {+ super.markUntouched('remaining_hours');+ super.markTouched('done_ratio');+ } else if (super.isTouchedAndEmpty('done_ratio') && super.isValueSet('remaining_hours')) {// force % complete derivation- this.markUntouched('done_ratio');- this.markTouched('remaining_hours');+ super.markUntouched('done_ratio');+ super.markTouched('remaining_hours');}}- private untouchFieldsWhenRemainingWorkIsEdited() {- if (this.isTouchedAndEmpty('estimated_hours') && this.isValueSet('done_ratio')) {+ private untouchFieldsWhenRemainingWorkIsEdited():void {+ if (super.isTouchedAndEmpty('estimated_hours') && super.isValueSet('done_ratio')) {// force work derivation- this.markUntouched('estimated_hours');- this.markTouched('done_ratio');- } else if (this.isValueSet('estimated_hours')) {- this.markUntouched('done_ratio');+ super.markUntouched('estimated_hours');+ super.markTouched('done_ratio');+ } else if (super.isValueSet('estimated_hours')) {+ super.markUntouched('done_ratio');}}- private untouchFieldsWhenPercentCompleteIsEdited() {- if (this.isValueSet('estimated_hours')) {- this.markUntouched('remaining_hours');+ private untouchFieldsWhenPercentCompleteIsEdited():void {+ if (super.isValueSet('estimated_hours')) {+ super.markUntouched('remaining_hours');}}- 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 areBothTouched(fieldName1:string, fieldName2:string):boolean {+ return super.isTouched(fieldName1) && super.isTouched(fieldName2);}}