The personal finance app for everyone (by everyone)
Ruby
feat(categories): choose a parent when creating a category inline (#3774)
scragnog7dc33b99019d
diff --git a/app/components/DS/category_select.html.erb b/app/components/DS/category_select.html.erbindex a33f0db561..165d6e6f8f 100644--- a/app/components/DS/category_select.html.erb+++ b/app/components/DS/category_select.html.erb@@ -6,6 +6,7 @@data-category-select-auto-submit-value="<%= auto_submit %>"data-category-select-create-label-value="<%= helpers.t("transactions.form.create_category", name: "__CATEGORY_NAME__") %>"data-category-select-create-error-message-value="<%= helpers.t("transactions.form.create_category_error") %>"+ data-category-select-parent-picker-label-value="<%= helpers.t("transactions.form.choose_parent", name: "__CATEGORY_NAME__") %>"data-action="click@window->category-select#handleOutsideClick"><div class="form-field">@@ -47,7 +48,8 @@<% unless disabled %><div class="absolute z-50 p-1.5 w-full min-w-48 rounded-lg shadow-lg bg-container mt-1.5 hidden"- data-category-select-target="menu">+ data-category-select-target="menu"+ data-action="keydown.esc->category-select#escape"><%= render DS::SearchInput.new(variant: :embedded,@@ -60,7 +62,8 @@<div class="flex flex-col gap-1 max-h-64 overflow-auto mt-1"id="<%= menu_id %>"- role="listbox">+ role="listbox"+ data-category-select-target="list"><% if blank_label.present? %><button type="button"@@ -107,9 +110,61 @@<span data-category-select-target="createLabel"></span><% end %>+ <%# Hidden by the controller while there is no top-level category to nest under. %>+ <%= render DS::ActionRow.new(+ text: helpers.t("transactions.form.create_as_subcategory"),+ icon: "corner-down-right",+ tone: :secondary,+ hidden: true,+ data: { category_select_target: "createAsSubcategory", action: "click->category-select#showParentPicker" }+ ) %>+<p class="hidden px-3 py-1 text-xs text-destructive"+ role="alert"data-category-select-target="createError"></p></div>++ <%# Shown in place of the list after "Add as a subcategory…": pick a top-level parent. %>+ <%# Only top-level categories can be parents (categories are at most two levels deep). %>+ <div class="hidden flex-col gap-1 mt-1"+ data-category-select-target="parentPicker"+ role="group"+ aria-labelledby="<%= parent_label_id %>">+ <%# Back and the label sit above the scrolling rows, so Back stays in reach with many parents. %>+ <div class="flex flex-col">+ <%= render DS::ActionRow.new(+ text: helpers.t("transactions.form.back_to_categories"),+ icon: "arrow-left",+ tone: :secondary,+ data: { category_select_target: "parentBack", action: "click->category-select#hideParentPicker" }+ ) %>+ <p id="<%= parent_label_id %>"+ class="px-3 py-1 text-xs text-secondary"+ data-category-select-target="parentPickerLabel"></p>+ </div>++ <div class="flex flex-col gap-1 max-h-64 overflow-auto"+ data-category-select-target="parentRows">+ <% parent_options.each do |parent| %>+ <%= render DS::ActionRow.new(+ tone: :secondary,+ data: { category_select_target: "parentOption", parent_id: parent.id, parent_name: parent.name, action: "click->category-select#createUnderParent" }+ ) do %>+ <%= render partial: "categories/badge", locals: { category: parent } %>+ <% end %>+ <% end %>++ <%# Cloned for a top-level category created inline, so it can be a parent straight away. %>+ <template data-category-select-target="parentOptionTemplate">+ <%= render DS::ActionRow.new(+ tone: :secondary,+ data: { category_select_target: "parentOption", action: "click->category-select#createUnderParent" }+ ) do %>+ <span data-category-select-parent-badge></span>+ <% end %>+ </template>+ </div>+ </div></div><% end %></div>diff --git a/app/components/DS/category_select.rb b/app/components/DS/category_select.rbindex cf84f3bf0e..f8e152de3b 100644--- a/app/components/DS/category_select.rb+++ b/app/components/DS/category_select.rb@@ -32,4 +32,13 @@ class DS::CategorySelect < DesignSystemComponentdef menu_id"#{field_id}_menu"end++ def parent_label_id+ "#{menu_id}_parent_label"+ end++ # Only top-level categories can be parents (categories are two levels deep).+ def parent_options+ categories.select { |category| category.parent_id.nil? }.sort_by { |category| category.name.downcase }+ endenddiff --git a/app/javascript/controllers/category_select_controller.js b/app/javascript/controllers/category_select_controller.jsindex efc4f59dd3..b3b82ea263 100644--- a/app/javascript/controllers/category_select_controller.js+++ b/app/javascript/controllers/category_select_controller.js@@ -12,6 +12,14 @@ export default class extends Controller {"createForm","createLabel","createError",+ "list",+ "createAsSubcategory",+ "parentPicker",+ "parentPickerLabel",+ "parentOption",+ "parentOptionTemplate",+ "parentRows",+ "parentBack",];static values = {@@ -21,6 +29,7 @@ export default class extends Controller {autoSubmit: Boolean,createLabel: String,createErrorMessage: String,+ parentPickerLabel: String,};connect() {@@ -42,6 +51,7 @@ export default class extends Controller {this.searchTarget.value = "";this.filter();+ this.hideParentPicker();requestAnimationFrame(() => this.searchTarget.focus());}@@ -54,6 +64,8 @@ export default class extends Controller {filter() {this.clearCreateError();+ // Editing the name returns to the list, so the picker never shows a stale name.+ this.hideParentPicker();const rawQuery = this.searchTarget.value.trim();const query = rawQuery.toLowerCase();@@ -74,21 +86,30 @@ export default class extends Controller {this.createFormTarget.classList.toggle("hidden", !canCreate);this.createFormTarget.classList.toggle("flex", canCreate);+ if (this.hasCreateAsSubcategoryTarget) {+ // Nesting needs at least one top-level category to nest under.+ const canNest = canCreate && this.parentOptionTargets.length > 0;+ this.createAsSubcategoryTarget.classList.toggle("hidden", !canNest);+ this.createAsSubcategoryTarget.classList.toggle("flex", canNest);+ }+this.createLabelTarget.textContent =this.createLabelValue.replace("__CATEGORY_NAME__", rawQuery);}handleSearchKeydown(event) {- if (event.key === "Escape") {+ // With the parent picker open, Enter moves into it instead of creating a+ // top-level category (or submitting the surrounding form).+ if (event.key === "Enter" && this.#parentPickerOpen()) {event.preventDefault();- this.close();- this.buttonTarget.focus();+ this.parentOptionTargets[0]?.focus();return;}if (event.key === "Enter" &&!this.createFormTarget.classList.contains("hidden") &&+ !this.#parentPickerOpen() &&!this.creating) {event.preventDefault();@@ -96,6 +117,18 @@ export default class extends Controller {}}+ // Escape from anywhere in the menu: leave the parent picker first, then+ // close the menu, keeping focus where the keyboard user can carry on.+ escape(event) {+ event.preventDefault();+ if (this.#parentPickerOpen()) {+ this.hideParentPicker(event);+ return;+ }+ this.close();+ this.buttonTarget.focus();+ }+selectCategory(event) {event.preventDefault();@@ -137,14 +170,56 @@ export default class extends Controller {}}- async createCategory() {+ showParentPicker(event) {+ event?.preventDefault();+ if (!this.hasParentPickerTarget) return;++ const name = this.searchTarget.value.trim();+ if (!name) return;++ this.parentPickerLabelTarget.textContent =+ this.parentPickerLabelValue.replace("__CATEGORY_NAME__", name);++ this.listTarget.classList.add("hidden");+ this.parentPickerTarget.classList.remove("hidden");+ this.parentPickerTarget.classList.add("flex");++ // The button that opened the picker is now hidden; move focus into it.+ this.parentOptionTargets[0]?.focus();+ }++ // From Back or Escape (an event) focus returns to the search; when filter()+ // or open() reset the picker, focus is left alone.+ hideParentPicker(event) {+ event?.preventDefault();+ if (!this.hasParentPickerTarget) return;++ const wasOpen = this.#parentPickerOpen();+ this.parentPickerTarget.classList.add("hidden");+ this.parentPickerTarget.classList.remove("flex");+ this.listTarget.classList.remove("hidden");++ if (event && wasOpen) this.searchTarget.focus();+ }++ createUnderParent(event) {+ event.preventDefault();+ this.#create(event.currentTarget.dataset.parentId);+ }++ createCategory(event) {+ event?.preventDefault();+ this.#create(null);+ }++ async #create(parentId) {if (this.creating) return;const name = this.searchTarget.value.trim();if (!name) return;this.creating = true;- this.createFormTarget.disabled = true;+ this.#setCreating(true);this.clearCreateError();try {@@ -152,20 +227,26 @@ export default class extends Controller {url: this.createUrlValue,name,color: this.defaultColorValue,+ parentId,});if (!category) {+ this.hideParentPicker();this.showCreateError(error);return;}- this.createFormTarget.insertAdjacentHTML("beforebegin", category.html);+ // A subcategory goes at the end of its parent's group, not the list.+ const anchor = parentId ? this.#lastOptionInGroup(parentId) : null;+ if (anchor) anchor.insertAdjacentHTML("afterend", category.html);+ else this.createFormTarget.insertAdjacentHTML("beforebegin", category.html);const newOption = this.optionTargets.find((option) => option.dataset.categoryId === String(category.id),);if (newOption) this.selectOption(newOption);+ if (!parentId) this.#addParentOption(category, newOption);this.searchTarget.value = "";this.filter();@@ -173,8 +254,61 @@ export default class extends Controller {this.submitForm();} finally {this.creating = false;- this.createFormTarget.disabled = false;+ this.#setCreating(false);+ }+ }++ #parentPickerOpen() {+ return (+ this.hasParentPickerTarget &&+ !this.parentPickerTarget.classList.contains("hidden")+ );+ }++ // Disable every way of creating while a request runs, so a slow POST+ // visibly can't be repeated from the picker either.+ #setCreating(creating) {+ this.createFormTarget.disabled = creating;+ for (const row of this.parentOptionTargets) row.disabled = creating;+ }++ #lastOptionInGroup(parentId) {+ let node = this.optionTargets.find(+ (option) => option.dataset.categoryId === String(parentId),+ );+ while (+ node?.nextElementSibling?.querySelector?.(+ "[data-testid=category-select-subcategory-indicator]",+ )+ ) {+ node = node.nextElementSibling;}+ return node;+ }++ // A top-level category created inline can be a parent straight away,+ // without reloading: add it to the parent picker in alphabetical order.+ #addParentOption(category, option) {+ if (!this.hasParentOptionTemplateTarget) return;++ const row =+ this.parentOptionTemplateTarget.content.firstElementChild.cloneNode(true);+ row.dataset.parentId = String(category.id);+ row.dataset.parentName = category.name;++ const badge = option?.querySelector("[data-category-select-badge]");+ const slot = row.querySelector("[data-category-select-parent-badge]");+ if (badge && slot) slot.replaceWith(badge.cloneNode(true));++ const name = category.name.toLocaleLowerCase();+ const before = this.parentOptionTargets.find(+ (existing) =>+ (existing.dataset.parentName || "").toLocaleLowerCase() > name,+ );+ this.parentRowsTarget.insertBefore(+ row,+ before || this.parentOptionTemplateTarget,+ );}async submitForm() {diff --git a/app/models/category.rb b/app/models/category.rbindex 8962600ae8..f1c6bdd6a0 100644--- a/app/models/category.rb+++ b/app/models/category.rb@@ -27,6 +27,7 @@ class Category < ApplicationRecordvalidates :name, exclusion: { in: [ UNCATEGORIZED_FILTER_VALUE ] }validate :category_level_limit+ validate :parent_in_same_familybefore_save :inherit_color_from_parent@@ -412,6 +413,12 @@ class Category < ApplicationRecordendend+ def parent_in_same_family+ return if parent.nil? || parent.family_id == family_id++ errors.add(:parent, :invalid)+ end+def monetizable_currencyfamily.currencyenddiff --git a/config/locales/views/transactions/ca.yml b/config/locales/views/transactions/ca.ymlindex 474d3070e2..cc60715222 100644--- a/config/locales/views/transactions/ca.yml+++ b/config/locales/views/transactions/ca.yml@@ -171,6 +171,9 @@ ca:category_search_placeholder: Cerca categoriescreate_category: Crea "%{name}"create_category_error: No s'ha pogut crear la categoria+ create_as_subcategory: Afegeix com a subcategoria…+ choose_parent: 'Crea "%{name}" dins de:'+ back_to_categories: Enrerecreate_merchant: Creacreate_merchant_error: No s'ha pogut crear el comerçmerchant_search_placeholder: Cerca o crea un comerçdiff --git a/config/locales/views/transactions/de.yml b/config/locales/views/transactions/de.ymlindex dcd396a4db..8101daa94d 100644--- a/config/locales/views/transactions/de.yml+++ b/config/locales/views/transactions/de.yml@@ -11,6 +11,9 @@ de:category_prompt: Kategorie auswählencreate_category: '„%{name}“ erstellen'create_category_error: Kategorie konnte nicht erstellt werden+ create_as_subcategory: Als Unterkategorie hinzufügen…+ choose_parent: '„%{name}“ erstellen unter:'+ back_to_categories: Zurückdate: Datumdescription: Beschreibungdescription_placeholder: Transaktion beschreibendiff --git a/config/locales/views/transactions/en.yml b/config/locales/views/transactions/en.ymlindex 559e143bcf..22d427a91e 100644--- a/config/locales/views/transactions/en.yml+++ b/config/locales/views/transactions/en.yml@@ -35,6 +35,9 @@ en:category_search_placeholder: Search categoriescreate_category: 'Create "%{name}"'create_category_error: Could not create category+ create_as_subcategory: Add as a subcategory…+ choose_parent: 'Create "%{name}" under:'+ back_to_categories: Backdate: Datedescription: Descriptiondescription_placeholder: Describe transactiondiff --git a/config/locales/views/transactions/fr.yml b/config/locales/views/transactions/fr.ymlindex a72285e755..0530a0cf45 100644--- a/config/locales/views/transactions/fr.yml+++ b/config/locales/views/transactions/fr.yml@@ -141,6 +141,9 @@ fr:category_search_placeholder: Rechercher des catégoriescreate_category: Créer « %{name} »create_category_error: Impossible de créer la catégorie+ create_as_subcategory: Ajouter comme sous-catégorie…+ choose_parent: 'Créer « %{name} » dans :'+ back_to_categories: Retourcreate_merchant: Créercreate_merchant_error: Impossible de créer le marchandcreate_tag: Créerdiff --git a/config/locales/views/transactions/pl.yml b/config/locales/views/transactions/pl.ymlindex eb3a6b8f33..ab0d516a31 100644--- a/config/locales/views/transactions/pl.yml+++ b/config/locales/views/transactions/pl.yml@@ -164,6 +164,9 @@ pl:category_search_placeholder: Szukaj kategoriicreate_category: Utwórz "%{name}"create_category_error: Nie udało się utworzyć kategorii+ create_as_subcategory: Dodaj jako podkategorię…+ choose_parent: 'Utwórz "%{name}" w:'+ back_to_categories: Wsteczcreate_merchant: Utwórzcreate_merchant_error: Nie udało się utworzyć kontrahentacreate_tag: Utwórzdiff --git a/config/locales/views/transactions/pt-PT.yml b/config/locales/views/transactions/pt-PT.ymlindex cfa405edab..1b2e5f3e44 100644--- a/config/locales/views/transactions/pt-PT.yml+++ b/config/locales/views/transactions/pt-PT.yml@@ -35,6 +35,9 @@ pt-PT:category_search_placeholder: Procurar categoriascreate_category: 'Criar "%{name}"'create_category_error: Não foi possível criar a categoria+ create_as_subcategory: Adicionar como subcategoria…+ choose_parent: 'Criar "%{name}" em:'+ back_to_categories: Voltardate: Datadescription: Descriçãodescription_placeholder: Descreva a transaçãodiff --git a/config/locales/views/transactions/ru.yml b/config/locales/views/transactions/ru.ymlindex 6b4feb9d5d..1291afe808 100644--- a/config/locales/views/transactions/ru.yml+++ b/config/locales/views/transactions/ru.yml@@ -180,6 +180,9 @@ ru:category_search_placeholder: Поиск категорийcreate_category: Создать «%{name}»create_category_error: Не удалось создать категорию+ create_as_subcategory: Добавить как подкатегорию…+ choose_parent: 'Создать «%{name}» в:'+ back_to_categories: Назадcreate_merchant: Создатьcreate_merchant_error: Не удалось создать продавцаmerchant_search_placeholder: Найдите или создайте продавцаdiff --git a/config/locales/views/transactions/tr.yml b/config/locales/views/transactions/tr.ymlindex f5a5d6f7cd..24c4be2978 100644--- a/config/locales/views/transactions/tr.yml+++ b/config/locales/views/transactions/tr.yml@@ -172,6 +172,9 @@ tr:category_search_placeholder: Kategori aracreate_category: '"%{name}" oluştur'create_category_error: Kategori oluşturulamadı+ create_as_subcategory: Alt kategori olarak ekle…+ choose_parent: '"%{name}" şunun altında oluştur:'+ back_to_categories: Gericreate_merchant: Oluşturcreate_merchant_error: Satıcı oluşturulamadımerchant_search_placeholder: Satıcı ara veya oluşturdiff --git a/config/locales/views/transactions/uk.yml b/config/locales/views/transactions/uk.ymlindex f0aa4bb1b9..0f0c98a34d 100644--- a/config/locales/views/transactions/uk.yml+++ b/config/locales/views/transactions/uk.yml@@ -48,6 +48,9 @@ uk:category_search_placeholder: Пошук категорійcreate_category: Створити «%{name}»create_category_error: Не вдалося створити категорію+ create_as_subcategory: Додати як підкатегорію…+ choose_parent: 'Створити «%{name}» у:'+ back_to_categories: Назадcreate_merchant: Створитиcreate_merchant_error: Не вдалося створити продавцяmerchant_search_placeholder: Знайдіть або створіть продавцяdiff --git a/test/controllers/categories_controller_test.rb b/test/controllers/categories_controller_test.rbindex e309ce0733..53fae754ba 100644--- a/test/controllers/categories_controller_test.rb+++ b/test/controllers/categories_controller_test.rb@@ -119,6 +119,33 @@ class CategoriesControllerTest < ActionDispatch::IntegrationTestassert response_json.fetch("errors").any?end+ test "create as json with a parent makes a subcategory" do+ parent = categories(:food_and_drink)++ assert_difference "Category.count", +1 do+ post categories_url(format: :json), params: {+ category: { name: "JSON Subcategory", color: Category::COLORS.first, parent_id: parent.id } }+ end++ assert_response :created+ new_category = Category.find(JSON.parse(response.body).fetch("id"))+ assert_equal parent, new_category.parent+ assert_includes JSON.parse(response.body).fetch("html"), "category-select-subcategory-indicator"+ end++ test "create as json rejects a parent from another family" do+ foreign_parent = families(:empty).categories.create!(name: "Foreign Parent", color: "#123456")++ assert_no_difference "Category.count" do+ post categories_url(format: :json), params: {+ category: { name: "Sneaky Child", color: Category::COLORS.first, parent_id: foreign_parent.id } }+ end++ assert_response :unprocessable_entity+ # The inline create reads `errors` first (then `error`, then `message`).+ assert_includes JSON.parse(response.body).fetch("errors"), "Parent is invalid"+ end+test "create and assign to transaction" docolor = Category::COLORS.samplediff --git a/test/models/category_test.rb b/test/models/category_test.rbindex 803e08e3d0..714b2572e9 100644--- a/test/models/category_test.rb+++ b/test/models/category_test.rb@@ -57,6 +57,24 @@ class CategoryTest < ActiveSupport::TestCaseassert_nil category.parentend+ test "a parent must belong to the same family" do+ other_family = families(:empty)+ foreign_parent = other_family.categories.create!(name: "Foreign Parent", color: "#123456")++ category = @family.categories.new(name: "Cross Family Child", color: "#000000", parent: foreign_parent)++ assert_not category.valid?+ assert category.errors.of_kind?(:parent, :invalid)+ end++ test "a parent from the same family is accepted" do+ parent = categories(:food_and_drink)+ category = @family.categories.create!(name: "Same Family Child", color: "#000000", parent: parent)++ assert_equal parent, category.parent+ assert_equal parent.color, category.color, "subcategories inherit their parent's color"+ end+test "subcategory can only be one level deep" docategory = categories(:subcategory)diff --git a/test/system/transaction_category_select_test.rb b/test/system/transaction_category_select_test.rbindex c1dabdfaee..6427361230 100644--- a/test/system/transaction_category_select_test.rb+++ b/test/system/transaction_category_select_test.rb@@ -56,4 +56,180 @@ class TransactionCategorySelectTest < ApplicationSystemTestCaseassert_nil transaction.reload.category_idend++ test "can create a subcategory from the transaction form" do+ parent = categories(:food_and_drink)+ visit new_transaction_url++ assert_difference "Category.count", +1 do+ find("[data-controller='category-select'] button").click++ within "[data-controller='category-select']" do+ fill_in "Search categories", with: "Inline Subcategory"+ click_button "Add as a subcategory…"++ assert_text 'Create "Inline Subcategory" under:'+ find("button[data-parent-id='#{parent.id}']").click++ assert_selector "[data-category-select-target='selectionContainer']", text: "Inline Subcategory"+ end+ end++ assert_equal parent, Category.find_by!(name: "Inline Subcategory").parent+ end++ test "can create a subcategory from the transaction details panel" do+ parent = categories(:food_and_drink)+ transaction = transactions(:one)+ entry = transaction.entry++ visit transactions_url++ page.execute_script <<~JS+ const frame = document.querySelector("turbo-frame#drawer")+ frame.src = "#{transaction_url(entry)}"+ JS++ within "turbo-frame#drawer", visible: :all do+ within "[data-controller='category-select']" do+ find("button", match: :first).click+ fill_in "Search categories", with: "Drawer Subcategory"+ click_button "Add as a subcategory…"+ find("button[data-parent-id='#{parent.id}']").click+ end+ end++ assert_selector "##{ActionView::RecordIdentifier.dom_id(entry)}", text: "Drawer Subcategory"++ category = Category.find_by!(name: "Drawer Subcategory")+ assert_equal parent, category.parent+ assert_equal category.id, transaction.reload.category_id+ end++ test "back from the parent picker returns to the category list" do+ visit new_transaction_url+ find("[data-controller='category-select'] button").click++ within "[data-controller='category-select']" do+ fill_in "Search categories", with: "Changed My Mind"+ click_button "Add as a subcategory…"+ assert_selector "[data-category-select-target='parentPicker']", visible: true++ click_button "Back"+ assert_no_selector "[data-category-select-target='parentPicker']", visible: true+ assert_button 'Create "Changed My Mind"'+ end+ end++ test "the parent picker keeps keyboard focus, and Escape steps back out" do+ visit new_transaction_url+ find("[data-controller='category-select'] button").click++ within "[data-controller='category-select']" do+ fill_in "Search categories", with: "Keyboard Category"+ click_button "Add as a subcategory…"+ end++ assert_equal "parentOption", active_element_attribute("data-category-select-target")++ send_escape+ assert_no_selector "[data-category-select-target='parentPicker']", visible: true+ assert_equal "search", active_element_attribute("data-category-select-target")++ send_escape+ assert_no_selector "[data-category-select-target='menu']", visible: true+ assert_equal "button", active_element_attribute("data-category-select-target")+ end++ test "Enter in the search while the parent picker is open doesn't create a top-level category" do+ visit new_transaction_url+ find("[data-controller='category-select'] button").click++ within "[data-controller='category-select']" do+ fill_in "Search categories", with: "Not Top Level"+ click_button "Add as a subcategory…"+ end++ assert_no_difference "Category.count" do+ page.execute_script("document.querySelector(\"[data-category-select-target='search']\").focus()")+ find("[data-category-select-target='search']").send_keys(:enter)+ assert_selector "[data-category-select-target='parentPicker']", visible: true+ assert_equal "parentOption", active_element_attribute("data-category-select-target")+ end+ end++ test "a new subcategory is listed under its parent straight away" do+ parent = categories(:food_and_drink)+ visit new_transaction_url+ find("[data-controller='category-select'] button").click++ within "[data-controller='category-select']" do+ fill_in "Search categories", with: "Grouped Subcategory"+ click_button "Add as a subcategory…"+ find("button[data-parent-id='#{parent.id}']").click+ # The rows stay disabled until the POST returns; give a slow request time.+ assert_selector "[data-category-select-target='selectionContainer']", text: "Grouped Subcategory", wait: 10+ end++ created = Category.find_by!(name: "Grouped Subcategory")+ group_ids = [ parent.id, *parent.subcategories.where.not(id: created.id).pluck(:id) ].map(&:to_s)+ previous_id = page.evaluate_script(<<~JS)+ document.querySelector("[data-category-select-target='option'][data-category-id='#{created.id}']")+ .previousElementSibling.dataset.categoryId+ JS+ assert_includes group_ids, previous_id+ end++ test "a failed create from the parent picker returns to the list with the error" do+ parent = categories(:food_and_drink)+ visit new_transaction_url+ find("[data-controller='category-select'] button").click++ within "[data-controller='category-select']" do+ fill_in "Search categories", with: "Late Duplicate"+ click_button "Add as a subcategory…"+ end++ # Someone else takes the name after the page loaded, so the server rejects it.+ Category.create!(family: parent.family, name: "Late Duplicate", color: "#e99537")++ within "[data-controller='category-select']" do+ find("button[data-parent-id='#{parent.id}']").click++ assert_selector "[role='alert']", text: "taken", wait: 10+ assert_no_selector "[data-category-select-target='parentPicker']", visible: true+ end+ end++ test "a top-level category created inline is offered as a parent without reloading" do+ visit new_transaction_url+ find("[data-controller='category-select'] button").click++ within "[data-controller='category-select']" do+ fill_in "Search categories", with: "Fresh Parent"+ click_button 'Create "Fresh Parent"'+ assert_selector "[data-category-select-target='selectionContainer']", text: "Fresh Parent"+ end++ fresh_parent = Category.find_by!(name: "Fresh Parent")+ find("[data-controller='category-select'] button").click++ within "[data-controller='category-select']" do+ fill_in "Search categories", with: "Fresh Child"+ click_button "Add as a subcategory…"+ find("button[data-parent-id='#{fresh_parent.id}']").click+ assert_selector "[data-category-select-target='selectionContainer']", text: "Fresh Child"+ end++ assert_equal fresh_parent, Category.find_by!(name: "Fresh Child").parent+ end++ private+ def active_element_attribute(name)+ page.evaluate_script("document.activeElement.getAttribute('#{name}')")+ end++ def send_escape+ page.driver.browser.action.send_keys(:escape).perform+ endend