Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Product variants form - add autocomplete for option values (#12537)
Łukasz Adamczykaaceb06a3b1c
diff --git a/admin/app/controllers/spree/admin/option_values_controller.rb b/admin/app/controllers/spree/admin/option_values_controller.rbindex 1b9d1cb3af..d535ab723e 100644--- a/admin/app/controllers/spree/admin/option_values_controller.rb+++ b/admin/app/controllers/spree/admin/option_values_controller.rb@@ -3,6 +3,10 @@ module Spreeclass OptionValuesController < ResourceControllerbelongs_to 'spree/option_type', find_by: :id+ def select_options+ render json: @option_type.option_values.to_tom_select_json+ end+privatedef update_turbo_stream_enabled?diff --git a/admin/app/controllers/spree/admin/products_controller.rb b/admin/app/controllers/spree/admin/products_controller.rbindex 0a400ce126..de49bf492c 100644--- a/admin/app/controllers/spree/admin/products_controller.rb+++ b/admin/app/controllers/spree/admin/products_controller.rb@@ -167,20 +167,25 @@ module Spreereturn unless @product.has_variants?@product_options = {}+ @product_available_options = {}@product.option_values.joins(option_type: :product_option_types).+ includes(option_type: :option_values).merge(@product.product_option_types).reorder('spree_product_option_types.position').uniq.group_by(&:option_type).each_with_index do |option, index|- option_type, option_values = option- @product_options[option_type.id.to_s] = {- name: option_type.presentation,- position: index + 1,- values: option_values.pluck(:presentation).uniq- }- end+ option_type, option_values = option++ @product_options[option_type.id.to_s] = {+ name: option_type.presentation,+ position: index + 1,+ values: option_values.pluck(:presentation).uniq+ }++ @product_available_options[option_type.id.to_s] = option_type.option_values.to_tom_select_json+ end@product_stock = {}@product.stock_items.includes(:variant).each do |stock_item|diff --git a/admin/app/helpers/tom_select_helper.rb b/admin/app/helpers/tom_select_helper.rbindex c8b6daa154..1ec13b67b1 100644--- a/admin/app/helpers/tom_select_helper.rb+++ b/admin/app/helpers/tom_select_helper.rb@@ -4,9 +4,9 @@ module TomSelectHelper## @param [String] name# @param [Hash] options- def tom_select_tag(name, options = { multiple: false, url: nil, active_option: nil, class: 'w-100', create: false, select_data: {} })+ def tom_select_tag(name, options = { template: false, multiple: false, url: nil, active_option: nil, class: 'w-100', create: false, select_data: {} })stimulus_options = options[:data] || {}- stimulus_options[:controller] = 'select'+ stimulus_options[:controller] = 'select' unless options[:template].present?stimulus_options['select-active-option-value'] = options[:active_option].as_json if options[:active_option]stimulus_options['select-empty-option-value'] = options[:empty_option] if options[:empty_option]stimulus_options['select-options-value'] = options[:options].as_json if options[:options]diff --git a/admin/app/javascript/spree/admin/application.js b/admin/app/javascript/spree/admin/application.jsindex 8e7301cf46..fa2f956248 100644--- a/admin/app/javascript/spree/admin/application.js+++ b/admin/app/javascript/spree/admin/application.js@@ -58,6 +58,7 @@ import FiltersController from 'spree/admin/controllers/filters_controller'import FontPickerController from 'spree/admin/controllers/font_picker_controller'import MediaFormController from 'spree/admin/controllers/media_form_controller'import MultiInputController from 'spree/admin/controllers/multi_input_controller'+import MultiTomSelectController from 'spree/admin/controllers/multi_tom_select_controller'import OrderBillingAddressController from 'spree/admin/controllers/order_billing_address_controller'import PageBuilderController from 'spree/admin/controllers/page_builder_controller'import PasswordToggle from 'spree/admin/controllers/password_toggle_controller'@@ -103,6 +104,7 @@ application.register('filters', FiltersController)application.register('font-picker', FontPickerController)application.register('media-form', MediaFormController)application.register('multi-input', MultiInputController)+application.register('multi-tom-select', MultiTomSelectController)application.register('nested-form', RailsNestedForm)application.register('notification', Notification)application.register('order-billing-address', OrderBillingAddressController)diff --git a/admin/app/javascript/spree/admin/controllers/multi_tom_select_controller.js b/admin/app/javascript/spree/admin/controllers/multi_tom_select_controller.jsnew file mode 100644index 0000000000..5f4688a771--- /dev/null+++ b/admin/app/javascript/spree/admin/controllers/multi_tom_select_controller.js@@ -0,0 +1,80 @@+import { Controller } from '@hotwired/stimulus'++export default class extends Controller {+ static targets = ['selectTemplate', 'select']++ static values = {+ preloadedValues: { type: Array, default: [] },+ preloadedOptions: { type: Array, default: [] }+ }++ connect() {+ this.element.reset = this.reset.bind(this)+ this.element.values = this.values.bind(this)+ this.element.setValues = this.setValues.bind(this)++ this.setValues(this.preloadedValuesValue)+ }++ reset(addBlankSelect = true) {+ this.selectTargets.forEach((container) => container.remove())++ if (addBlankSelect)+ this.addSelect()+ }++ values() {+ return this.selectTargets+ .map((selectTarget) => selectTarget.querySelector('select'))+ .map((select) => select.options[select.selectedIndex].text)+ .filter((text) => text?.length > 0)+ }++ setValues() {+ this.reset(false)+ this.preloadedValuesValue.forEach((value) => this.addSelect(value))++ if (this.selectTargets.length === this.preloadedValuesValue.length)+ this.addSelect()+ }++ handleSelect(event) {+ const ts = event.target.tomselect++ if (ts && ts.getValue().length > 0 && (this.lastSelect === event.target || this.selectTargets.length === 1)) {+ this.addSelect()+ } else if (ts && ts.getValue().length === 0 && this.selectTargets.length > 1) {+ const inputContainer = event.target.closest('[data-multi-tom-select-target="select"]')+ this.removeSelect(inputContainer)+ }+ }++ removeSelect(container) {+ if (this.selectTargets.length > 1) {+ const select = container.querySelector('select')+ select.tomselect?.destroy()+ container.remove()+ }+ }++ addSelect(value = null) {+ const newTomSelectTag = this.selectTemplateTarget.cloneNode(true)++ newTomSelectTag.setAttribute('data-select-options-value', JSON.stringify(this.preloadedOptionsValue))++ if (value)+ newTomSelectTag.setAttribute('data-select-active-option-value', value.id)++ newTomSelectTag.setAttribute('data-multi-tom-select-target', 'select')+ newTomSelectTag.setAttribute('data-controller', 'select')++ if (this.hasSelectTargets) {+ const lastSelect = this.selectTargets[this.selectTargets.length - 1]+ lastSelect.insertAdjacentElement('afterend', newTomSelectTag)+ } else {+ this.element.insertAdjacentElement('beforeend', newTomSelectTag)+ }++ this.lastSelect = newTomSelectTag.querySelector('select')+ }+}diff --git a/admin/app/javascript/spree/admin/controllers/variants_form_controller.js b/admin/app/javascript/spree/admin/controllers/variants_form_controller.jsindex 15d6f06979..cb36480f7e 100644--- a/admin/app/javascript/spree/admin/controllers/variants_form_controller.js+++ b/admin/app/javascript/spree/admin/controllers/variants_form_controller.js@@ -1,5 +1,6 @@import CheckboxSelectAll from 'stimulus-checkbox-select-all'import { Sortable } from 'sortablejs'+import { get } from '@rails/request.js'export default class extends CheckboxSelectAll {static targets = [@@ -8,7 +9,8 @@ export default class extends CheckboxSelectAll {'optionsContainer','optionFormTemplate','newOptionForm',- 'newOptionValuesInput',+ 'newOptionValuesSelectContainer',+ 'newOptionValuesSelect','newOptionNameInput','newOptionButton','newOptionButtonLabel',@@ -25,6 +27,7 @@ export default class extends CheckboxSelectAll {static values = {productId: String,options: Object,+ availableOptions: Object,variants: Array,stock: Object,prices: Object,@@ -32,7 +35,8 @@ export default class extends CheckboxSelectAll {currencies: Array,variantIds: Object,currentStockLocationId: String,- stockLocations: Array+ stockLocations: Array,+ optionValuesSelectOptions: Array}connect() {@@ -51,6 +55,7 @@ export default class extends CheckboxSelectAll {this.element.closest('[data-controller*="product-form"]'),'product-form')+ this.currentOptionValues = {}// Set ignoredVariants to all the variants that are not on the serverconst existingVariantsOnServer = Object.keys(this.variantIdsValue)@@ -239,7 +244,7 @@ export default class extends CheckboxSelectAll {label.textContent = label.dataset.noOptionsText}}- this.refreshTomSelect()+ this.refreshOptionNameSelect()this.variantsValue = this.generateVariants(value)// We want to clear the ignoredVariants when the options change@@ -699,10 +704,45 @@ export default class extends CheckboxSelectAll {}}- handleNewOption(event) {+ // After selecting an option name (eg. "Color"), we fetch the option values for that option name and update the tom select options+ async handleSelectedOptionName(event) {+ const targetInput = event.target+ this.lastOptionNameId = targetInput.value++ if (this.lastOptionNameId) {+ const response = await get(`/admin/option_types/${this.lastOptionNameId}/option_values/select_options`)++ if (response.ok) {+ this.currentOptionValues[this.lastOptionNameId] = await response.json++ const optionsCreatorContainer = targetInput.closest('.options-creator__option')+ const newOptionValuesSelects = optionsCreatorContainer.querySelectorAll('[data-variants-form-target="newOptionValuesSelect"]')++ newOptionValuesSelects.forEach((select) => this.replaceSelectOptions(select))+ }+ }+ }++ replaceSelectOptions(select) {+ const tomSelect = select.tomselect++ if (tomSelect) {+ tomSelect.clear()+ tomSelect.clearOptions()+ tomSelect.addOptions(this.currentOptionValues[this.lastOptionNameId])+ }+ }++ newOptionValuesSelectTargetConnected(select) {+ if (this.lastOptionNameId)+ this.replaceSelectOptions(select)+ }++ handleNewOption(_event) {const newOptionName = this.newOptionNameInputTarget.options[this.newOptionNameInputTarget.selectedIndex].textconst newOptionId = String(this.newOptionNameInputTarget.value)- const newOptionValues = this.newOptionValuesInputTarget.values()+ const newOptionValues = this.newOptionValuesSelectContainerTarget.values()+if (!newOptionName.length ||this.optionsValue[newOptionId] ||@@ -722,7 +762,7 @@ export default class extends CheckboxSelectAll {hideNewOptionForm() {this.newOptionNameInputTarget.tomselect.clear()- this.newOptionValuesInputTarget.reset()+ this.newOptionValuesSelectContainerTarget.reset()this.newOptionFormTarget.classList.add('d-none')@@ -736,10 +776,21 @@ export default class extends CheckboxSelectAll {const option = this.optionsContainerTarget.querySelector(`#option-${optionId}`)const { name, values } = this.optionsValue[optionId]+ const availableOptions = this.availableOptionsValue[optionId] || this.currentOptionValues[optionId]?.map((option) => ({ id: option.id, name: option.name }))- const form = this.optionFormTemplate(name, values, optionId)+ const form = this.optionFormTemplate(name, values, optionId, availableOptions)option.replaceWith(form)++ // Disable the option name in the select tag that is already picked+ const optionContainer = this.optionsContainerTarget.querySelector(`#option-${optionId}`)+ const optionNameSelect = optionContainer.querySelector('select[name="option_name"]')+ const options = Array.from(optionNameSelect.options)++ const alreadySelectedOptions = Object.keys(this.optionsValue).filter((k) => this.optionsValue[k] !== null)+ const optionsToDisable = options.filter((option) => option.text != name && alreadySelectedOptions.includes(option.value))++ optionsToDisable.forEach((option) => option.disabled = true)}saveOption(event) {@@ -760,7 +811,7 @@ export default class extends CheckboxSelectAll {let position = this.optionsValue[optionId].positionlet newOptionsPositions = {}- const optionValues = option.querySelector('[data-slot="optionValuesInput"]').values()+ const optionValues = option.querySelector('[data-slot="optionValuesSelectContainer"]').values()if (optionValues.length === 0) {return@@ -796,6 +847,7 @@ export default class extends CheckboxSelectAll {event.preventDefault()this.newOptionFormTarget.classList.remove('d-none')this.newOptionButtonTarget.classList.add('d-none')+ this.refreshOptionNameSelect()}optionTemplate(name, values, id, color = false) {@@ -830,7 +882,7 @@ export default class extends CheckboxSelectAll {this.refreshParentInputs()}- optionFormTemplate(optionName, optionValues, id) {+ optionFormTemplate(optionName, optionValues, id, availableOptions) {const template = this.optionFormTemplateTarget.content.cloneNode(true)const optionNameSelect = template.querySelector('select[name="option_name"]')@@ -852,8 +904,16 @@ export default class extends CheckboxSelectAll {optionNameSelect.appendChild(newOption)}- const optionValuesInput = template.querySelector('[data-slot="optionValuesInput"]')- optionValuesInput.dataset.multiInputPreloadedValuesValue = JSON.stringify(optionValues)+ const optionValuesSelectContainer = template.querySelector('[data-slot="optionValuesSelectContainer"]')+ const tomSelectOptionValues = optionValues.map((optionValue) => {+ return {+ id: availableOptions.find((availableOption) => availableOption.name === optionValue)?.id,+ name: optionValue+ }+ })++ optionValuesSelectContainer.setAttribute('data-multi-tom-select-preloaded-options-value', JSON.stringify(availableOptions))+ optionValuesSelectContainer.setAttribute('data-multi-tom-select-preloaded-values-value', JSON.stringify(tomSelectOptionValues))template.querySelectorAll('[data-variants-form-option-id-param]').forEach((el) => {el.dataset.variantsFormOptionIdParam = id@@ -880,24 +940,34 @@ export default class extends CheckboxSelectAll {return templates}- refreshTomSelect() {+ refreshOptionNameSelect() {const alreadySelectedOptions = Object.keys(this.optionsValue).filter((k) => this.optionsValue[k] !== null)Array.from(this.newOptionNameInputTarget.options).forEach((option) => {- const tomselectOption = this.newOptionNameInputTarget.tomselect?.getOption(option.value)+ const tomSelect = this.newOptionNameInputTarget.tomselect+ if (!tomSelect) return++ const tomselectOption = tomSelect.getOption(option.value)if (!tomselectOption) return+const alreadySelected = alreadySelectedOptions.includes(option.value)tomselectOption.ariaDisabled = alreadySelected+if (alreadySelected) {tomselectOption.removeAttribute('data-selectable')} else {tomselectOption.setAttribute('data-selectable', '')}+tomselectOption.disabled = alreadySelected})- this.newOptionNameInputTarget.tomselect?.sync()- this.newOptionNameInputTarget.tomselect?.refreshOptions()+ const optionNameTomSelect = this.newOptionNameInputTarget.tomselect++ if (optionNameTomSelect) {+ optionNameTomSelect.sync()+ optionNameTomSelect.refreshOptions(false)+ }}generateVariants(optionsValue) {diff --git a/admin/app/views/spree/admin/products/form/_variants.html.erb b/admin/app/views/spree/admin/products/form/_variants.html.erbindex 549d41511d..6650a21be8 100644--- a/admin/app/views/spree/admin/products/form/_variants.html.erb+++ b/admin/app/views/spree/admin/products/form/_variants.html.erb@@ -15,6 +15,7 @@data-variants-form-current-stock-location-id-value="<%= default_stock_location_for_product(@product).id %>"data-variants-form-stock-locations-value="<%= available_stock_locations_for_product(@product).ids.map(&:to_s).to_json %>"<% if @product_options.present? %> data-variants-form-options-value="<%= @product_options.to_json %>" <% end %>+ <% if @product_available_options.present? %> data-variants-form-available-options-value="<%= @product_available_options.to_json %>" <% end %><% if @product_stock.present? %> data-variants-form-stock-value="<%= @product_stock.to_json %>" <% end %><% if @product_prices.present? %> data-variants-form-prices-value="<%= @product_prices.to_json %>" <% end %><% if @product_variant_ids.present? %> data-variants-form-variant-ids-value="<%= @product_variant_ids.to_json %>" <% end %>@@ -51,7 +52,15 @@<div class="w-100"><div class="form-group"><label class="label" for="new_option_name"><%= Spree.t(:option_name) %></label>- <%= tom_select_tag :new_option_name, multiple: false, create: true, preloaded_options: option_types_for_select, include_blank: true, select_data: {variants_form_target: "newOptionNameInput"} %>+ <%= tom_select_tag :new_option_name,+ multiple: false,+ create: true,+ preloaded_options: option_types_for_select,+ include_blank: true,+ select_data: {+ variants_form_target: "newOptionNameInput",+ action: "variants-form#handleSelectedOptionName tomSelectInitialized->variants-form#refreshOptionNameSelect"+ } %><% if can?(:manage, Spree::OptionType) %><p class="form-text text-muted mt-2"><%= Spree.t('admin.products.variants.option_types_link', link: spree.admin_option_types_path).html_safe %>@@ -60,10 +69,31 @@</div><div class="form-group"><span class="label"><%= Spree.t(:option_values) %></span>- <div data-controller="multi-input" class="values-inputs" data-variants-form-target="newOptionValuesInput">- <div class="values-inputs__input" data-multi-input-target="input">- <input class="form-control" name="new_option_values[]" data-action="multi-input#handleInput keydown->multi-input#handleKeyDown keydown.enter->variants-form#handleNewOption:prevent">- </div>+ <div data-controller="multi-tom-select" class="values-inputs" data-variants-form-target="newOptionValuesSelectContainer">+ <%= tom_select_tag "new_option_values[]",+ template: true,+ multiple: false,+ create: true,+ include_blank: true,+ data: {+ multi_tom_select_target: "selectTemplate"+ },+ select_data: {+ variants_form_target: "newOptionValuesSelect",+ action: "multi-tom-select#handleSelect keydown.enter->variants-form#handleNewOption:prevent"+ } %>++ <%= tom_select_tag "new_option_values[]",+ multiple: false,+ create: true,+ include_blank: true,+ data: {+ multi_tom_select_target: "select"+ },+ select_data: {+ variants_form_target: "newOptionValuesSelect",+ action: "multi-tom-select#handleSelect keydown.enter->variants-form#handleNewOption:prevent"+ } %></div></div><div class="d-flex justify-content-between">diff --git a/admin/app/views/spree/admin/products/form/variants/_option_template.html.erb b/admin/app/views/spree/admin/products/form/variants/_option_template.html.erbindex 11b1835bde..a90899afef 100644--- a/admin/app/views/spree/admin/products/form/variants/_option_template.html.erb+++ b/admin/app/views/spree/admin/products/form/variants/_option_template.html.erb@@ -24,14 +24,30 @@<div class="w-100"><div class="form-group"><label class="label" for="option_name"><%= Spree.t(:option_name) %></label>- <%= tom_select_tag :option_name, multiple: false, create: true, preloaded_options: option_types_for_select, include_blank: true %>+ <%= tom_select_tag :option_name,+ multiple: false,+ create: true,+ preloaded_options: option_types_for_select,+ include_blank: true,+ select_data: {+ action: "variants-form#handleSelectedOptionName tomSelectInitialized->variants-form#refreshOptionNameSelect"+ } %></div><div class="form-group"><span class="label"><%= Spree.t(:option_values) %></span>- <div data-controller="multi-input" class="values-inputs" data-slot="optionValuesInput">- <div class="values-inputs__input" data-multi-input-target="input">- <input class="form-control" data-variants-form-option-id-param="" name="new_option_values[]" data-action="multi-input#handleInput keydown->multi-input#handleKeyDown keydown.enter->variants-form#saveOption:prevent">- </div>+ <div data-controller="multi-tom-select" class="values-inputs" data-variants-form-target="newOptionValuesSelectContainer" data-slot="optionValuesSelectContainer">+ <%= tom_select_tag "new_option_values[]",+ template: true,+ multiple: false,+ create: true,+ include_blank: true,+ data: {+ multi_tom_select_target: "selectTemplate"+ },+ select_data: {+ variants_form_target: "newOptionValuesSelect",+ action: "multi-tom-select#handleSelect keydown.enter->variants-form#handleNewOption:prevent"+ } %></div></div><div class="d-flex justify-content-between">diff --git a/admin/config/routes.rb b/admin/config/routes.rbindex 35c5b72b4d..80e85fc753 100644--- a/admin/config/routes.rb+++ b/admin/config/routes.rb@@ -3,7 +3,11 @@ Spree::Core::Engine.add_routes do# product catalogresources :properties, except: :showresources :option_types, except: :show do- resources :option_values, only: [:update]+ resources :option_values, only: [:update] do+ collection do+ get :select_options+ end+ endendresources :products docollection dodiff --git a/core/app/models/spree/option_value.rb b/core/app/models/spree/option_value.rbindex e1428bc245..7a403fe539 100644--- a/core/app/models/spree/option_value.rb+++ b/core/app/models/spree/option_value.rb@@ -61,6 +61,15 @@ module Spreedelegate :name, :presentation, to: :option_type, prefix: true, allow_nil: true+ def self.to_tom_select_json+ all.pluck(:id, :presentation).map do |id, presentation|+ {+ id: id,+ name: presentation+ }+ end+ end+privatedef touch_all_variants