Skip to content

Self-hosted project management for devs and their clients: tickets, time tracking, docs and meetings, with an AI assistant that cites its sources. AGPL-3.0.

Keep typed values when the kind of a detail changes

Guido Boyke9e6d2001b02d
diff --git a/app/helpers/people_helper.rb b/app/helpers/people_helper.rb
index c6db6ee..ceaddcb 100644
--- a/app/helpers/people_helper.rb
+++ b/app/helpers/people_helper.rb
@@ -184,7 +184,10 @@ module PeopleHelper
({ label: Person.human_attribute_name(:function), value: person.function } if person&.function.present?),
({ label: Person.human_attribute_name(:department), value: person.department } if person&.department.present?),
({ label: Person.human_attribute_name(:company), value: person.company } if person&.company.present?),
- ({ label: Person.human_attribute_name(:email), value: email, href: "mailto:#{email}", icon: 'bi-envelope' } if email.present?),
+ if email.present?
+ { label: Person.human_attribute_name(:email), value: email,
+ href: PersonDetail.new('kind' => 'email', 'value' => email).href, icon: 'bi-envelope' }
+ end,
if phone.present?
{ label: Person.human_attribute_name(:phone), value: phone, href: PersonDetail.new('kind' => 'phone', 'value' => phone).href,
icon: 'bi-telephone', mono: true, action: t('views.organisations.people.show.call') }
diff --git a/app/javascript/controllers/person_details_controller.js b/app/javascript/controllers/person_details_controller.js
index 34507b2..23c5204 100644
--- a/app/javascript/controllers/person_details_controller.js
+++ b/app/javascript/controllers/person_details_controller.js
@@ -6,11 +6,11 @@
// Without JavaScript the stored rows still render and save; the add button
// stays hidden, because only adding needs this controller.
import { Controller } from "@hotwired/stimulus"
-import { nextIndex, fillIndex, canAdd, valueField } from "person_details"
+import { nextIndex, fillIndex, canAdd, valueField, singleLine } from "person_details"
export default class extends Controller {
static targets = ["list", "row", "template", "add", "limit"]
- static values = { max: Number, kinds: Object }
+ static values = { max: Number, kinds: Object, positionLabel: String }
connect() {
this.update()
@@ -48,8 +48,17 @@ export default class extends Controller {
const current = row.querySelector("[data-person-details-value]")
if (!current) return
+ const value = field.tag === "textarea" ? current.value : singleLine(current.value)
const next = current.tagName.toLowerCase() === field.tag ? current : this.rebuild(current, field.tag)
if (field.type) next.type = field.type
+ next.value = value
+ // A field that cannot hold the value empties it (a date field and
+ // "im Mai"). The row keeps a text field with the value instead, and the
+ // server names the problem on save; nothing is lost behind a success.
+ if (value !== "" && next.value === "") {
+ next.type = "text"
+ next.value = value
+ }
if (field.maxlength) next.maxLength = field.maxlength
}
@@ -68,6 +77,9 @@ export default class extends Controller {
}
update() {
+ this.rowTargets.forEach((row, index) => {
+ row.setAttribute("aria-label", this.positionLabelValue.replace("%{position}", String(index + 1)))
+ })
const room = canAdd(this.rowTargets.length, this.maxValue)
this.addTarget.hidden = !room
this.limitTarget.hidden = room
diff --git a/app/javascript/lib/person_details.js b/app/javascript/lib/person_details.js
index 4757735..7e1773b 100644
--- a/app/javascript/lib/person_details.js
+++ b/app/javascript/lib/person_details.js
@@ -38,3 +38,13 @@ export function valueField(kinds, kind) {
list: config.list || null
}
}
+
+// A multi-line value (an address) for a single-line field: its lines, trimmed,
+// joined with ", ", so a kind switch keeps what was typed readable.
+export function singleLine(value) {
+ return String(value)
+ .split(/\r\n|\r|\n/)
+ .map((line) => line.trim())
+ .filter((line) => line !== "")
+ .join(", ")
+}
diff --git a/app/models/person_detail.rb b/app/models/person_detail.rb
index 6b95063..46ffd73 100644
--- a/app/models/person_detail.rb
+++ b/app/models/person_detail.rb
@@ -35,13 +35,16 @@ class PersonDetail
ISO_DATE = /\A\d{4}-\d{2}-\d{2}\z/
LINE_BREAK = /\r\n|\r|\n/
NON_ASCII = /[^\x00-\x7F]/
+ INVISIBLE = /[\p{Cc}\p{Cf}]/
attr_reader :kind, :label, :value
# Raw input in, a list of clean entries out: an array of hashes, or the
# indexed hash of the form ({"0" => {...}, "3" => {...}}, ordered by index).
# Only the three keys, as strings; label and value squeezed (an address keeps
- # its lines); a row without a value is dropped. An unknown kind is kept for
+ # its lines); a row without label and value is dropped (an empty row of the
+ # form). A row with a label but no value stays, so the validation names it
+ # instead of losing it behind a success (a value the browser emptied). An unknown kind is kept for
# the validation. Junk from a hand-made request is skipped, never raised on.
def self.normalize(raw)
rows(raw).filter_map { |row| clean(row) }
@@ -88,9 +91,10 @@ class PersonDetail
kind = string_in(row, 'kind')&.squish
value = string_in(row, 'value').to_s
value = kind == 'address' ? address_lines(value).join("\n") : value.squish
- return if value.empty?
+ label = string_in(row, 'label').to_s.squish
+ return if value.empty? && label.empty?
- { 'kind' => kind, 'label' => string_in(row, 'label').to_s.squish, 'value' => value }
+ { 'kind' => kind, 'label' => label, 'value' => value }
end
private_class_method :clean
@@ -173,9 +177,12 @@ class PersonDetail
# A web address may carry umlauts ("https://example.com/wiki/Köln", an
# umlaut domain), which a browser accepts and URI.parse does not: they are
- # escaped for the check only, the stored value stays as written. Control
- # characters and spaces are ASCII and still refused.
+ # escaped for the check only, the stored value stays as written. Control and
+ # format characters (bidi overrides, zero-width, soft hyphen) are refused
+ # first: they would change what the link shows, or break its host.
def http_url?
+ return false if value.match?(INVISIBLE)
+
uri = URI.parse(value.gsub(NON_ASCII) { |char| CGI.escape(char) })
URL_SCHEMES.include?(uri.scheme.to_s.downcase) && uri.host.present?
rescue URI::Error
diff --git a/app/views/organisations/people/_detail_row.html.erb b/app/views/organisations/people/_detail_row.html.erb
index 3db27e6..000e7ff 100644
--- a/app/views/organisations/people/_detail_row.html.erb
+++ b/app/views/organisations/people/_detail_row.html.erb
@@ -1,11 +1,17 @@
-<%# locals: (index:, detail:) %>
+<%# locals: (index:, detail:, invalid: false) %>
<%# One additional detail in the form (PersonDetail): kind, label, value and
a remove button. The rows travel as an indexed hash; the template row
carries __INDEX__, which person_details_controller replaces. The value
- field and the label suggestions follow the kind (person_detail_field). %>
+ field and the label suggestions follow the kind (person_detail_field).
+ The row is a group named by its position ("Angabe 3"), the number a
+ refused save names; person_details_controller renumbers after a change. %>
<% field = person_detail_field(detail.kind) %>
+<%# A date field cannot show a value that is no date (it would come back empty
+ and the next save would lose it): such a value stays in a text field. %>
+<% input = field[:input] == 'date' && detail.value.present? && detail.date.nil? ? 'text' : field[:input] %>
<% name = "person[additional_details][#{index}]" %>
-<div class="people-detail-row" data-person-details-target="row" data-index="<%= index %>">
+<div class="people-detail-row" role="group" data-person-details-target="row" data-index="<%= index %>"
+ aria-label="<%= t('views.organisations.people.form.detail_position', position: index.is_a?(Integer) ? index + 1 : index) %>">
<%= select_tag "#{name}[kind]", options_for_select(person_detail_kind_options, detail.kind),
id: nil, class: 'people-input people-detail-row__kind',
'aria-label': t('views.organisations.people.form.detail_kind'),
@@ -21,10 +27,11 @@
<i class="bi bi-x-lg" aria-hidden="true"></i>
</button>
<% value_options = { id: nil, maxlength: field[:maxlength], 'aria-label': t('views.organisations.people.form.detail_value'),
+ 'aria-invalid': ('true' if invalid),
data: { person_details_value: true } } %>
- <% if field[:input] == 'textarea' %>
+ <% if input == 'textarea' %>
<%= text_area_tag "#{name}[value]", detail.value, rows: 3, class: 'people-input people-input--area people-detail-row__value', **value_options %>
<% else %>
- <%= tag.input type: field[:input], name: "#{name}[value]", value: detail.value, class: 'people-input people-detail-row__value', **value_options %>
+ <%= tag.input type: input, name: "#{name}[value]", value: detail.value, class: 'people-input people-detail-row__value', **value_options %>
<% end %>
</div>
diff --git a/app/views/organisations/people/_form.html.erb b/app/views/organisations/people/_form.html.erb
index 4727d74..f51f995 100644
--- a/app/views/organisations/people/_form.html.erb
+++ b/app/views/organisations/people/_form.html.erb
@@ -86,14 +86,17 @@
placeholder: t('views.organisations.people.form.placeholders.phone') %>
</div>
+ <% invalid_positions = person.errors.details[:additional_details].filter_map { |error| error[:position] } %>
<fieldset class="people-form__details" data-controller="person-details"
data-person-details-max-value="<%= PersonDetail::MAX %>"
+ data-person-details-position-label-value="<%= t('views.organisations.people.form.detail_position', position: '%{position}') %>"
data-person-details-kinds-value="<%= person_detail_fields_config.to_json %>">
<legend><%= Person.human_attribute_name(:additional_details) %></legend>
<%= hidden_field_tag "person[additional_details][#{PersonDetail::FORM_MARKER}]", '1', id: nil %>
<div class="people-form__detail-rows" data-person-details-target="list">
<% person.additional_details.each_with_index do |entry, index| %>
- <%= render 'organisations/people/detail_row', index: index, detail: PersonDetail.new(entry) %>
+ <%= render 'organisations/people/detail_row', index: index, detail: PersonDetail.new(entry),
+ invalid: invalid_positions.include?(index + 1) %>
<% end %>
</div>
<template data-person-details-target="template">
diff --git a/config/locales/views/personen.de.yml b/config/locales/views/personen.de.yml
index f8fd9b6..8373ddf 100644
--- a/config/locales/views/personen.de.yml
+++ b/config/locales/views/personen.de.yml
@@ -102,7 +102,7 @@ de:
delete: "Löschen"
delete_confirm: "%{name} wird aus der Liste gelöscht. Das lässt sich nicht rückgängig machen."
remove_details: "Ergänzte Angaben entfernen"
- remove_details_confirm: "Alle ergänzten Angaben von %{name} werden entfernt (Anrede, Funktion, Abteilung, Telefon, Notiz und weitere Angaben), das Konto bleibt. Das lässt sich nicht rückgängig machen."
+ remove_details_confirm: "Alle ergänzten Angaben von %{name} werden entfernt (Anrede, Funktion, Abteilung, Firma, Telefon, Notiz und weitere Angaben), das Konto bleibt. Das lässt sich nicht rückgängig machen."
details:
kinds:
phone: "Telefon"
@@ -128,6 +128,7 @@ de:
detail_kind: "Art"
detail_label: "Bezeichnung"
detail_label_placeholder: "Bezeichnung, z. B. Mobil"
+ detail_position: "Angabe %{position}"
detail_value: "Wert"
add_detail: "Angabe hinzufügen"
remove_detail: "Angabe entfernen"
diff --git a/config/locales/views/personen.en.yml b/config/locales/views/personen.en.yml
index 67c8a60..986f690 100644
--- a/config/locales/views/personen.en.yml
+++ b/config/locales/views/personen.en.yml
@@ -102,7 +102,7 @@ en:
delete: "Delete"
delete_confirm: "%{name} will be deleted from the list. This cannot be undone."
remove_details: "Remove added details"
- remove_details_confirm: "All added details of %{name} will be removed (salutation, function, department, phone, note and additional details), the account stays. This cannot be undone."
+ remove_details_confirm: "All added details of %{name} will be removed (salutation, function, department, company, phone, note and additional details), the account stays. This cannot be undone."
details:
kinds:
phone: "Phone"
@@ -128,6 +128,7 @@ en:
detail_kind: "Kind"
detail_label: "Label"
detail_label_placeholder: "Label, e.g. Mobile"
+ detail_position: "Detail %{position}"
detail_value: "Value"
add_detail: "Add detail"
remove_detail: "Remove detail"
diff --git a/spec/helpers/people_helper_spec.rb b/spec/helpers/people_helper_spec.rb
index 8c23717..1323c26 100644
--- a/spec/helpers/people_helper_spec.rb
+++ b/spec/helpers/people_helper_spec.rb
@@ -125,6 +125,13 @@ RSpec.describe PeopleHelper, type: :helper do
expect(fields_for(phone: 'nur Zentrale').first[:href]).to be_nil
end
+ # Review round 2, finding 6: the fixed email links through the same rule.
+ it 'links the fixed email through PersonDetail, and not a malformed one' do
+ expect(helper.person_fields(Person.new(name: 'M', email: '[email protected]'), nil).first[:href])
+ .to eq('mailto:[email protected]')
+ expect(helper.person_fields(Person.new(name: 'M', email: 'kaputt'), nil).first[:href]).to be_nil
+ end
+
it 'shows no line for a person without details' do
expect(fields_for(phone: nil)).to eq([])
end
diff --git a/spec/javascript/lib/person_details.test.js b/spec/javascript/lib/person_details.test.js
index 56d019b..0676cc9 100644
--- a/spec/javascript/lib/person_details.test.js
+++ b/spec/javascript/lib/person_details.test.js
@@ -5,7 +5,7 @@
// kind must not break a row.
import { test } from "node:test"
import assert from "node:assert/strict"
-import { nextIndex, fillIndex, canAdd, valueField } from "../../../app/javascript/lib/person_details.js"
+import { nextIndex, fillIndex, canAdd, valueField, singleLine } from "../../../app/javascript/lib/person_details.js"
test("a new row takes the index above the highest present one", () => {
assert.equal(nextIndex([]), 0)
@@ -48,3 +48,12 @@ test("gives an unknown kind a plain text input, also for inherited names", () =>
assert.deepEqual(valueField(KINDS, "constructor"), { tag: "input", type: "text", maxlength: null, list: null })
assert.deepEqual(valueField(undefined, "phone"), { tag: "input", type: "text", maxlength: null, list: null })
})
+
+// Review round 2, finding 1: an address switched to a single-line kind lost
+// its line breaks without a separator ("Musterstraße 112345 Berlin").
+test("joins the lines of a multi-line value for a single-line field", () => {
+ assert.equal(singleLine("Musterstraße 1\n12345 Berlin"), "Musterstraße 1, 12345 Berlin")
+ assert.equal(singleLine(" A \r\n\r\n B \r C "), "A, B, C")
+ assert.equal(singleLine("eine Zeile"), "eine Zeile")
+ assert.equal(singleLine(""), "")
+})
diff --git a/spec/models/person_detail_spec.rb b/spec/models/person_detail_spec.rb
index 5552301..01e4a3b 100644
--- a/spec/models/person_detail_spec.rb
+++ b/spec/models/person_detail_spec.rb
@@ -30,12 +30,18 @@ RSpec.describe PersonDetail do
expect(described_class.normalize(raw).first).to include('label' => 'Büro Zentrale', 'value' => '+49 30 1234567')
end
- it 'drops a row without a value (an empty row of the form is no detail)' do
- raw = [detail(value: ' '), detail(value: nil), detail(kind: 'phone', label: 'Fax', value: '1')]
+ it 'drops a row without a label and a value (an empty row of the form is no detail)' do
+ raw = [detail(label: '', value: ' '), detail(label: ' ', value: nil), detail(kind: 'phone', label: 'Fax', value: '1')]
expect(described_class.normalize(raw)).to eq([detail(kind: 'phone', label: 'Fax', value: '1')])
end
+ # Review round 2, finding 1: a row whose value the browser emptied (a
+ # kind switch) kept its label; dropping it lost the row behind a success.
+ it 'keeps a row with a label but no value, for the validation to name it' do
+ expect(described_class.normalize([detail(label: 'Geburtstag', value: ' ')])).to eq([detail(label: 'Geburtstag', value: '')])
+ end
+
it 'keeps an empty label as an empty string' do
expect(described_class.normalize([detail(label: nil)]).first['label']).to eq('')
end
@@ -133,8 +139,12 @@ RSpec.describe PersonDetail do
end
end
- it 'still refuses spaces and control characters next to an umlaut' do
- ['https://exa mple.com/Köln', "https://example.com/Köln\u0000", "java\tscript:alert('ö')"].each do |value|
+ # Review round 2, finding 2: escaping the umlauts must not let invisible
+ # and control characters through (bidi overrides turn the shown text).
+ it 'still refuses spaces, control and format characters next to an umlaut' do
+ ['https://exa mple.com/Köln', "https://example.com/Köln\u0000", "java\tscript:alert('ö')",
+ "https://\u202Emoc.elpmaxe", "https://ex\u0080ample.com", "https://exa\u200Bmple.com",
+ "https://exa\u00ADmple.com"].each do |value|
expect(problems(detail(kind: 'url', value: value))).to eq([[:invalid_url, { position: 1 }]]), value.inspect
end
end
@@ -152,8 +162,10 @@ RSpec.describe PersonDetail do
expect(problems(detail(kind: nil))).to eq([[:unknown_kind, { position: 1 }]])
end
- it 'refuses a detail without a value (written around the normalisation)' do
+ it 'refuses a detail without a value' do
expect(problems(detail(value: ''))).to eq([[:value_missing, { position: 1 }]])
+ expect(described_class.problems(described_class.normalize([detail(label: 'Fax', value: '')])))
+ .to eq([[:value_missing, { position: 1 }]])
end
it 'refuses an entry that is no hash' do
diff --git a/spec/models/person_spec.rb b/spec/models/person_spec.rb
index ae2243b..126cadf 100644
--- a/spec/models/person_spec.rb
+++ b/spec/models/person_spec.rb
@@ -72,7 +72,7 @@ RSpec.describe Person, type: :model do
it 'normalizes them through PersonDetail before the validation' do
person = create(:person, organisation: organisation,
- additional_details: { '1' => detail(value: ' +49 30 2 '), '0' => detail(label: ' Mobil ', value: '') })
+ additional_details: { '1' => detail(value: ' +49 30 2 '), '0' => detail(label: ' ', value: '') })
expect(person.reload.additional_details).to eq([detail(value: '+49 30 2')])
end
diff --git a/spec/requests/organisations/people_spec.rb b/spec/requests/organisations/people_spec.rb
index 0b14209..e105fa0 100644
--- a/spec/requests/organisations/people_spec.rb
+++ b/spec/requests/organisations/people_spec.rb
@@ -437,6 +437,30 @@ RSpec.describe 'Organisations::People', :ci_guard, type: :request do
expect(person.phone).to eq('+49 30 1234567')
end
+ # Review round 2, finding 1: a kind switch in the browser can empty a value
+ # (a date field and "im Mai"). A row that keeps its label is named, not lost.
+ it 'refuses a row with a label but no value, with its position' do
+ person.update!(additional_details: [row('text', 'bleibt')])
+
+ patch_details(person, details_params(row('text', 'bleibt'), row('date', '', label: 'Geburtstag')))
+
+ expect(response).to have_http_status(:unprocessable_content)
+ reason = I18n.t('activerecord.errors.models.person.attributes.additional_details.value_missing', position: 2)
+ expect(response.body).to include(CGI.escapeHTML(reason))
+ expect(person.reload.additional_details).to eq([{ 'kind' => 'text', 'label' => '', 'value' => 'bleibt' }])
+ end
+
+ it 'shows a refused date that is no date in a text field, marked invalid in its numbered row' do
+ patch_details(person, details_params(row('text', 'ok'), row('date', 'im Mai', label: 'Geburtstag')))
+
+ expect(response).to have_http_status(:unprocessable_content)
+ rows = Nokogiri::HTML(response.body).css('[data-person-details-target="list"] [data-person-details-target="row"]')
+ value = rows[1].at_css('[data-person-details-value]')
+ expect([value['type'], value['value'], value['aria-invalid']]).to eq(['text', 'im Mai', 'true'])
+ expect(rows[0].at_css('[data-person-details-value]')['aria-invalid']).to be_nil
+ expect(rows.pluck('aria-label')).to eq([1, 2].map { |n| I18n.t('views.organisations.people.form.detail_position', position: n) })
+ end
+
it 'refuses an eleventh detail' do
patch_details(person, details_params(*Array.new(PersonDetail::MAX + 1) { row('text', 'x') }))
@@ -958,6 +982,12 @@ RSpec.describe 'Organisations::People', :ci_guard, type: :request do
expect(response.body).to include(I18n.t('views.organisations.people.show.remove_details'))
expect(response.body).not_to include(">#{I18n.t('views.organisations.people.show.delete')}<")
+ # Review round 2, finding 3: the confirmation names what goes, the
+ # additional details included.
+ confirm = I18n.t('views.organisations.people.show.remove_details_confirm', name: viewer.display_name)
+ expect(Nokogiri::HTML(response.body).css('[data-turbo-confirm]').pluck('data-turbo-confirm')).to include(confirm)
+ expect(confirm.downcase).to include(Person.human_attribute_name(:company).downcase,
+ Person.human_attribute_name(:additional_details).downcase)
end
it 'shows the email of the account, and locks name and email in the form' do
diff --git a/spec/system/people_additional_details_spec.rb b/spec/system/people_additional_details_spec.rb
index 4c430b0..42f9733 100644
--- a/spec/system/people_additional_details_spec.rb
+++ b/spec/system/people_additional_details_spec.rb
@@ -119,6 +119,45 @@ RSpec.describe 'People additional details in the form', type: :system do
expect(person.reload.additional_details.pluck('value')).to eq(['zwei', 'drei', '+49 30 4'])
end
+ # Review round 2, finding 1: a kind switch emptied a date and lost the line
+ # breaks of an address, and the save then dropped the row behind a success.
+ it 'keeps what was typed when the kind changes, and names a value that does not fit' do
+ person.update!(additional_details: [{ 'kind' => 'address', 'label' => 'Büro', 'value' => "Musterstraße 1\n12345 Berlin" },
+ { 'kind' => 'text', 'label' => 'Geburtstag', 'value' => 'im Mai' }])
+ open_form
+
+ within(rows[0]) do
+ find('select').select(kind_name('text'))
+ expect(find('input[data-person-details-value]').value).to eq('Musterstraße 1, 12345 Berlin')
+ end
+ within(rows[1]) do
+ find('select').select(kind_name('date'))
+ expect(find('[data-person-details-value]').value).to eq('im Mai')
+ end
+ click_button I18n.t('views.organisations.people.form.save')
+
+ reason = I18n.t('activerecord.errors.models.person.attributes.additional_details.invalid_date', position: 2)
+ expect(page).to have_text(reason)
+ expect(rows[1].find('[data-person-details-value]').value).to eq('im Mai')
+ expect(person.reload.additional_details.pluck('value')).to eq(["Musterstraße 1\n12345 Berlin", 'im Mai'])
+ end
+
+ # Review round 2, findings 4 and 5: focus after adding and removing, and the
+ # rows named by their position after a removal.
+ it 'moves the focus to the new row and back to the add button, and renumbers the rows' do
+ open_form
+ add_button.click
+ add_button.click
+
+ expect(page.evaluate_script('document.activeElement === document.querySelectorAll("[data-person-details-target=list] select")[1]'))
+ .to be(true)
+ within(rows[0]) { click_button remove_label }
+
+ expect(page.evaluate_script('document.activeElement.dataset.personDetailsTarget')).to eq('add')
+ expect(rows.map { |row| row['aria-label'] })
+ .to eq([I18n.t('views.organisations.people.form.detail_position', position: 1)])
+ end
+
it 'hides the add button at ten with a note, and shows it again after a remove' do
open_form
hint = I18n.t('views.organisations.people.form.details_limit', count: PersonDetail::MAX)