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
create a pattern autocompleter input
Bruno Pagnob0fefb83fca8
diff --git a/app/components/_index.sass b/app/components/_index.sassindex 993e12daeb7..5b68eaa4098 100644--- a/app/components/_index.sass+++ b/app/components/_index.sass@@ -22,3 +22,4 @@@import "work_package_relations_tab/index_component"@import "users/hover_card_component"@import "enterprise_edition/banner_component"+@import "work_packages/types/pattern_input"diff --git a/app/components/work_packages/types/pattern_input.html.erb b/app/components/work_packages/types/pattern_input.html.erbnew file mode 100644index 00000000000..83e160305e0--- /dev/null+++ b/app/components/work_packages/types/pattern_input.html.erb@@ -0,0 +1,93 @@+<%#-- 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.++++#%>++<%=+ render(+ Primer::BaseComponent.new(+ tag: :div,+ classes: "pattern-input",+ "data-controller": "pattern-input",+ "data-pattern-input-pattern-initial-value": @value,+ "data-pattern-input-suggestions-initial-value": suggestions_for_stimulus+ )+ ) do+%>+ <%= @input.builder.hidden_field(name, value: @value, data: { "pattern-input-target": "formInput" }) %>++ <template data-pattern-input-target="tokenTemplate">+ <%= render(Primer::Beta::Label.new(tag: :span, scheme: :accent, "data-role": :token)) %>+ </template>++ <template data-pattern-input-target="suggestionsHeadingTemplate">+ <%= render(Primer::Alpha::ActionList::Heading.new(title: "__placeholder__", heading_level: 2)) %>+ </template>++ <template data-pattern-input-target="suggestionsDividerTemplate">+ <%= render(Primer::Alpha::ActionList::Divider.new) %>+ </template>++ <template data-pattern-input-target="suggestionsItemTemplate">+ <%=+ render(+ Primer::Alpha::ActionList::Item.new(+ list: suggestions_list_component,+ label: "__placeholder__",+ role: "menuitem",+ data: {+ prop: "__placeholder__",+ action: "click->pattern-input#suggestions_select"+ }+ )+ )+ %>+ </template>++ <%=+ render(+ Primer::BaseComponent.new(+ tag: :div,+ contenteditable: true,+ border: true, border_radius: 2, p: 1, classes: :input,+ "data-pattern-input-target": "content",+ data: {+ action: "keydown->pattern-input#input_keydown+ input->pattern-input#input_change+ mouseup->pattern-input#input_mouseup+ focus->pattern-input#input_focus+ blur->pattern-input#input_blur"+ }+ )+ )+ %>+ <%= render(Primer::BaseComponent.new(tag: :div, box_shadow: :medium, border_radius: 2)) do %>+ <focus-group direction="vertical">+ <%= render(suggestions_list_component) %>+ </focus-group>+ <% end %>+<% end %>diff --git a/app/components/work_packages/types/pattern_input.rb b/app/components/work_packages/types/pattern_input.rbnew file mode 100644index 00000000000..87c9d4cc14f--- /dev/null+++ b/app/components/work_packages/types/pattern_input.rb@@ -0,0 +1,57 @@+# frozen_string_literal: true++# -- copyright+# OpenProject is an open source project management software.+# Copyright (C) 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 Types+ class PatternInput < Primer::Forms::BaseComponent+ delegate :name, to: :@input++ def initialize(input:, value:, suggestions:)+ super()+ @input = input+ @value = value+ @suggestions = suggestions+ end++ def suggestions_for_stimulus+ @suggestions_for_stimulus ||= @suggestions+ .transform_keys { |key| key.to_s.humanize }+ .to_json+ end++ def suggestions_list_component+ @suggestions_list_component ||= Primer::Alpha::ActionList.new(+ role: :list,+ "data-pattern-input-target": "suggestions"+ )+ end+ end+ end+enddiff --git a/app/components/work_packages/types/pattern_input.sass b/app/components/work_packages/types/pattern_input.sassnew file mode 100644index 00000000000..feafed48d00--- /dev/null+++ b/app/components/work_packages/types/pattern_input.sass@@ -0,0 +1,4 @@+.pattern-input+ .input+ white-space: pre-wrap+diff --git a/app/components/work_packages/types/subject_configuration_component.rb b/app/components/work_packages/types/subject_configuration_component.rbindex 02a993cc6fd..b4688b84f77 100644--- a/app/components/work_packages/types/subject_configuration_component.rb+++ b/app/components/work_packages/types/subject_configuration_component.rb@@ -57,6 +57,7 @@ module WorkPackages::Types::Forms::SubjectConfigurationFormModel.new(subject_configuration: subject_pattern.enabled ? :generated : :manual,pattern: subject_pattern.blueprint,+ suggestions: ::Types::Patterns::TokenPropertyMapper.new.tokens_for_type(model),validation_errors: model.errors)enddiff --git a/app/forms/work_packages/types/subject_configuration_form.rb b/app/forms/work_packages/types/subject_configuration_form.rbindex fcddde1b6d7..7f6b1697552 100644--- a/app/forms/work_packages/types/subject_configuration_form.rb+++ b/app/forms/work_packages/types/subject_configuration_form.rb@@ -51,12 +51,13 @@ module WorkPackagesendsubject_form.group(data: { "admin--subject-configuration-target": "patternInput" }) do |toggleable_group|- toggleable_group.text_field(+ toggleable_group.pattern_input(name: :pattern,+ value: model.pattern,+ suggestions: model.suggestions,label: I18n.t("types.edit.subject_configuration.pattern.label"),caption: I18n.t("types.edit.subject_configuration.pattern.caption"),required: true,- input_width: :large,validation_message: validation_message_for(:patterns))enddiff --git a/app/models/types/forms/subject_configuration_form_model.rb b/app/models/types/forms/subject_configuration_form_model.rbindex f6158322af4..3a8a53cff94 100644--- a/app/models/types/forms/subject_configuration_form_model.rb+++ b/app/models/types/forms/subject_configuration_form_model.rb@@ -33,11 +33,12 @@ module Typesclass SubjectConfigurationFormModelextend ActiveModel::Naming- attr_reader :subject_configuration, :pattern, :validation_errors+ attr_reader :subject_configuration, :pattern, :suggestions, :validation_errors- def initialize(subject_configuration:, pattern:, validation_errors: {})+ def initialize(subject_configuration:, pattern:, suggestions:, validation_errors: {})@subject_configuration = subject_configuration@pattern = pattern+ @suggestions = suggestions@validation_errors = validation_errorsendenddiff --git a/frontend/src/stimulus/controllers/pattern-input.controller.ts b/frontend/src/stimulus/controllers/pattern-input.controller.tsnew file mode 100644index 00000000000..e99c6bc5d90--- /dev/null+++ b/frontend/src/stimulus/controllers/pattern-input.controller.ts@@ -0,0 +1,287 @@+/*+ * -- 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';++export default class PatternInputController extends Controller {+ static targets = [+ 'tokenTemplate',+ 'content',+ 'formInput',++ 'suggestions',+ 'suggestionsHeadingTemplate',+ 'suggestionsDividerTemplate',+ 'suggestionsItemTemplate',+ ];++ declare readonly tokenTemplateTarget:HTMLTemplateElement;+ declare readonly contentTarget:HTMLElement;+ declare readonly formInputTarget:HTMLInputElement;++ declare readonly suggestionsTarget:HTMLElement;+ declare readonly suggestionsHeadingTemplateTarget:HTMLTemplateElement;+ declare readonly suggestionsDividerTemplateTarget:HTMLTemplateElement;+ declare readonly suggestionsItemTemplateTarget:HTMLTemplateElement;++ static values = {+ patternInitial: String,+ suggestionsInitial: Object,+ };++ declare patternInitialValue:string;+ declare suggestionsInitialValue:Record<string, Record<string, string>>;++ currentRange:Range|undefined = undefined;++ connect() {+ this.contentTarget.innerHTML = this.toHtml(this.patternInitialValue) || ' ';+ }++ // Input field events+ input_keydown(event:KeyboardEvent) {+ if (event.key === 'Enter') {+ event.preventDefault();+ }++ if (event.key === 'ArrowDown') {+ const firstSuggestion = this.suggestionsTarget.querySelector('[role="menuitem"]') as HTMLElement;+ firstSuggestion?.focus();+ event.preventDefault();+ }++ // close the suggestions+ if (event.key === 'Escape' || event.key === 'ArrowLeft' || event.key === 'ArrowRight') {+ this.clearSuggestionsFilter();+ }++ // update cursor+ this.setRange();+ }++ input_change() {+ // clean up empty tags from the input+ this.contentTarget.querySelectorAll('span').forEach((element) => element.textContent?.trim() === '' && element.remove());+ this.contentTarget.querySelectorAll('br').forEach((element) => element.remove());++ // show suggestions for the current word+ const word = this.currentWord();+ if (word && word.length > 0) {+ this.filterSuggestions(word);+ } else {+ this.clearSuggestionsFilter();+ }++ this.tagInvalidTokens();++ // update cursor+ this.setRange();+ }++ input_mouseup() {+ this.setRange();+ }++ input_focus() {+ this.setRange();+ }++ input_blur() {+ this.updateFormInputValue();+ }++ // Autocomplete events+ suggestions_select(event:PointerEvent) {+ const target = event.currentTarget as HTMLElement;++ if (target) {+ this.insertToken(this.createToken(target.dataset.prop!));+ this.clearSuggestionsFilter();+ }+ }++ // internal methods+ private updateFormInputValue():void {+ this.formInputTarget.value = this.toBlueprint();+ }++ /**+ * Sets an internal representation of the cursor position by persisting the current `Range`+ */+ private setRange():void {+ const selection = document.getSelection();+ if (selection?.rangeCount) {+ const range = selection.getRangeAt(0);+ if (range.startContainer.parentNode === this.contentTarget) {+ this.currentRange = range;+ }+ }+ }++ private insertToken(tokenElement:HTMLElement) {+ if (this.currentRange) {+ const targetNode = this.currentRange.startContainer;+ const targetOffset = this.currentRange.startOffset;++ if (!targetNode.textContent) { return; }++ let pos = targetOffset - 1;+ while (pos > -1 && !this.isWhitespace(targetNode.textContent.charAt(pos))) { pos-=1; }++ const wordRange = document.createRange();+ wordRange.setStart(targetNode, pos + 1);+ wordRange.setEnd(targetNode, targetOffset);++ wordRange.deleteContents();+ wordRange.insertNode(tokenElement);++ const postRange = document.createRange();+ postRange.setStartAfter(tokenElement);++ const selection = document.getSelection();+ selection?.removeAllRanges();+ selection?.addRange(postRange);++ this.updateFormInputValue();+ this.setRange();++ // clear suggestions+ this.clearSuggestionsFilter();+ } else {+ this.contentTarget.appendChild(tokenElement);+ }+ }++ private currentWord():string|null {+ const selection = document.getSelection();+ if (selection) {+ return (selection.anchorNode?.textContent?.slice(0, selection.anchorOffset)+ .split(' ')+ .pop() as string)+ .toLowerCase();+ }++ return null;+ }++ private clearSuggestionsFilter():void {+ this.suggestionsTarget.innerHTML = '';+ }++ private filterSuggestions(word:string):void {+ this.clearSuggestionsFilter();++ const filtered = Object.keys(this.suggestionsInitialValue).map((key) => {+ const group = this.suggestionsInitialValue[key];+ return {+ key,+ values: Object.keys(group).filter((prop) => {+ const value = group[prop];+ return value.toLowerCase().includes(word.toLowerCase()) || prop.toLowerCase().includes(word.toLowerCase()) || word === '*';+ }).map((prop) => ({ prop, value: group[prop] })),+ };+ }).filter((group) => group.values.length > 0);+ // insert the HTML+ filtered.forEach((group) => {+ const groupHeader = this.suggestionsHeadingTemplateTarget.content?.cloneNode(true) as HTMLElement;+ groupHeader.querySelector('h2')!.innerText = group.key;++ this.suggestionsTarget.appendChild(groupHeader);++ group.values.forEach((suggestion) => {+ const suggestionTemplate = this.suggestionsItemTemplateTarget.content?.cloneNode(true) as HTMLElement;+ const suggestionItem = suggestionTemplate.firstElementChild as HTMLElement;+ suggestionItem.dataset.prop = suggestion.prop;+ suggestionItem.querySelector('span')!.innerText = suggestion.value;+ this.suggestionsTarget.appendChild(suggestionItem);+ });++ const groupDivider = this.suggestionsDividerTemplateTarget.content?.cloneNode(true) as HTMLElement;+ this.suggestionsTarget.appendChild(groupDivider);+ });+ }++ private tagInvalidTokens():void {+ this.contentTarget.querySelectorAll('[data-role="token"]').forEach((element) => {+ const token = element.textContent?.trim();++ let exists = false;+ Object.keys(this.suggestionsInitialValue).forEach((key) => {+ const group = this.suggestionsInitialValue[key];+ Object.keys(group).forEach((prop) => {+ if (prop === token) { exists = true; }+ });+ });++ if (exists) {+ element.classList.remove('Label--danger');+ } else {+ element.classList.add('Label--danger');+ }+ });+ }++ private hide(el:HTMLElement):void {+ el.setAttribute('hidden', 'hidden');+ }++ private show(el:HTMLElement):void {+ el.removeAttribute('hidden');+ }++ private createToken(value:string):HTMLElement {+ const templateTarget = this.tokenTemplateTarget.content?.cloneNode(true) as HTMLElement;+ const contentElement = templateTarget.firstElementChild as HTMLElement;+ contentElement.innerText = value;+ return contentElement;+ }++ private toHtml(blueprint:string):string {+ return blueprint.replace(/{{([0-9A-Za-z_]+)}}/g, (_, token:string) => this.createToken(token).outerHTML);+ }++ private toBlueprint():string {+ let result = '';+ this.contentTarget.childNodes.forEach((node:Element) => {+ if (node.nodeType === Node.TEXT_NODE) {+ // Plain text node+ result += node.textContent;+ } else if (node.nodeType === Node.ELEMENT_NODE && (node as HTMLElement).dataset.role === 'token') {+ // Token element+ result += `{{${node.textContent?.trim()}}}`;+ }+ });+ return result.trim();+ }++ private isWhitespace(value:string):boolean {+ return /\s/.test(value);+ }+}diff --git a/frontend/src/stimulus/setup.ts b/frontend/src/stimulus/setup.tsindex d7196c7371f..d9ebf658cd0 100644--- a/frontend/src/stimulus/setup.ts+++ b/frontend/src/stimulus/setup.ts@@ -15,6 +15,7 @@ import FlashController from './controllers/flash.controller';import OpProjectsZenModeController from './controllers/dynamic/projects/zen-mode.controller';import PasswordConfirmationDialogController from './controllers/password-confirmation-dialog.controller';import KeepScrollPositionController from './controllers/keep-scroll-position.controller';+import PatternInputController from './controllers/pattern-input.controller';declare global {interface Window {@@ -45,3 +46,4 @@ instance.register('show-when-value-selected', OpShowWhenValueSelectedController)instance.register('table-highlighting', TableHighlightingController);instance.register('projects-zen-mode', OpProjectsZenModeController);instance.register('keep-scroll-position', KeepScrollPositionController);+instance.register('pattern-input', PatternInputController);diff --git a/lib/primer/open_project/forms/dsl/input_methods.rb b/lib/primer/open_project/forms/dsl/input_methods.rbindex eca21f89ef7..25ada7426ca 100644--- a/lib/primer/open_project/forms/dsl/input_methods.rb+++ b/lib/primer/open_project/forms/dsl/input_methods.rb@@ -9,6 +9,10 @@ module Primeradd_input AutocompleterInput.new(builder:, form:, **, &)end+ def pattern_input(**, &)+ add_input PatternInput.new(builder:, form:, **, &)+ end+def color_select_list(**, &)add_input ColorSelectInput.new(builder:, form:, **, &)enddiff --git a/lib/primer/open_project/forms/dsl/pattern_input.rb b/lib/primer/open_project/forms/dsl/pattern_input.rbnew file mode 100644index 00000000000..fb654d663f7--- /dev/null+++ b/lib/primer/open_project/forms/dsl/pattern_input.rb@@ -0,0 +1,61 @@+# frozen_string_literal: true++#-- 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 Primer+ module OpenProject+ module Forms+ module Dsl+ class PatternInput < Primer::Forms::Dsl::Input+ attr_reader :name, :value, :suggestions++ def initialize(name:, value:, suggestions:, **system_arguments)+ @name = name+ @value = value+ @suggestions = suggestions++ super(**system_arguments)+ end++ def to_component+ WorkPackages::Types::PatternInput.new(input: self, value:, suggestions:)+ end++ def type+ :pattern_autocompleter+ end++ def focusable?+ true+ end+ end+ end+ end+ end+end