The personal finance app for everyone (by everyone)
Ruby
Add inline category creation to transaction form (#3088)
rottenit9930b721b36b
diff --git a/app/components/DS/category_select.html.erb b/app/components/DS/category_select.html.erbnew file mode 100644index 0000000000..41bb5d4ee8--- /dev/null+++ b/app/components/DS/category_select.html.erb@@ -0,0 +1,105 @@+<div class="relative"+ data-controller="category-select"+ data-category-select-create-url-value="<%= helpers.categories_path(format: :json) %>"+ data-category-select-default-color-value="<%= Category::COLORS.first %>"+ data-category-select-disabled-value="<%= disabled %>"+ 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-action="click@window->category-select#handleOutsideClick">++ <div class="form-field">+ <div class="form-field__body">+ <%= form.label :category_id,+ helpers.t("transactions.form.category"),+ class: "form-field__label" %>++ <button type="button"+ id="<%= field_id %>"+ class="form-field__input min-h-7 flex items-center gap-2 pr-8"+ data-category-select-target="button"+ data-action="click->category-select#toggle"+ aria-haspopup="listbox"+ aria-expanded="false"+ aria-controls="<%= menu_id %>"+ <%= "disabled" if disabled %>>++ <span data-category-select-target="selectionContainer"+ class="text-secondary">+ <% selected = categories.find { |c| c.id.to_s == selected_id } %>++ <% if selected %>+ <%= render partial: "categories/badge",+ locals: { category: selected } %>+ <% else %>+ <%= helpers.t("transactions.form.category_prompt") %>+ <% end %>+ </span>+ </button>+ </div>+ </div>++ <input type="hidden"+ name="<%= field_name %>"+ value="<%= selected_id %>"+ data-category-select-target="hiddenInput"+ <%= "disabled" if disabled %>>++ <% 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">++ <%= render DS::SearchInput.new(+ variant: :embedded,+ placeholder: helpers.t("transactions.form.category_search_placeholder"),+ data: {+ category_select_target: "search",+ action: "input->category-select#filter keydown->category-select#handleSearchKeydown"+ }+ ) %>++ <div class="flex flex-col gap-1 max-h-64 overflow-auto mt-1"+ id="<%= menu_id %>"+ role="listbox">++ <% if blank_label.present? %>+ <button type="button"+ role="option"+ aria-selected="<%= selected_id.blank? %>"+ data-category-select-target="option"+ data-category-id=""+ data-category-name="<%= blank_label %>"+ data-category-display-label="<%= blank_label %>"+ data-action="click->category-select#selectCategory"+ class="flex items-center gap-2 w-full px-3 py-1.5 text-sm rounded-lg hover:bg-container-inset-hover <%= "bg-container-inset" if selected_id.blank? %>">+ <span class="check-icon w-4 <%= "invisible" unless selected_id.blank? %>">+ <%= helpers.icon("check") %>+ </span>++ <span><%= blank_label %></span>+ </button>+ <% end %>++ <% categories.each do |category| %>+ <%= render partial: "DS/category_select/option",+ locals: {+ category: category,+ selected: category.id.to_s == selected_id,+ view_helpers: helpers+ } %>+ <% end %>++ <button type="button"+ class="hidden text-primary text-sm cursor-pointer items-center gap-2 px-3 py-1.5 rounded-lg hover:bg-container-inset-hover"+ data-category-select-target="createForm"+ data-action="click->category-select#createCategory">+ <%= helpers.icon("plus") %>+ <span data-category-select-target="createLabel"></span>+ </button>++ <p class="hidden px-3 py-1 text-xs text-destructive"+ data-category-select-target="createError"></p>+ </div>+ </div>+ <% end %>+</div>diff --git a/app/components/DS/category_select.rb b/app/components/DS/category_select.rbnew file mode 100644index 0000000000..f09efa4fa0--- /dev/null+++ b/app/components/DS/category_select.rb@@ -0,0 +1,31 @@+class DS::CategorySelect < DesignSystemComponent+ attr_reader :form, :categories, :selected_id, :disabled, :auto_submit, :blank_label++ def initialize(+ form:,+ categories:,+ selected_id: nil,+ disabled: false,+ auto_submit: false,+ blank_label: nil+ )+ @form = form+ @categories = categories+ @selected_id = selected_id&.to_s+ @disabled = disabled+ @auto_submit = auto_submit+ @blank_label = blank_label+ end++ def field_name+ "#{form.object_name}[category_id]"+ end++ def field_id+ form.field_id(:category_id)+ end++ def menu_id+ "#{field_id}_menu"+ end+enddiff --git a/app/controllers/categories_controller.rb b/app/controllers/categories_controller.rbindex 90cb3bd9a7..a035bcd439 100644--- a/app/controllers/categories_controller.rb+++ b/app/controllers/categories_controller.rb@@ -34,16 +34,35 @@ class CategoriesController < ApplicationController@transaction.record_category_usage!end- flash[:notice] = t(".success")-redirect_target_url = request.referer || categories_path+respond_to do |format|format.html { redirect_back_or_to categories_path, notice: t(".success") }- format.turbo_stream { render turbo_stream: turbo_stream.action(:redirect, redirect_target_url) }++ format.turbo_stream do+ flash[:notice] = t(".success")+ render turbo_stream: turbo_stream.action(:redirect, redirect_target_url)+ end++ format.json { render json: category_json(@category), status: :created }endelse- set_categories- render :new, status: :unprocessable_entity+ respond_to do |format|+ format.html do+ set_categories+ render :new, status: :unprocessable_entity+ end++ format.turbo_stream do+ set_categories+ render :new, formats: [ :html ], status: :unprocessable_entity+ end++ format.json do+ render json: { errors: @category.errors.full_messages },+ status: :unprocessable_entity+ end+ endendend@@ -131,6 +150,20 @@ class CategoriesController < ApplicationControllerparams.permit(:target_id, source_ids: [])end+ def category_json(category)+ category.as_json(only: %i[id name color]).merge(+ html: render_to_string(+ partial: "DS/category_select/option",+ formats: [ :html ],+ locals: {+ category: category,+ selected: true,+ view_helpers: helpers+ }+ )+ )+ end+def record_error_message(error)record = error.respond_to?(:record) ? error.record : nilrecord&.errors&.full_messages&.to_sentence.presence || error.messagediff --git a/app/javascript/controllers/category_select_controller.js b/app/javascript/controllers/category_select_controller.jsnew file mode 100644index 0000000000..90e80bc286--- /dev/null+++ b/app/javascript/controllers/category_select_controller.js@@ -0,0 +1,228 @@+import { Controller } from "@hotwired/stimulus";++export default class extends Controller {+ static targets = [+ "button",+ "menu",+ "search",+ "option",+ "selectionContainer",+ "hiddenInput",+ "createForm",+ "createLabel",+ "createError",+ ];++ static values = {+ createUrl: String,+ defaultColor: String,+ disabled: Boolean,+ autoSubmit: Boolean,+ createLabel: String,+ createErrorMessage: String,+ };++ connect() {+ this.creating = false;+ this.isOpen = false;+ }++ toggle(event) {+ event.preventDefault();+ if (this.disabledValue) return;++ this.isOpen ? this.close() : this.open();+ }++ open() {+ this.isOpen = true;+ this.buttonTarget.setAttribute("aria-expanded", "true");+ this.menuTarget.classList.remove("hidden");++ this.searchTarget.value = "";+ this.filter();++ requestAnimationFrame(() => this.searchTarget.focus());+ }++ close() {+ this.isOpen = false;+ this.buttonTarget.setAttribute("aria-expanded", "false");+ this.menuTarget.classList.add("hidden");+ }++ filter() {+ this.clearCreateError();++ const rawQuery = this.searchTarget.value.trim();+ const query = rawQuery.toLowerCase();++ let exactMatch = false;++ this.optionTargets.forEach((option) => {+ const name = option.dataset.categoryName.toLowerCase();+ const matches = name.includes(query);++ option.classList.toggle("hidden", !matches);++ if (name === query) exactMatch = true;+ });++ const canCreate = rawQuery.length > 0 && !exactMatch;++ this.createFormTarget.classList.toggle("hidden", !canCreate);+ this.createFormTarget.classList.toggle("flex", canCreate);++ this.createLabelTarget.textContent =+ this.createLabelValue.replace("__CATEGORY_NAME__", rawQuery);+ }++ handleSearchKeydown(event) {+ if (event.key === "Escape") {+ event.preventDefault();+ this.close();+ this.buttonTarget.focus();+ return;+ }++ if (+ event.key === "Enter" &&+ !this.createFormTarget.classList.contains("hidden") &&+ !this.creating+ ) {+ event.preventDefault();+ this.createCategory();+ }+ }++ selectCategory(event) {+ event.preventDefault();++ const option = event.currentTarget;++ this.selectOption(option);+ this.close();+ this.submitForm();+ }++ selectOption(option) {+ const id = option.dataset.categoryId;++ this.optionTargets.forEach((candidate) => {+ const selected = candidate === option;++ candidate.setAttribute(+ "aria-selected",+ selected ? "true" : "false",+ );++ candidate.classList.toggle("bg-container-inset", selected);++ const checkIcon = candidate.querySelector(".check-icon");+ if (checkIcon) checkIcon.classList.toggle("invisible", !selected);+ });++ this.hiddenInputTarget.value = id;++ const badge = option.querySelector("[data-category-select-badge]");++ this.selectionContainerTarget.innerHTML = "";++ if (badge) {+ this.selectionContainerTarget.appendChild(badge.cloneNode(true));+ } else {+ this.selectionContainerTarget.textContent =+ option.dataset.categoryDisplayLabel;+ }+ }++ async createCategory() {+ if (this.creating) return;++ const name = this.searchTarget.value.trim();+ if (!name) return;++ this.creating = true;+ this.createFormTarget.disabled = true;+ this.clearCreateError();++ try {+ const response = await fetch(this.createUrlValue, {+ method: "POST",+ headers: {+ Accept: "application/json",+ "Content-Type": "application/json",+ "X-CSRF-Token": this.csrfToken,+ },+ body: JSON.stringify({+ category: {+ name,+ color: this.defaultColorValue,+ },+ }),+ });++ const category = await response.json();++ if (!response.ok) {+ this.showCreateError(+ category.errors?.join(", ") || category.error,+ );+ return;+ }++ this.createFormTarget.insertAdjacentHTML(+ "beforebegin",+ category.html,+ );++ const newOption = this.optionTargets.find(+ (option) =>+ option.dataset.categoryId === String(category.id),+ );++ if (newOption) this.selectOption(newOption);++ this.searchTarget.value = "";+ this.filter();+ this.close();+ this.submitForm();+ } catch {+ this.showCreateError();+ } finally {+ this.creating = false;+ this.createFormTarget.disabled = false;+ }+ }++ async submitForm() {+ if (!this.autoSubmitValue) return;++ const form = this.element.closest("form");+ if (form) form.requestSubmit();+ }++ handleOutsideClick(event) {+ if (this.isOpen && !this.element.contains(event.target)) {+ this.close();+ }+ }++ clearCreateError() {+ this.createErrorTarget.textContent = "";+ this.createErrorTarget.classList.add("hidden");+ }++ showCreateError(message) {+ this.createErrorTarget.textContent =+ message || this.createErrorMessageValue;++ this.createErrorTarget.classList.remove("hidden");+ }++ get csrfToken() {+ return document+ .querySelector('meta[name="csrf-token"]')+ ?.getAttribute("content");+ }+}diff --git a/app/views/DS/category_select/_option.html.erb b/app/views/DS/category_select/_option.html.erbnew file mode 100644index 0000000000..763ad6a300--- /dev/null+++ b/app/views/DS/category_select/_option.html.erb@@ -0,0 +1,23 @@+<%# locals: (category:, selected:, view_helpers:) %>++<button type="button"+ role="option"+ aria-selected="<%= selected %>"+ data-category-select-target="option"+ data-category-id="<%= category.id %>"+ data-category-name="<%= category.name %>"+ data-category-display-label="<%= category.name %>"+ data-action="click->category-select#selectCategory"+ class="flex items-center gap-2 w-full px-3 py-1.5 text-sm rounded-lg hover:bg-container-inset-hover <%= "bg-container-inset" if selected %>">++ <span class="check-icon w-4 <%= "invisible" unless selected %>">+ <%= view_helpers.icon("check") %>+ </span>++ <span data-category-select-badge>+ <%= view_helpers.render partial: "categories/badge",+ formats: [ :html ],+ locals: { category: category } %>++ </span>+</button>diff --git a/app/views/transactions/_form.html.erb b/app/views/transactions/_form.html.erbindex acf69714fe..dd38d09d44 100644--- a/app/views/transactions/_form.html.erb+++ b/app/views/transactions/_form.html.erb@@ -29,7 +29,12 @@currency_data: { transaction_form_target: "currency", action: "change->transaction-form#onCurrencyChange" } %><%= f.fields_for :entryable do |ef| %>- <%= ef.collection_select :category_id, categories, :id, :name, { prompt: t(".category_prompt"), label: t(".category"), variant: :badge, searchable: true } %>+ <%= render DS::CategorySelect.new(+ form: ef,+ categories: categories,+ selected_id: ef.object.category_id,+ blank_label: t(".category_prompt")+ ) %><% end %><%= f.date_field :date,diff --git a/app/views/transactions/show.html.erb b/app/views/transactions/show.html.erbindex 01ce13855d..77a00aa5f9 100644--- a/app/views/transactions/show.html.erb+++ b/app/views/transactions/show.html.erb@@ -83,13 +83,14 @@disable_currency: @entry.linked? || split_locked || edit_locked %></div><%= f.fields_for :entryable do |ef| %>- <%= ef.collection_select :category_id,- Current.family.categories.alphabetically,- :id, :name,- { label: t(".category_label"),- class: "text-subdued", include_blank: t(".uncategorized"),- variant: :badge, searchable: true, disabled: @entry.split_child? || annotate_locked },- "data-auto-submit-form-target": "auto" %>+ <%= render DS::CategorySelect.new(+ form: ef,+ categories: Current.family.categories.alphabetically,+ selected_id: ef.object.category_id,+ disabled: @entry.split_child? || annotate_locked,+ auto_submit: true,+ blank_label: t(".uncategorized")+ ) %><% end %><% end %><% end %>diff --git a/config/locales/views/transactions/en.yml b/config/locales/views/transactions/en.ymlindex 147a601d03..6f4162f0dc 100644--- a/config/locales/views/transactions/en.yml+++ b/config/locales/views/transactions/en.yml@@ -32,6 +32,9 @@ en:category: Categorycategory_label: Categorycategory_prompt: Select a Category+ category_search_placeholder: Search categories+ create_category: 'Create "%{name}"'+ create_category_error: Could not create categorydate: Datedescription: Descriptiondescription_placeholder: Describe transactiondiff --git a/test/controllers/categories_controller_test.rb b/test/controllers/categories_controller_test.rbindex 54bd9262cc..7b75635980 100644--- a/test/controllers/categories_controller_test.rb+++ b/test/controllers/categories_controller_test.rb@@ -83,6 +83,42 @@ class CategoriesControllerTest < ActionDispatch::IntegrationTestassert_response :unprocessable_entityend+ test "create as json returns rendered category option" do+ color = Category::COLORS.sample++ assert_difference "Category.count", +1 do+ post categories_url(format: :json), params: {+ category: {+ name: "JSON Category",+ color: color } }+ end++ assert_response :created++ response_json = JSON.parse(response.body)+ new_category = Category.find(response_json.fetch("id"))++ assert_equal "JSON Category", response_json.fetch("name")+ assert_equal color, response_json.fetch("color")+ assert_equal "JSON Category", new_category.name+ assert_includes response_json.fetch("html"), "JSON Category"+ assert_includes response_json.fetch("html"), new_category.id+ end++ test "create as json returns errors for invalid category" do+ assert_no_difference "Category.count" do+ post categories_url(format: :json), params: {+ category: {+ name: categories(:food_and_drink).name,+ color: Category::COLORS.sample } }+ end++ assert_response :unprocessable_entity++ response_json = JSON.parse(response.body)+ assert response_json.fetch("errors").any?+ end+test "create and assign to transaction" docolor = Category::COLORS.samplediff --git a/test/system/transaction_category_select_test.rb b/test/system/transaction_category_select_test.rbnew file mode 100644index 0000000000..c219cdbec5--- /dev/null+++ b/test/system/transaction_category_select_test.rb@@ -0,0 +1,55 @@+require "application_system_test_case"++class TransactionCategorySelectTest < ApplicationSystemTestCase+ setup do+ sign_in @user = users(:family_admin)+ end++ test "can create a category from the transaction form" do+ 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 Test Category"++ assert_text 'Create "Inline Test Category"'+ click_button 'Create "Inline Test Category"'++ assert_text "Inline Test Category"+ end+ end++ assert Category.exists?(name: "Inline Test Category")+ end++ test "can clear a category from an existing transaction" do+ transaction = transactions(:one)+ transaction.update!(category: categories(:food_and_drink))+ 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+ assert_selector "[data-controller='category-select']"++ within "[data-controller='category-select']" do+ find("button", match: :first).click+ click_button "(uncategorized)"+ end+ end++ assert_selector(+ "##{ActionView::RecordIdentifier.dom_id(entry)}",+ text: "Uncategorized"+ )++ assert_nil transaction.reload.category_id+ end+end