Skip to content

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

Rewrite custom_fields.js into stimulus controller

Oliver Günther54ea0183c241
diff --git a/app/views/custom_fields/_custom_fields_header.html.erb b/app/views/custom_fields/_custom_fields_header.html.erb
deleted file mode 100644
index e945f0f356f..00000000000
--- a/app/views/custom_fields/_custom_fields_header.html.erb
+++ /dev/null
@@ -1,32 +0,0 @@
-<%#-- copyright
-OpenProject is an open source project management software.
-Copyright (C) 2012-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.
-
-++#%>
-
-<% content_for :header_tags do %>
- <meta name="required_script" content="custom_fields" />
-<% end %>
diff --git a/app/views/custom_fields/_custom_options.html.erb b/app/views/custom_fields/_custom_options.html.erb
index 5e86cfaae48..ed68f999333 100644
--- a/app/views/custom_fields/_custom_options.html.erb
+++ b/app/views/custom_fields/_custom_options.html.erb
@@ -75,10 +75,15 @@ See COPYRIGHT and LICENSE files for more details.
</tr>
</thead>
- <tbody id="custom-field-dragula-container">
+ <tbody
+ data-qa-selector="dragula-container"
+ data-admin--custom-fields-target="dragContainer">
<% custom_field.custom_options.each_with_index do |custom_option, i| %>
<%= f.fields_for :custom_options, custom_option do |co_f| %>
- <tr class="dragula-element custom-option-row">
+ <tr
+ class="dragula-element custom-option-row"
+ data-admin--custom-fields-target="customOptionRow"
+ >
<td>
<span class="dragula-handle icon icon-table icon-drag-handle"></span>
<%= co_f.hidden_field :id, class: 'custom-option-id' %>
@@ -89,20 +94,47 @@ See COPYRIGHT and LICENSE files for more details.
<td>
<%= co_f.check_box :default_value,
container_class: 'custom-option-default-value',
+ data: {
+ 'admin--custom-fields-target': 'customOptionDefaults',
+ action: 'admin--custom-fields#uncheckOtherDefaults'
+ },
no_label: true %>
</td>
<td>
<span class="reorder-icons">
- <a title="<%= t(:label_sort_highest) %>" rel="nofollow" href="#" class="sort-up-custom-option">
+ <a
+ title="<%= t(:label_sort_highest) %>"
+ rel="nofollow"
+ href="#"
+ class="sort-up-custom-option"
+ data-action="admin--custom-fields#moveRowToTheTop"
+ >
<%= op_icon('icon-context icon-sort-up icon-small') %>
</a>
- <a title="<%= t(:label_sort_higher) %>" rel="nofollow" href="#" class="move-up-custom-option">
+ <a
+ title="<%= t(:label_sort_higher) %>"
+ rel="nofollow"
+ href="#"
+ class="move-up-custom-option"
+ data-action="admin--custom-fields#moveUpRow"
+ >
<%= op_icon('icon-context icon-arrow-up2 icon-small') %>
</a>
- <a title="<%= t(:label_sort_lower) %>" rel="nofollow" href="#" class="move-down-custom-option">
+ <a
+ title="<%= t(:label_sort_lower) %>"
+ rel="nofollow" href="#"
+ class="move-down-custom-option"
+ data-action="admin--custom-fields#moveDownRow"
+ >
<%= op_icon('icon-context icon-arrow-down2 icon-small') %>
</a>
- <a title="<%= t(:label_sort_lowest) %>" rel="nofollow" href="#" class="sort-down-custom-option">
+ <a
+ title="<%= t(:label_sort_lowest) %>"
+ rel="nofollow"
+ href="#"
+ class="sort-down-custom-option"
+ data-action="admin--custom-fields#moveRowToTheBottom"
+ >
<%= op_icon('icon-context icon-sort-down icon-small') %>
</a>
</span>
@@ -111,7 +143,10 @@ See COPYRIGHT and LICENSE files for more details.
<%= link_to '',
delete_option_of_custom_field_path(id: custom_field.id || 0, option_id: custom_option.id || 0),
method: :delete,
- data: { confirm: t(:'custom_fields.confirm_destroy_option') },
+ data: {
+ action: 'admin--custom-fields#removeOption',
+ confirm: t(:'custom_fields.confirm_destroy_option')
+ },
class: 'icon icon-delete delete-custom-option',
title: t(:button_delete) %>
</td>
diff --git a/app/views/custom_fields/_form.html.erb b/app/views/custom_fields/_form.html.erb
index e8c7f0e3aa3..ca7b3213126 100644
--- a/app/views/custom_fields/_form.html.erb
+++ b/app/views/custom_fields/_form.html.erb
@@ -34,19 +34,28 @@ See COPYRIGHT and LICENSE files for more details.
<%= f.select :field_format,
custom_field_formats_for_select(@custom_field),
{ container_class: '-slim' },
- disabled: !@custom_field.new_record? %>
+ disabled: !@custom_field.new_record?,
+ data: {
+ action: 'admin--custom-fields#formatChanged',
+ 'admin--custom-fields-target': 'format'
+ }
+ %>
</div>
<div class="form--grouping" id="custom_field_length">
<div class="form--grouping-label">
<%= t(:label_min_max_length) %> <br>
- <small>(<%= t(:text_min_max_length_info ) %>)</small>
+ <small>(<%= t(:text_min_max_length_info) %>)</small>
</div>
<div class="form--grouping-row">
<div class="form--field -wide-label">
- <%= f.number_field :min_length, container_class: '-xslim' %>
+ <%= f.number_field :min_length,
+ container_class: '-xslim',
+ data: { 'admin--custom-fields-target': 'length' } %>
</div>
<div class="form--field -wide-label">
- <%= f.number_field :max_length, container_class: '-xslim' %>
+ <%= f.number_field :max_length,
+ container_class: '-xslim',
+ data: { 'admin--custom-fields-target': 'length' } %>
</div>
</div>
</div>
@@ -54,18 +63,23 @@ See COPYRIGHT and LICENSE files for more details.
<div class="form--field">
<%= f.text_field :regexp,
size: 50,
- container_class: '-wide' %>
+ container_class: '-wide',
+ data: { 'admin--custom-fields-target': 'regexp' } %>
<span class="form--field-instructions">
<%= t(:text_regexp_info) %>
</span>
</div>
<% if @custom_field.new_record? || @custom_field.list? || @custom_field.multi_value_possible? %>
- <div class="form--field" id="custom_field_multi_select" style="display:none">
- <%= f.check_box :multi_value %>
+ <div class="form--field" hidden>
+ <%= f.check_box :multi_value,
+ data: {
+ 'admin--custom-fields-target': 'multiSelect',
+ action: 'admin--custom-fields#checkOnlyOne'
+ } %>
</div>
- <fieldset class="form--fieldset" id="custom_field_possible_values_attributes">
+ <fieldset class="form--fieldset" data-admin--custom-fields-target="possibleValues">
<legend class="form--fieldset-legend"><%= I18n.t("activerecord.attributes.custom_field.possible_values") %></legend>
<% if @custom_field.persisted? %>
<div class="form--toolbar">
@@ -79,36 +93,47 @@ See COPYRIGHT and LICENSE files for more details.
<% end %>
<div class="form--field">
<%= render partial: "custom_fields/custom_options", locals: { custom_field: @custom_field, f: f } %>
- <a id="add-custom-option" href="#" class="icon icon-add"><%= t(:button_add) %></a>
+ <button
+ type="button"
+ class="spot-link"
+ data-qa-selector="add-custom-option"
+ data-action="admin--custom-fields#addOption"
+ >
+ <span class="spot-icon spot-icon_1_25 spot-icon_add"></span>
+ <span><%= t(:button_add) %></span>
+ </button>
</div>
</fieldset>
<% end %>
- <div id="custom_field_default_value_attributes">
+ <div data-admin--custom-fields-target="defaultValue">
<div class="form--field" id="default_value_text">
<% if @custom_field.new_record? || !%w[text bool].include?(@custom_field.field_format) %>
<%= f.text_field :default_value,
id: 'custom_fields_default_value_text',
for: 'custom_fields_default_value_text',
+ data: { 'admin--custom-fields-target': 'defaultText' },
container_class: '-wide' %>
<% end %>
</div>
- <div class="form--field" style="display:none" id="default_value_bool">
+ <div class="form--field" hidden>
<% if @custom_field.new_record? || @custom_field.field_format == 'bool' %>
<%= f.check_box :default_value,
id: 'custom_fields_default_value_bool',
+ data: { 'admin--custom-fields-target': 'defaultBool' },
for: 'custom_fields_default_value_bool' %>
<% end %>
</div>
- <div class="form--field" style="display:none" id="default_value_long_text">
+ <div class="form--field" hidden>
<% if @custom_field.new_record? || @custom_field.field_format == 'text' %>
<%= f.text_area :default_value,
id: 'custom_fields_default_value_longtext',
+ data: { 'admin--custom-fields-target': 'defaultLongText' },
for: 'custom_fields_default_value_longtext',
cols: 100,
rows: 20,
class: 'wiki-edit',
with_text_formatting: true %>
- <% end %>
+ <% end %>
</div>
</div>
<%= call_hook(:view_custom_fields_form_upper_box, custom_field: @custom_field, form: f) %>
@@ -117,23 +142,52 @@ See COPYRIGHT and LICENSE files for more details.
<section class="form--section">
<% case @custom_field.class.name
when "WorkPackageCustomField" %>
- <div class="form--field"><%= f.check_box :is_required %></div>
- <div class="form--field"><%= f.check_box :is_for_all %></div>
- <div class="form--field"><%= f.check_box :is_filter %></div>
- <div class="form--field" id="searchable_container"><%= f.check_box :searchable %></div>
- <div class="form--field" id="custom_field_text_orientation"><%= f.check_box :content_right_to_left %></div>
+ <div class="form--field">
+ <%= f.check_box :is_required %>
+ </div>
+ <div class="form--field">
+ <%= f.check_box :is_for_all %>
+ </div>
+ <div class="form--field">
+ <%= f.check_box :is_filter %>
+ </div>
+ <div class="form--field">
+ <%= f.check_box :searchable,
+ data: { 'admin--custom-fields-target': 'searchable' }%>
+ </div>
+ <div class="form--field" hidden>
+ <%= f.check_box :content_right_to_left,
+ data: { 'admin--custom-fields-target': 'textOrientation' } %>
+ </div>
<% when "UserCustomField" %>
- <div class="form--field"><%= f.check_box :is_required %></div>
- <div class="form--field"><%= f.check_box :visible %></div>
- <div class="form--field"><%= f.check_box :editable %></div>
+ <div class="form--field">
+ <%= f.check_box :is_required %>
+ </div>
+ <div class="form--field">
+ <%= f.check_box :visible %>
+ </div>
+ <div class="form--field">
+ <%= f.check_box :editable %>
+ </div>
<% when "ProjectCustomField" %>
- <div class="form--field"><%= f.check_box :is_required %></div>
- <div class="form--field"><%= f.check_box :visible %></div>
- <div class="form--field" id="searchable_container"><%= f.check_box :searchable %></div>
+ <div class="form--field">
+ <%= f.check_box :is_required %>
+ </div>
+ <div class="form--field">
+ <%= f.check_box :visible %>
+ </div>
+ <div class="form--field">
+ <%= f.check_box :searchable,
+ data: { 'admin--custom-fields-target': 'searchable' }%>
+ </div>
<% when "TimeEntryCustomField" %>
- <div class="form--field"><%= f.check_box :is_required %></div>
+ <div class="form--field">
+ <%= f.check_box :is_required %>
+ </div>
<% else %>
- <div class="form--field"><%= f.check_box :is_required %></div>
+ <div class="form--field">
+ <%= f.check_box :is_required %>
+ </div>
<% end %>
<%= call_hook(:"view_custom_fields_form_#{@custom_field.type.to_s.underscore}", custom_field: @custom_field, form: f) %>
</section>
diff --git a/app/views/custom_fields/edit.html.erb b/app/views/custom_fields/edit.html.erb
index ddf17a64d70..3541a1b1bd3 100644
--- a/app/views/custom_fields/edit.html.erb
+++ b/app/views/custom_fields/edit.html.erb
@@ -27,7 +27,10 @@ See COPYRIGHT and LICENSE files for more details.
++#%>
-<%= render :partial => 'custom_fields_header' %>
+<% content_controller 'admin--custom-fields',
+ dynamic: true,
+ 'admin--custom-fields-format-value': @custom_field.field_format
+%>
<% html_title t(:label_administration), "#{t(:label_edit)} #{CustomField.model_name.human} #{h @custom_field.name}" %>
diff --git a/app/views/custom_fields/new.html.erb b/app/views/custom_fields/new.html.erb
index 9bd3ddbdf54..ad9f7f7f978 100644
--- a/app/views/custom_fields/new.html.erb
+++ b/app/views/custom_fields/new.html.erb
@@ -26,7 +26,11 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
See COPYRIGHT and LICENSE files for more details.
++#%>
-<%= render :partial => 'custom_fields_header' %>
+
+<% content_controller 'admin--custom-fields',
+ dynamic: true,
+ 'admin--custom-fields-format-value': @custom_field.field_format
+%>
<% html_title t(:label_administration), t(:label_custom_field_new) %>
<% local_assigns[:additional_breadcrumb] = link_to(I18n.t(@custom_field.type_name), custom_fields_path(tab: @custom_field.type)),
diff --git a/frontend/src/app/core/augmenting/dynamic-scripts/custom_fields.js b/frontend/src/app/core/augmenting/dynamic-scripts/custom_fields.js
deleted file mode 100644
index 90ece5cf56a..00000000000
--- a/frontend/src/app/core/augmenting/dynamic-scripts/custom_fields.js
+++ /dev/null
@@ -1,310 +0,0 @@
-//-- copyright
-// OpenProject is an open source project management software.
-// Copyright (C) 2012-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.
-//++
-(function(window, $) {
- /*
- * @see /app/views/custom_fields/_form.html.erb
- */
- $(function() {
- var customFieldForm = $('#custom_field_form');
-
- if (customFieldForm.length === 0) {
- return;
- }
-
- // collect the nodes involved
- var format = $('#custom_field_field_format'),
- lengthField = $('#custom_field_length'),
- regexpField = $('#custom_field_regexp'),
- multiSelect = $('#custom_field_multi_select'),
- possibleValues = $('#custom_field_possible_values_attributes'),
- defaultValueFields = $('#custom_field_default_value_attributes'),
- spanDefaultText = $('#default_value_text'),
- spanDefaultLongText = $('#default_value_long_text'),
- spanDefaultBool = $('#default_value_bool'),
- textOrientationField = $('#custom_field_text_orientation');
-
- var deactivate = function(element) {
- element.hide().find('input, textarea').not('.destroy_flag,.-cf-ignore-disabled').attr('disabled', true);
- },
- activate = function(element) {
- element.show().find('input, textarea').not('.destroy_flag,.-cf-ignore-disabled').removeAttr('disabled');
- },
- toggleVisibility = function(method, args) {
- var fields = Array.prototype.slice.call(args);
- $.each(fields, function(idx, field) {
- field.closest('.form--field, .form--grouping')[method]();
- });
- },
- hide = function() { toggleVisibility('hide', arguments); },
- show = function() { toggleVisibility('show', arguments); },
- toggleFormat = function() {
- var searchable = $('#searchable_container'),
- unsearchable = function() { searchable.attr('checked', false).hide(); };
-
- // defaults (reset these fields before doing anything else)
- $.each([spanDefaultBool, spanDefaultLongText, spanDefaultText, multiSelect, textOrientationField], function(idx, element) {
- deactivate(element);
- });
- activate(defaultValueFields);
- activate(spanDefaultText);
-
- switch (format.val()) {
- case 'list':
- deactivate(defaultValueFields);
- hide(lengthField, regexpField, defaultValueFields);
- show(searchable, multiSelect);
- activate(multiSelect);
- activate(possibleValues);
- break;
- case 'bool':
- activate(spanDefaultBool);
- deactivate(spanDefaultText);
- deactivate(possibleValues);
- hide(lengthField, regexpField, searchable);
- unsearchable();
- break;
- case 'date':
- deactivate(defaultValueFields);
- deactivate(possibleValues);
- hide(lengthField, regexpField, defaultValueFields);
- unsearchable();
- break;
- case 'float':
- case 'int':
- deactivate(possibleValues);
- show(lengthField, regexpField);
- unsearchable();
- break;
- case 'user':
- show(multiSelect);
- activate(multiSelect);
- case 'version':
- deactivate(defaultValueFields);
- deactivate(possibleValues);
- hide(lengthField, regexpField, defaultValueFields);
- unsearchable();
- break;
- case 'text':
- activate(spanDefaultLongText);
- deactivate(spanDefaultText);
- show(lengthField, regexpField, searchable, textOrientationField);
- deactivate(possibleValues);
- activate(textOrientationField);
- break;
- default:
- show(lengthField, regexpField, searchable);
- deactivate(possibleValues);
- break;
- }
- };
-
- // assign the switch format function to the select field
- format.on('change', toggleFormat).trigger('change');
- toggleFormat();
- });
-
- $(function() {
- var localeSelectors = $('.locale_selector');
-
- localeSelectors.change(function () {
- var lang = $(this).val(),
- span = $(this).closest('.translation');
- span.attr('lang', lang);
- }).trigger('change');
- });
-
- var moveUpRow = function() {
- var row = $(this).closest("tr");
- var above = row.prev("tr");
-
- above.before(row);
-
- return false;
- };
-
- var moveDownRow = function() {
- var row = $(this).closest("tr");
- var after = row.next("tr");
-
- after.after(row);
-
- return false;
- };
-
- var moveRowToTheTop = function() {
- var row = $(this).closest("tr");
- var first = jQuery(row.siblings()[0]);
-
- first.before(row);
-
- return false;
- };
-
- var moveRowToTheBottom = function() {
- var row = $(this).closest("tr");
- var last = jQuery(row.siblings().last()[0]);
-
- last.after(row);
-
- return false;
- };
-
- var removeOption = function() {
- var self = $(this);
- if (self.attr("href") === "#" || self.attr("href").endsWith("/0")) {
- var row = self.closest("tr");
-
- if (row.siblings().length > 1) {
- row.remove();
- }
-
- return false; // just remove new element
- } else {
- return true; // send off deletion
- }
- };
-
- var duplicateRow = function() {
- var count = $("#custom-options-table tr.custom-option-row").length;
- var row = $("#custom-options-table tr.custom-option-row:last");
- var dup = row.clone();
-
- var value = dup.find(".custom-option-value input");
-
- value.attr("name", "custom_field[custom_options_attributes][" + count + "][value]");
- value.attr("id", "custom_field_custom_options_attributes_" + count + "_value");
- value.val("");
-
- var defaultValueContainer = dup.find(".custom-option-default-value");
- var defaultValueCheckbox = defaultValueContainer.find('input[type="checkbox"]');
- var defaultValueHidden = defaultValueContainer.find('input[type="hidden"]');
-
- defaultValueHidden.attr("name", "custom_field[custom_options_attributes][" + count + "][default_value]");
- defaultValueCheckbox.attr("name", "custom_field[custom_options_attributes][" + count + "][default_value]");
- defaultValueCheckbox.attr("id", "custom_field_custom_options_attributes_" + count + "_default_value]");
- defaultValueCheckbox.prop("checked", false);
-
- dup.find(".custom-option-id").remove();
-
- dup.find(".move-up-custom-option").click(moveUpRow);
- dup.find(".sort-up-custom-option").click(moveRowToTheTop);
- dup.find(".sort-down-custom-option").click(moveRowToTheBottom);
- dup.find(".move-down-custom-option").click(moveDownRow);
- dup.find(".custom-option-default-value").change(uncheckOtherDefaults);
-
- dup
- .find(".delete-custom-option")
- .attr("href", "#")
- .click(removeOption);
-
- row.after(dup);
-
- return false;
- };
-
- var uncheckOtherDefaults = function() {
- var cb = $(this);
-
- if (cb.prop("checked")) {
- var multi = $('#custom_field_multi_value');
-
- if (!multi.prop("checked")) {
- $(".custom-option-default-value").each(function(i, other) {
- $(other).prop("checked", false);
- });
-
- cb.prop("checked", true);
- }
- }
- };
-
- var checkOnlyOne = function() {
- var cb = $(this);
-
- if (!cb.prop("checked")) {
- $(".custom-option-default-value:checked").slice(1).each(function(i, other) {
- $(other).prop("checked", false);
- });
- }
- };
-
- $(document).ready(function() {
- $("#add-custom-option").click(duplicateRow);
- $(".delete-custom-option").click(removeOption);
-
- $(".move-up-custom-option").click(moveUpRow);
- $(".move-down-custom-option").click(moveDownRow);
-
- $(".sort-up-custom-option").click(moveRowToTheTop);
- $(".sort-down-custom-option").click(moveRowToTheBottom);
-
- $(".custom-option-default-value").change(uncheckOtherDefaults);
- $('#custom_field_multi_value').change(checkOnlyOne);
-
- // Make custom fields draggable
- const container = document.getElementById('custom-field-dragula-container');
- // eslint-disable-next-line no-undef
- const drake = dragula([container], {
- isContainer: function (el) {
- return false;
- },
- moves: function (el, source, handle, sibling) {
- return $(handle).hasClass('dragula-handle');
- },
- accepts: function (el, target, source, sibling) {
- return true;
- },
- invalid: function (el, handle) {
- return false;
- },
- direction: 'vertical',
- copy: false,
- copySortSource: false,
- revertOnSpill: true,
- removeOnSpill: false,
- mirrorContainer: container,
- ignoreInputTextSelection: true
- });
-
- // Setup autoscroll
- window.OpenProject.getPluginContext().then((pluginContext) => {
- new pluginContext.classes.DomAutoscrollService(
- [
- document.getElementById('content-wrapper'),
- ],
- {
- margin: 25,
- maxSpeed: 10,
- scrollWhenOutside: true,
- autoScroll: function () {
- return drake.dragging;
- }
- });
- });
- });
-}(window, jQuery));
diff --git a/frontend/src/stimulus/controllers/dynamic/admin/custom-fields.controller.ts b/frontend/src/stimulus/controllers/dynamic/admin/custom-fields.controller.ts
new file mode 100644
index 00000000000..fad3b6c613d
--- /dev/null
+++ b/frontend/src/stimulus/controllers/dynamic/admin/custom-fields.controller.ts
@@ -0,0 +1,331 @@
+/*
+ * -- 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 { Controller } from '@hotwired/stimulus';
+
+export default class CustomFieldsController extends Controller {
+ static targets = [
+ 'dragContainer',
+ 'format',
+ 'length',
+ 'regexp',
+ 'multiSelect',
+ 'possibleValues',
+ 'defaultValue',
+ 'defaultText',
+ 'defaultLongText',
+ 'defaultBool',
+ 'textOrientation',
+ 'searchable',
+ 'customOptionRow',
+ 'customOptionDefaults',
+ ];
+
+ static values = {
+ format: String,
+ };
+
+ declare readonly formatValue:string;
+ declare readonly dragContainerTarget:HTMLElement;
+ declare readonly hasDragContainerTarget:boolean;
+
+ // Lots of the option fields are optionally, so we use the
+ // array notation to loop through instead of a lot of if (has...Target) calls
+ declare readonly lengthTargets:HTMLElement[];
+ declare readonly regexpTargets:HTMLElement[];
+ declare readonly multiSelectTargets:HTMLElement[];
+ declare readonly possibleValuesTargets:HTMLElement[];
+ declare readonly defaultValueTargets:HTMLElement[];
+ declare readonly defaultTextTargets:HTMLElement[];
+ declare readonly defaultLongTextTargets:HTMLElement[];
+ declare readonly defaultBoolTargets:HTMLElement[];
+ declare readonly textOrientationTargets:HTMLElement[];
+ declare readonly searchableTargets:HTMLInputElement[];
+ declare readonly customOptionRowTargets:HTMLTableRowElement[];
+ declare readonly customOptionDefaultsTargets:HTMLInputElement[];
+
+ connect() {
+ if (this.hasDragContainerTarget) {
+ this.setupDragAndDrop();
+ }
+
+ this.toggleFormat(this.formatValue);
+ }
+
+ activate(elements:HTMLElement[], active = true) {
+ this.toggleVisibility(!active, elements);
+ elements.forEach((element) => {
+ element
+ .querySelectorAll<HTMLInputElement>('input,textarea')
+ .forEach((input) => {
+ if (!input.matches('.destroy_flag,.-cf-ignore-disabled')) {
+ input.disabled = !active;
+ }
+ });
+ });
+ }
+
+ toggleVisibility(hidden:boolean, elements:HTMLElement[]) {
+ elements
+ .forEach((field) => {
+ const wrapper = field.closest<HTMLElement>('.form--grouping') || field.closest<HTMLElement>('.form--field');
+ if (wrapper) {
+ wrapper.hidden = hidden;
+ } else {
+ field.hidden = hidden;
+ }
+ });
+ }
+
+ hide(...elements:HTMLElement[]) {
+ this.toggleVisibility(true, elements);
+ }
+
+ show(...elements:HTMLElement[]) {
+ this.toggleVisibility(false, elements);
+ }
+
+ unsearchable() {
+ this.hide(...this.searchableTargets);
+ this
+ .searchableTargets
+ .forEach((target) => (target.checked = false));
+ }
+
+ formatChanged(event:{ target:HTMLInputElement }) {
+ this.toggleFormat(event.target.value);
+ }
+
+ moveUpRow(event:{ target:HTMLElement }) {
+ const row = event.target.closest('tr') as HTMLTableRowElement;
+ const idx = this.customOptionRowTargets.indexOf(row);
+ if (idx > 0) {
+ this.customOptionRowTargets[idx - 1].before(row);
+ }
+
+ return false;
+ }
+
+ moveDownRow(event:{ target:HTMLElement }) {
+ const row = event.target.closest('tr') as HTMLTableRowElement;
+ const idx = this.customOptionRowTargets.indexOf(row);
+ if (idx < this.customOptionRowTargets.length - 1) {
+ this.customOptionRowTargets[idx + 1].after(row);
+ }
+
+ return false;
+ }
+
+ moveRowToTheTop(event:{ target:HTMLElement }) {
+ const row = event.target.closest('tr') as HTMLTableRowElement;
+ const first = this.customOptionRowTargets[0];
+
+ if (first && first !== row) {
+ first.before(row);
+ }
+
+ return false;
+ }
+
+ moveRowToTheBottom(event:{ target:HTMLElement }) {
+ const row = event.target.closest('tr') as HTMLTableRowElement;
+ const last = this.customOptionRowTargets[this.customOptionRowTargets.length - 1];
+
+ if (last && last !== row) {
+ last.after(row);
+ }
+
+ return false;
+ }
+
+ removeOption(event:MouseEvent) {
+ const self = event.target as HTMLAnchorElement;
+ if (self.href === '#' || self.href.endsWith('/0')) {
+ const row = self.closest('tr');
+
+ if (row && this.customOptionRowTargets.length > 1) {
+ row.remove();
+ }
+
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ }
+ return true; // send off deletion
+ }
+
+ addOption() {
+ const count = this.customOptionRowTargets.length;
+ const last = this.customOptionRowTargets[count - 1];
+ const dup = last.cloneNode(true) as HTMLElement;
+
+ const input = dup.querySelector('.custom-option-value input') as HTMLInputElement;
+
+ input.setAttribute('name', `custom_field[custom_options_attributes][${count}][value]`);
+ input.setAttribute('id', `custom_field_custom_options_attributes_${count}_value`);
+ input.value = '';
+
+ dup
+ .querySelector('.custom-option-id')
+ ?.remove();
+
+ const defaultValueCheckbox = dup.querySelector('input[type="checkbox"]') as HTMLInputElement;
+ const defaultValueHidden = dup.querySelector('input[type="hidden"]') as HTMLInputElement;
+
+ defaultValueHidden.setAttribute('name', `custom_field[custom_options_attributes][${count}][default_value]`);
+ defaultValueHidden.removeAttribute('id');
+ defaultValueCheckbox.setAttribute('name', `custom_field[custom_options_attributes][${count}][default_value]`);
+ defaultValueCheckbox.setAttribute('id', `custom_field_custom_options_attributes_${count}_default_value`);
+ defaultValueCheckbox.checked = false;
+
+ last.insertAdjacentElement('afterend', dup);
+
+ return false;
+ }
+
+ uncheckOtherDefaults(event:{ target:HTMLElement }) {
+ const cb = event.target as HTMLInputElement;
+
+ if (cb.checked) {
+ const multi = this.multiSelectTargets[0] as HTMLInputElement|undefined;
+
+ if (multi?.checked === false) {
+ this.customOptionDefaultsTargets.forEach((el) => (el.checked = false));
+ cb.checked = true;
+ }
+ }
+ }
+
+ checkOnlyOne(event:{ target:HTMLElement }) {
+ const cb = event.target as HTMLInputElement;
+
+ if (!cb.checked) {
+ this.customOptionDefaultsTargets
+ .filter((el) => el.checked)
+ .slice(1)
+ .forEach((el) => (el.checked = false));
+ }
+ }
+
+ private setupDragAndDrop() {
+ // Make custom fields draggable
+ // eslint-disable-next-line no-undef
+ const drake = dragula([this.dragContainerTarget], {
+ isContainer: () => false,
+ moves: (el, source, handle:HTMLElement) => handle.classList.contains('dragula-handle'),
+ accepts: () => true,
+ invalid: () => false,
+ direction: 'vertical',
+ copy: false,
+ copySortSource: false,
+ revertOnSpill: true,
+ removeOnSpill: false,
+ mirrorContainer: this.dragContainerTarget,
+ ignoreInputTextSelection: true,
+ });
+
+ // Setup autoscroll
+ void window.OpenProject.getPluginContext().then((pluginContext) => {
+ // eslint-disable-next-line no-new
+ new pluginContext.classes.DomAutoscrollService(
+ [
+ document.getElementById('content-wrapper') as HTMLElement,
+ ],
+ {
+ margin: 25,
+ maxSpeed: 10,
+ scrollWhenOutside: true,
+ autoScroll: () => drake.dragging,
+ },
+ );
+ });
+ }
+
+ private toggleFormat(format:string) {
+ // defaults (reset these fields before doing anything else)
+ this.activate(this.defaultBoolTargets, false);
+ this.activate(this.defaultLongTextTargets, false);
+ this.activate(this.multiSelectTargets, false);
+ this.activate(this.textOrientationTargets, false);
+ this.activate(this.defaultValueTargets);
+ this.activate(this.defaultTextTargets);
+
+ switch (format) {
+ case 'list':
+ this.activate(this.defaultValueTargets, false);
+ this.hide(...this.lengthTargets, ...this.regexpTargets, ...this.defaultValueTargets);
+ this.show(...this.searchableTargets, ...this.multiSelectTargets);
+ this.activate(this.multiSelectTargets);
+ this.activate(this.possibleValuesTargets);
+ break;
+ case 'bool':
+ this.activate(this.defaultBoolTargets);
+ this.activate(this.defaultTextTargets, false);
+ this.activate(this.possibleValuesTargets, false);
+ this.hide(...this.lengthTargets, ...this.regexpTargets, ...this.searchableTargets);
+ this.unsearchable();
+ break;
+ case 'date':
+ this.activate(this.defaultValueTargets, false);
+ this.activate(this.possibleValuesTargets, false);
+ this.hide(...this.lengthTargets, ...this.regexpTargets, ...this.defaultValueTargets);
+ this.unsearchable();
+ break;
+ case 'float':
+ case 'int':
+ this.activate(this.possibleValuesTargets, false);
+ this.show(...this.lengthTargets, ...this.regexpTargets);
+ this.unsearchable();
+ break;
+ case 'user':
+ this.show(...this.multiSelectTargets);
+ this.activate(this.multiSelectTargets);
+ this.hide(...this.lengthTargets, ...this.regexpTargets, ...this.defaultValueTargets);
+ this.unsearchable();
+ break;
+ case 'version':
+ this.activate(this.defaultValueTargets, false);
+ this.activate(this.possibleValuesTargets, false);
+ this.hide(...this.lengthTargets, ...this.regexpTargets, ...this.defaultValueTargets);
+ this.unsearchable();
+ break;
+ case 'text':
+ this.activate(this.defaultLongTextTargets);
+ this.activate(this.defaultTextTargets, false);
+ this.show(...this.lengthTargets, ...this.regexpTargets, ...this.searchableTargets, ...this.textOrientationTargets);
+ this.activate(this.possibleValuesTargets, false);
+ this.activate(this.textOrientationTargets);
+ break;
+ default:
+ this.show(...this.lengthTargets, ...this.regexpTargets, ...this.searchableTargets);
+ this.activate(this.possibleValuesTargets, false);
+ break;
+ }
+ }
+}
diff --git a/spec/features/admin/custom_fields/multi_value_custom_fields_spec.rb b/spec/features/admin/custom_fields/multi_value_custom_fields_spec.rb
index 14021c0ae8d..605e48ec7ac 100644
--- a/spec/features/admin/custom_fields/multi_value_custom_fields_spec.rb
+++ b/spec/features/admin/custom_fields/multi_value_custom_fields_spec.rb
@@ -48,13 +48,13 @@ describe 'Multi-value custom fields creation', js: true do
fill_in 'custom_field_custom_options_attributes_0_value', with: 'A'
# Add new row
- find_by_id('add-custom-option').click
+ page.find('[data-qa-selector="add-custom-option"]').click
SeleniumHubWaiter.wait
expect(page).to have_selector('input#custom_field_custom_options_attributes_1_value')
fill_in 'custom_field_custom_options_attributes_1_value', with: 'B'
# Add new row
- find_by_id('add-custom-option').click
+ page.find('[data-qa-selector="add-custom-option"]').click
SeleniumHubWaiter.wait
expect(page).to have_selector('input#custom_field_custom_options_attributes_2_value')
fill_in 'custom_field_custom_options_attributes_2_value', with: 'C'
@@ -77,8 +77,11 @@ describe 'Multi-value custom fields creation', js: true do
# We need to hack a target for where to drag the row to
page.execute_script <<-JS
- jQuery('#custom-field-dragula-container')
- .append('<tr class="__drag_and_drop_end_of_list"><td colspan="4" style="height: 100px"></td></tr>');
+ const container = document.querySelector('[data-qa-selector="dragula-container"]');
+ const element = document.createElement('tr')
+ element.classList.add('__drag_and_drop_end_of_list');
+ element.innerHTML = '<td colspan="4" style="height: 100px"></td>';
+ container.insertAdjacentElement('beforeend', element);
JS
rows = page.all('tr.custom-option-row')
@@ -88,15 +91,14 @@ describe 'Multi-value custom fields creation', js: true do
sleep 1
page.execute_script <<-JS
- jQuery('.__drag_and_drop_end_of_list').remove()
+ document.querySelector('.__drag_and_drop_end_of_list').remove();
JS
click_on 'Save'
-
# Edit again
- expect(page).to have_selector('input#custom_field_custom_options_attributes_0_value[value=B]')
- expect(page).to have_selector('input#custom_field_custom_options_attributes_1_value[value=C]')
- expect(page).to have_selector('input#custom_field_custom_options_attributes_2_value[value=A]')
+ expect(page).to have_field('custom_field_custom_options_attributes_0_value', with: 'B')
+ expect(page).to have_field('custom_field_custom_options_attributes_1_value', with: 'C')
+ expect(page).to have_field('custom_field_custom_options_attributes_2_value', with: 'A')
cf.reload
expect(cf.name).to eq('My List CF')
diff --git a/spec/features/custom_fields/create_long_text_spec.rb b/spec/features/custom_fields/create_long_text_spec.rb
index c6756fcc29f..d0ccefb8e92 100644
--- a/spec/features/custom_fields/create_long_text_spec.rb
+++ b/spec/features/custom_fields/create_long_text_spec.rb
@@ -4,7 +4,7 @@ require 'support/pages/custom_fields'
describe 'custom fields', js: true do
let(:user) { create(:admin) }
let(:cf_page) { Pages::CustomFields.new }
- let(:editor) { Components::WysiwygEditor.new '#default_value_long_text' }
+ let(:editor) { Components::WysiwygEditor.new '#custom_field_form' }
let(:type) { create(:type_task) }
let(:project) { create(:project, enabled_module_names: %i[work_package_tracking], types: [type]) }
diff --git a/spec/features/custom_fields/custom_fields_spec.rb b/spec/features/custom_fields/custom_fields_spec.rb
index f9757247f8a..baf865d9442 100644
--- a/spec/features/custom_fields/custom_fields_spec.rb
+++ b/spec/features/custom_fields/custom_fields_spec.rb
@@ -26,14 +26,14 @@ describe 'custom fields', js: true do
find(".custom-option-default-value input").set true
end
- click_on "add-custom-option"
+ page.find('[data-qa-selector="add-custom-option"]').click
expect(page).to have_selector('.custom-option-row', count: 2)
within all(".custom-option-row").last do
find(".custom-option-value input").set "Linux"
end
- click_on "add-custom-option"
+ page.find('[data-qa-selector="add-custom-option"]').click
expect(page).to have_selector('.custom-option-row', count: 3)
within all(".custom-option-row").last do
@@ -90,7 +90,7 @@ describe 'custom fields', js: true do
end
it "adds new options" do
- click_on "add-custom-option"
+ page.find('[data-qa-selector="add-custom-option"]').click
SeleniumHubWaiter.wait
expect(page).to have_selector('.custom-option-row', count: 5)
@@ -98,7 +98,7 @@ describe 'custom fields', js: true do
find(".custom-option-value input").set "Sega"
end
- click_on "add-custom-option"
+ page.find('[data-qa-selector="add-custom-option"]').click
SeleniumHubWaiter.wait
expect(page).to have_selector('.custom-option-row', count: 6)
@@ -125,7 +125,7 @@ describe 'custom fields', js: true do
expect(page).to have_field("custom_field_custom_options_attributes_#{i}_value", with: value)
end
- fill_in("custom_field_custom_options_attributes_1_value", with: "Sega")
+ fill_in("custom_field_custom_options_attributes_1_value", with: "Sega", fill_options: { clear: :backspace })
check("custom_field_multi_value")
check("custom_field_custom_options_attributes_0_default_value")
check("custom_field_custom_options_attributes_2_default_value")