Skip to content

armgit / spree

Public Imported from GitHub
0

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.

Simplify Table/BulkActions code

Damian Legawiec2ec03a256769
diff --git a/admin/app/helpers/spree/admin/table_helper.rb b/admin/app/helpers/spree/admin/table_helper.rb
index 9343fd3486..3938539685 100644
--- a/admin/app/helpers/spree/admin/table_helper.rb
+++ b/admin/app/helpers/spree/admin/table_helper.rb
@@ -66,18 +66,20 @@ module Spree
end
end
+ # Render placeholder for empty column values
+ # @return [String]
+ def empty_column_placeholder
+ content_tag(:span, '-', class: 'text-gray-400')
+ end
+
# Render money column
# @param value [Object] the value (Spree::Money or numeric)
# @param column [Spree::Admin::Table::Column] column definition
# @return [String]
def render_money_column(value, column)
- return content_tag(:span, '-', class: 'text-gray-400') if value.blank?
+ return empty_column_placeholder if value.blank?
- if value.respond_to?(:display_amount)
- value.display_amount
- else
- Spree::Money.new(value, currency: current_currency).to_html
- end
+ value.respond_to?(:display_amount) ? value.display_amount : Spree::Money.new(value, currency: current_currency).to_html
end
# Render date column
@@ -85,13 +87,7 @@ module Spree
# @param column [Spree::Admin::Table::Column] column definition
# @return [String]
def render_date_column(value, column)
- return content_tag(:span, '-', class: 'text-gray-400') if value.blank?
-
- if column.format.present? && respond_to?(column.format)
- send(column.format, value)
- else
- spree_date(value)
- end
+ render_temporal_column(value, column, :spree_date)
end
# Render datetime column
@@ -99,33 +95,37 @@ module Spree
# @param column [Spree::Admin::Table::Column] column definition
# @return [String]
def render_datetime_column(value, column)
- return content_tag(:span, '-', class: 'text-gray-400') if value.blank?
+ render_temporal_column(value, column, :spree_time_ago)
+ end
- if column.format.present? && respond_to?(column.format)
- send(column.format, value)
- else
- spree_time_ago(value)
- end
+ # Render temporal (date/datetime) column with optional format
+ # @param value [Object] the value
+ # @param column [Spree::Admin::Table::Column] column definition
+ # @param default_formatter [Symbol] default formatter method
+ # @return [String]
+ def render_temporal_column(value, column, default_formatter)
+ return empty_column_placeholder if value.blank?
+
+ formatter = column.format.present? && respond_to?(column.format) ? column.format : default_formatter
+ send(formatter, value)
end
+ STATUS_BADGE_CLASSES = {
+ 'active' => 'badge-active', 'complete' => 'badge-active', 'completed' => 'badge-active',
+ 'paid' => 'badge-active', 'shipped' => 'badge-active', 'available' => 'badge-active',
+ 'draft' => 'badge-warning', 'pending' => 'badge-warning', 'processing' => 'badge-warning', 'ready' => 'badge-warning',
+ 'archived' => 'badge-inactive', 'canceled' => 'badge-inactive', 'cancelled' => 'badge-inactive',
+ 'failed' => 'badge-inactive', 'void' => 'badge-inactive', 'inactive' => 'badge-inactive'
+ }.freeze
+
# Render status column as badge
# @param value [Object] the value
# @param column [Spree::Admin::Table::Column] column definition
# @return [String]
def render_status_column(value, column)
- return content_tag(:span, '-', class: 'text-gray-400') if value.blank?
-
- css_class = case value.to_s
- when 'active', 'complete', 'completed', 'paid', 'shipped', 'available'
- 'badge-active'
- when 'draft', 'pending', 'processing', 'ready'
- 'badge-warning'
- when 'archived', 'canceled', 'cancelled', 'failed', 'void', 'inactive'
- 'badge-inactive'
- else
- 'badge-secondary'
- end
+ return empty_column_placeholder if value.blank?
+ css_class = STATUS_BADGE_CLASSES[value.to_s] || 'badge-secondary'
content_tag(:span, Spree.t(value, scope: column.key, default: value.to_s.humanize), class: "badge #{css_class}")
end
@@ -144,20 +144,11 @@ module Spree
# @param table [Spree::Admin::Table] the table
# @return [String]
def render_link_column(record, value, column, table = nil)
- return content_tag(:span, '-', class: 'text-gray-400') if value.blank?
-
- url = nil
- if table&.link_to_action == :show && respond_to?(:object_url)
- url = object_url(record) rescue nil
- elsif respond_to?(:edit_object_url)
- url = edit_object_url(record) rescue nil
- end
+ return empty_column_placeholder if value.blank?
- if url
- link_to h(value.to_s.truncate(100)), url, data: { turbo_frame: '_top' }
- else
- h(value.to_s.truncate(100))
- end
+ truncated_value = h(value.to_s.truncate(100))
+ url = resolve_link_url(record, table)
+ url ? link_to(truncated_value, url, data: { turbo_frame: '_top' }) : truncated_value
end
# Render image column
@@ -166,14 +157,14 @@ module Spree
# @param column [Spree::Admin::Table::Column] column definition
# @return [String]
def render_image_column(record, value, column)
- return content_tag(:span, '-', class: 'text-gray-400') if value.blank?
+ return empty_column_placeholder if value.blank?
if value.respond_to?(:attached?) && value.attached?
spree_image_tag(value, width: 50, height: 50, class: 'rounded', loading: 'lazy')
- elsif value.is_a?(String) && value.present?
+ elsif value.is_a?(String)
image_tag value, class: 'rounded', style: 'max-width: 50px; max-height: 50px;', loading: 'lazy'
else
- content_tag(:span, '-', class: 'text-gray-400')
+ empty_column_placeholder
end
end
@@ -182,13 +173,9 @@ module Spree
# @param column [Spree::Admin::Table::Column] column definition
# @return [String]
def render_string_column(value, column)
- return content_tag(:span, '-', class: 'text-gray-400') if value.blank?
+ return empty_column_placeholder if value.blank?
- if column.format.present? && respond_to?(column.format)
- send(column.format, value)
- else
- h(value.to_s.truncate(100))
- end
+ column.format.present? && respond_to?(column.format) ? send(column.format, value) : h(value.to_s.truncate(100))
end
# Render association column (e.g., taxons, tags)
@@ -196,7 +183,7 @@ module Spree
# @param column [Spree::Admin::Table::Column] column definition
# @return [String]
def render_association_column(value, column)
- return content_tag(:span, '-', class: 'text-gray-400') if value.blank?
+ return empty_column_placeholder if value.blank?
h(value.to_s.truncate(100))
end
@@ -211,83 +198,12 @@ module Spree
current_field, current_direction = parse_current_sort(current_sort)
current_label = find_sort_label(sortable, current_sort)
-
- # Convert params[:q] to a regular hash to avoid unpermitted parameters error
current_q = params[:q].respond_to?(:to_unsafe_h) ? params[:q].to_unsafe_h : (params[:q] || {})
+ default_field = sortable.first.ransack_attribute
dropdown(portal: false) do
- toggle = dropdown_toggle(class: 'btn-light btn-sm h-[2.125rem]') do
- safe_join([
- current_direction == 'asc' ? icon('sort-ascending') : icon('sort-descending'),
- content_tag(:span, current_label),
- icon('chevron-down')
- ])
- end
-
- menu = dropdown_menu(class: 'min-w-[200px]') do
- sections = []
-
- # Sort by section header
- sections << content_tag(:div, class: 'dropdown-header') do
- Spree.t('admin.tables.sort_by')
- end
-
- # Sort field options
- sortable.each do |column|
- is_active = current_field == column.ransack_attribute
- sort_value = "#{column.ransack_attribute} #{current_direction || 'desc'}"
-
- sections << link_to(
- url_for(q: current_q.merge(s: sort_value)),
- class: "dropdown-item flex items-center justify-between #{'active' if is_active}",
- data: { turbo_action: 'advance' }
- ) do
- safe_join([
- content_tag(:span, column.resolve_label),
- is_active ? icon('check') : ''
- ])
- end
- end
-
- # Divider
- sections << content_tag(:hr, '', class: 'dropdown-divider')
-
- # Order section header
- sections << content_tag(:div, class: 'dropdown-header') do
- Spree.t('admin.tables.order')
- end
-
- # Ascending option
- asc_active = current_direction == 'asc'
- asc_sort_value = current_field.present? ? "#{current_field} asc" : "#{sortable.first.ransack_attribute} asc"
- sections << link_to(
- url_for(q: current_q.merge(s: asc_sort_value)),
- class: "dropdown-item flex items-center justify-between #{'active' if asc_active}",
- data: { turbo_action: 'advance' }
- ) do
- safe_join([
- content_tag(:span, Spree.t('admin.tables.ascending')),
- asc_active ? icon('check') : ''
- ])
- end
-
- # Descending option
- desc_active = current_direction == 'desc' || current_direction.nil?
- desc_sort_value = current_field.present? ? "#{current_field} desc" : "#{sortable.first.ransack_attribute} desc"
- sections << link_to(
- url_for(q: current_q.merge(s: desc_sort_value)),
- class: "dropdown-item flex items-center justify-between #{'active' if desc_active}",
- data: { turbo_action: 'advance' }
- ) do
- safe_join([
- content_tag(:span, Spree.t('admin.tables.descending')),
- desc_active ? icon('check') : ''
- ])
- end
-
- safe_join(sections)
- end
-
+ toggle = sort_dropdown_toggle(current_direction, current_label)
+ menu = sort_dropdown_menu(sortable, current_field, current_direction, current_q, default_field)
safe_join([toggle, menu])
end
end
@@ -296,19 +212,17 @@ module Spree
# @param column [Spree::Admin::Table::Column] column definition
# @return [String]
def column_header_class(column)
- classes = []
- classes << "text-#{column.align}" if column.align.to_s != 'left'
- classes << "w-#{column.width}" if column.width.present?
- classes.join(' ')
+ [].tap do |classes|
+ classes << "text-#{column.align}" unless column.align.to_s == 'left'
+ classes << "w-#{column.width}" if column.width.present?
+ end.join(' ')
end
# Get column cell CSS class
# @param column [Spree::Admin::Table::Column] column definition
# @return [String]
def column_cell_class(column)
- classes = []
- classes << "text-#{column.align}" if column.align.to_s != 'left'
- classes.join(' ')
+ column.align.to_s == 'left' ? '' : "text-#{column.align}"
end
# Build query builder fields JSON for Stimulus controller
@@ -439,24 +353,71 @@ module Spree
private
+ def sort_dropdown_toggle(current_direction, current_label)
+ dropdown_toggle(class: 'btn-light btn-sm h-[2.125rem]') do
+ safe_join([
+ icon(current_direction == 'asc' ? 'sort-ascending' : 'sort-descending'),
+ content_tag(:span, current_label),
+ icon('chevron-down')
+ ])
+ end
+ end
+
+ def sort_dropdown_menu(sortable, current_field, current_direction, current_q, default_field)
+ dropdown_menu(class: 'min-w-[200px]') do
+ sections = [sort_dropdown_header('admin.tables.sort_by')]
+
+ sortable.each do |column|
+ is_active = current_field == column.ransack_attribute
+ sort_value = "#{column.ransack_attribute} #{current_direction || 'desc'}"
+ sections << sort_dropdown_item(column.resolve_label, sort_value, is_active, current_q)
+ end
+
+ sections << content_tag(:hr, '', class: 'dropdown-divider')
+ sections << sort_dropdown_header('admin.tables.order')
+
+ field = current_field.presence || default_field
+ sections << sort_dropdown_item(Spree.t('admin.tables.ascending'), "#{field} asc", current_direction == 'asc', current_q)
+ sections << sort_dropdown_item(Spree.t('admin.tables.descending'), "#{field} desc", current_direction != 'asc', current_q)
+
+ safe_join(sections)
+ end
+ end
+
+ def sort_dropdown_header(i18n_key)
+ content_tag(:div, Spree.t(i18n_key), class: 'dropdown-header')
+ end
+
+ def sort_dropdown_item(label, sort_value, is_active, current_q)
+ link_to(
+ url_for(q: current_q.merge(s: sort_value)),
+ class: "dropdown-item flex items-center justify-between #{'active' if is_active}",
+ data: { turbo_action: 'advance' }
+ ) do
+ safe_join([content_tag(:span, label), is_active ? icon('check') : ''])
+ end
+ end
+
+ def resolve_link_url(record, table)
+ if table&.link_to_action == :show && respond_to?(:object_url)
+ object_url(record) rescue nil
+ elsif respond_to?(:edit_object_url)
+ edit_object_url(record) rescue nil
+ end
+ end
+
def parse_current_sort(current_sort)
return [nil, nil] if current_sort.blank?
- parts = current_sort.split(' ')
- [parts[0], parts[1]]
+ current_sort.split(' ', 2)
end
def find_sort_label(sortable, current_sort)
return Spree.t('admin.tables.sort_by') if current_sort.blank?
- field, _direction = parse_current_sort(current_sort)
+ field, = parse_current_sort(current_sort)
column = sortable.find { |c| c.ransack_attribute == field }
-
- if column
- column.resolve_label
- else
- Spree.t('admin.tables.sort_by')
- end
+ column&.resolve_label || Spree.t('admin.tables.sort_by')
end
# Recursively count filters in a state object (including nested groups)
@@ -465,21 +426,9 @@ module Spree
def count_filters_in_state(state)
return 0 unless state.is_a?(Hash)
- count = 0
-
- # Count filters at this level (only those with a field selected)
- if state['filters'].is_a?(Array)
- count += state['filters'].count { |f| f['field'].present? }
- end
-
- # Count filters in nested groups
- if state['groups'].is_a?(Array)
- state['groups'].each do |group|
- count += count_filters_in_state(group)
- end
- end
-
- count
+ filters_count = Array(state['filters']).count { |f| f['field'].present? }
+ groups_count = Array(state['groups']).sum { |group| count_filters_in_state(group) }
+ filters_count + groups_count
end
end
end
diff --git a/admin/app/models/spree/admin/table.rb b/admin/app/models/spree/admin/table.rb
index 6ac6ba54e3..086a646510 100644
--- a/admin/app/models/spree/admin/table.rb
+++ b/admin/app/models/spree/admin/table.rb
@@ -87,10 +87,7 @@ module Spree
column = @columns[key.to_sym]
return nil unless column
- options.each do |attr, value|
- column.send("#{attr}=", value) if column.respond_to?("#{attr}=")
- end
-
+ apply_attributes(column, options)
sort_columns!
column
end
@@ -231,10 +228,7 @@ module Spree
action = @bulk_actions[key.to_sym]
return nil unless action
- options.each do |attr, value|
- action.send("#{attr}=", value) if action.respond_to?("#{attr}=")
- end
-
+ apply_attributes(action, options)
sort_bulk_actions!
action
end
@@ -300,6 +294,12 @@ module Spree
private
+ def apply_attributes(object, options)
+ options.each do |attr, value|
+ object.send("#{attr}=", value) if object.respond_to?("#{attr}=")
+ end
+ end
+
def sort_columns!
@columns = @columns.sort_by { |_key, col| [col.position, col.key.to_s] }.to_h
end
diff --git a/admin/app/models/spree/admin/table/bulk_action.rb b/admin/app/models/spree/admin/table/bulk_action.rb
index 34e1a058c0..c4b3e46134 100644
--- a/admin/app/models/spree/admin/table/bulk_action.rb
+++ b/admin/app/models/spree/admin/table/bulk_action.rb
@@ -4,6 +4,7 @@ module Spree
class BulkAction
include ActiveModel::Model
include ActiveModel::Attributes
+ include Visibility
METHODS = %i[get post put patch delete].freeze
@@ -37,16 +38,6 @@ module Spree
self.method = self.method.to_sym if self.method.is_a?(String)
end
- # Check if action is visible for the given context
- # @param context [Object, nil] view context with access to helper methods
- # @return [Boolean]
- def visible?(context = nil)
- return true if condition.nil?
- return condition unless condition.respond_to?(:call)
-
- context&.respond_to?(:instance_exec) ? context.instance_exec(&condition) : condition.call(context)
- end
-
# Resolve label (handles i18n keys)
# @return [String]
def resolve_label
diff --git a/admin/app/models/spree/admin/table/column.rb b/admin/app/models/spree/admin/table/column.rb
index 8882cdcc10..ad6433c91e 100644
--- a/admin/app/models/spree/admin/table/column.rb
+++ b/admin/app/models/spree/admin/table/column.rb
@@ -4,10 +4,25 @@ module Spree
class Column
include ActiveModel::Model
include ActiveModel::Attributes
+ include Visibility
TYPES = %w[string number date datetime money status link boolean image custom association].freeze
FILTER_TYPES = %w[string number date datetime money status boolean autocomplete select].freeze
+ DEFAULT_OPERATORS = {
+ 'string' => %i[eq not_eq cont not_cont start end in not_in null not_null],
+ 'number' => %i[eq not_eq gt gteq lt lteq in not_in null not_null],
+ 'money' => %i[eq not_eq gt gteq lt lteq in not_in null not_null],
+ 'date' => %i[eq not_eq gt gteq lt lteq null not_null],
+ 'datetime' => %i[eq not_eq gt gteq lt lteq null not_null],
+ 'boolean' => %i[eq],
+ 'status' => %i[eq not_eq in not_in],
+ 'select' => %i[eq not_eq in not_in],
+ 'association' => %i[in not_in],
+ 'tags' => %i[in not_in],
+ 'autocomplete' => %i[in not_in]
+ }.freeze
+
attribute :key, :string
attribute :label
attribute :type, :string, default: 'string'
@@ -51,29 +66,10 @@ module Spree
sort_scope_asc.present? || sort_scope_desc.present?
end
- # Check if column is visible for the given context
- def visible?(context = nil)
- return true if condition.nil?
-
- if condition.respond_to?(:call)
- if context&.respond_to?(:instance_exec)
- context.instance_exec(&condition)
- else
- condition.call(context)
- end
- else
- condition
- end
- end
-
# Resolve label (handles i18n keys)
def resolve_label
- if label.is_a?(String) && label.present?
- if label.include?('.')
- return I18n.t(label, default: label.split('.').last.humanize)
- end
- return label
- end
+ return I18n.t(label, default: label.split('.').last.humanize) if label.is_a?(String) && label.include?('.')
+ return label if label.is_a?(String) && label.present?
key_to_translate = label || key
Spree.t(key_to_translate, default: key_to_translate.to_s.humanize)
@@ -82,11 +78,7 @@ module Spree
# Resolve value from record
def resolve_value(record, context = nil)
if self.method.respond_to?(:call)
- if context&.respond_to?(:instance_exec)
- context.instance_exec(record, &self.method)
- else
- self.method.call(record)
- end
+ context&.respond_to?(:instance_exec) ? context.instance_exec(record, &self.method) : self.method.call(record)
elsif record.respond_to?(self.method)
record.send(self.method)
end
@@ -111,22 +103,7 @@ module Spree
end
def default_operators_for_type
- case filter_type
- when 'string'
- %i[eq not_eq cont not_cont start end in not_in null not_null]
- when 'number', 'money'
- %i[eq not_eq gt gteq lt lteq in not_in null not_null]
- when 'date', 'datetime'
- %i[eq not_eq gt gteq lt lteq null not_null]
- when 'boolean'
- %i[eq]
- when 'status', 'select'
- %i[eq not_eq in not_in]
- when 'association', 'tags', 'autocomplete'
- %i[in not_in]
- else
- %i[eq not_eq cont null not_null]
- end
+ DEFAULT_OPERATORS[filter_type] || %i[eq not_eq cont null not_null]
end
end
end
diff --git a/admin/app/models/spree/admin/table/visibility.rb b/admin/app/models/spree/admin/table/visibility.rb
new file mode 100644
index 0000000000..8dc4e89f7c
--- /dev/null
+++ b/admin/app/models/spree/admin/table/visibility.rb
@@ -0,0 +1,20 @@
+module Spree
+ module Admin
+ class Table
+ # Shared visibility logic for components with conditional display
+ module Visibility
+ extend ActiveSupport::Concern
+
+ # Check if component is visible for the given context
+ # @param context [Object, nil] view context with access to helper methods
+ # @return [Boolean]
+ def visible?(context = nil)
+ return true if condition.nil?
+ return condition unless condition.respond_to?(:call)
+
+ context&.respond_to?(:instance_exec) ? context.instance_exec(&condition) : condition.call(context)
+ end
+ end
+ end
+ end
+end