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.

Some controllers

Damian Kaczmarczyk41a63de1e914
diff --git a/admin/app/javascript/spree/admin/application.js b/admin/app/javascript/spree/admin/application.js
index 27a8421c23..ef43f56512 100644
--- a/admin/app/javascript/spree/admin/application.js
+++ b/admin/app/javascript/spree/admin/application.js
@@ -18,16 +18,19 @@ import 'spree/admin/helpers/canvas'
import 'spree/admin/helpers/trix/video_embed'
import 'spree/admin/helpers/bootstrap'
-
// Stimulus controllers
import { Application } from "@hotwired/stimulus"
-const application = Application.start()
-
-// Configure Stimulus development experience
-application.debug = false
-window.Stimulus = application
+let application
+if (typeof Stimulus === 'undefined') {
+ application = Application.start()
+ // Configure Stimulus development experience
+ application.debug = false
+ window.Stimulus = application
+} else {
+ application = window.Stimulus
+}
import AutoSubmit from '@stimulus-components/auto-submit'
import TextareaAutogrow from 'stimulus-textarea-autogrow'
import Notification from 'stimulus-notification'
@@ -38,11 +41,9 @@ import Sortable from 'stimulus-sortable'
import { Tabs } from 'tailwindcss-stimulus-components'
import AccountBillingAddressController from 'spree/admin/controllers/account_billing_address_controller'
-import AccountTaxRegistrationsController from 'spree/admin/controllers/account_tax_registrations_controller'
import ActiveStorageUpload from 'spree/admin/controllers/active_storage_upload_controller'
-import AddDomainController from 'spree/admin/controllers/add_domain_controller'
-// import AddressAutocompleteController from 'spree/addre/controllersss_autocomplete_controller'
-// import AddressFormController from 'spree/addre/controllersss_form_controller'
+// // import AddressAutocompleteController from 'spree/addre/controllersss_autocomplete_controller'
+// // import AddressFormController from 'spree/addre/controllersss_form_controller'
import AssetUploaderController from 'spree/admin/controllers/asset_uploader_controller'
import AutocompleteSelectController from 'spree/admin/controllers/autocomplete_select_controller'
import BetterSliderController from 'spree/admin/controllers/better_slider_controller'
@@ -54,39 +55,36 @@ import CalendarRangeController from 'spree/admin/controllers/calendar_range_cont
import Clipboard from 'spree/admin/controllers/clipboard_controller'
import ColorPaletteController from 'spree/admin/controllers/color_palette_controller'
import ColorPickerController from 'spree/admin/controllers/color_picker_controller'
-// import EnableButtonController from 'spree/enabl/controllerse_button_controller'
-import FlatfileUploaderController from 'spree/admin/controllers/flatfile_uploader_controller'
-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 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'
-import ProductFormController from 'spree/admin/controllers/product_form_controller'
-import RangeInputController from 'spree/admin/controllers/range_input_controller'
-import ReplaceController from 'spree/admin/controllers/replace_controller'
-import RowLinkController from 'spree/admin/controllers/row_link_controller'
-import RuleFormController from 'spree/admin/controllers/rule_form_controller'
-import SearchPickerController from 'spree/admin/controllers/search_picker_controller'
-import SectionFormController from 'spree/admin/controllers/section_form_controller'
-import SelectController from 'spree/admin/controllers/select_controller'
-import SeoFormController from 'spree/admin/controllers/seo_form_controller'
-import SlugFormController from 'spree/admin/controllers/slug_form_controller'
-import SortableTree from 'spree/admin/controllers/sortable_tree_controller'
-import SpreeController from 'spree/admin/controllers/spree_controller'
-import StockTransferController from 'spree/admin/controllers/stock_transfer_controller'
-import StoreFormController from 'spree/admin/controllers/store_form_controller'
-import UnitSystemController from 'spree/admin/controllers/unit_system_controller'
-import VariantsFormController from 'spree/admin/controllers/variants_form_controller'
-import WebhooksSubscriberEventsController from 'spree/admin/controllers/webhook_subscriber_events_controller'
+// // import EnableButtonController from 'spree/enabl/controllerse_button_controller'
+// import FlatfileUploaderController from 'spree/admin/controllers/flatfile_uploader_controller'
+// 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 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'
+// import ProductFormController from 'spree/admin/controllers/product_form_controller'
+// import RangeInputController from 'spree/admin/controllers/range_input_controller'
+// import ReplaceController from 'spree/admin/controllers/replace_controller'
+// import RowLinkController from 'spree/admin/controllers/row_link_controller'
+// import RuleFormController from 'spree/admin/controllers/rule_form_controller'
+// import SearchPickerController from 'spree/admin/controllers/search_picker_controller'
+// import SectionFormController from 'spree/admin/controllers/section_form_controller'
+// import SelectController from 'spree/admin/controllers/select_controller'
+// import SeoFormController from 'spree/admin/controllers/seo_form_controller'
+// import SlugFormController from 'spree/admin/controllers/slug_form_controller'
+// import SortableTree from 'spree/admin/controllers/sortable_tree_controller'
+// import StockTransferController from 'spree/admin/controllers/stock_transfer_controller'
+// import StoreFormController from 'spree/admin/controllers/store_form_controller'
+// import UnitSystemController from 'spree/admin/controllers/unit_system_controller'
+// import VariantsFormController from 'spree/admin/controllers/variants_form_controller'
+// import WebhooksSubscriberEventsController from 'spree/admin/controllers/webhook_subscriber_events_controller'
application.register('account-billing-address', AccountBillingAddressController)
-application.register('account-tax-registrations', AccountTaxRegistrationsController)
application.register('active-storage-upload', ActiveStorageUpload)
-application.register('add-domain', AddDomainController)
-// application.register('address-autocomplete', AddressAutocompleteController)
-// application.register('address-form', AddressFormController)
+// // application.register('address-autocomplete', AddressAutocompleteController)
+// // application.register('address-form', AddressFormController)
application.register('asset-uploader', AssetUploaderController)
application.register('auto-submit', AutoSubmit)
application.register('autocomplete-select', AutocompleteSelectController)
@@ -99,41 +97,38 @@ application.register('calendar-range', CalendarRangeController)
application.register('clipboard', Clipboard)
application.register('color-palette', ColorPaletteController)
application.register('color-picker', ColorPickerController)
-// application.register('enable-button', EnableButtonController)
-application.register('flatfile-uploader', FlatfileUploaderController)
-application.register('filters', FiltersController)
-application.register('font-picker', FontPickerController)
-application.register('media-form', MediaFormController)
-application.register('multi-input', MultiInputController)
+// // application.register('enable-button', EnableButtonController)
+// application.register('flatfile-uploader', FlatfileUploaderController)
+// application.register('filters', FiltersController)
+// application.register('font-picker', FontPickerController)
+// application.register('media-form', MediaFormController)
+// application.register('multi-input', MultiInputController)
application.register('nested-form', RailsNestedForm)
application.register('notification', Notification)
-application.register('order-billing-address', OrderBillingAddressController)
-application.register('page-builder', PageBuilderController)
-application.register('password-toggle', PasswordToggle)
+// application.register('order-billing-address', OrderBillingAddressController)
+// application.register('page-builder', PageBuilderController)
+// application.register('password-toggle', PasswordToggle)
application.register('password-visibility', PasswordVisibility)
-application.register('product-form', ProductFormController)
-application.register('range-input', RangeInputController)
-application.register('replace', ReplaceController)
+// application.register('product-form', ProductFormController)
+// application.register('range-input', RangeInputController)
+// application.register('replace', ReplaceController)
application.register('reveal', Reveal)
-application.register('row-link', RowLinkController)
-application.register('rule-form', RuleFormController)
-application.register('search-picker', SearchPickerController)
-application.register('section-form', SectionFormController)
-application.register('select', SelectController)
-application.register('seo-form', SeoFormController)
-application.register('slug-form', SlugFormController)
+// application.register('row-link', RowLinkController)
+// application.register('rule-form', RuleFormController)
+// application.register('search-picker', SearchPickerController)
+// application.register('section-form', SectionFormController)
+// application.register('select', SelectController)
+// application.register('seo-form', SeoFormController)
+// application.register('slug-form', SlugFormController)
application.register('sortable', Sortable)
-application.register('sortable-tree', SortableTree)
-application.register('spree', SpreeController)
-application.register('stock-transfer', StockTransferController)
-application.register('store-form', StoreFormController)
+// application.register('sortable-tree', SortableTree)
+// application.register('stock-transfer', StockTransferController)
+// application.register('store-form', StoreFormController)
application.register('tabs', Tabs)
application.register('textarea-autogrow', TextareaAutogrow)
-application.register('unit-system', UnitSystemController)
-application.register('variants-form', VariantsFormController)
-application.register('webhooks-subscriber-events', WebhooksSubscriberEventsController)
-
-
+// application.register('unit-system', UnitSystemController)
+// application.register('variants-form', VariantsFormController)
+// application.register('webhooks-subscriber-events', WebhooksSubscriberEventsController)
LocalTime.start()
diff --git a/admin/app/javascript/spree/admin/controllers/account_billing_address_controller.js b/admin/app/javascript/spree/admin/controllers/account_billing_address_controller.js
new file mode 100644
index 0000000000..ed29d93dc8
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/account_billing_address_controller.js
@@ -0,0 +1,25 @@
+import { Controller } from '@hotwired/stimulus'
+
+export default class extends Controller {
+ static targets = [
+ 'country',
+ 'state',
+ 'stateSelectContainer'
+ ]
+
+ connect() {
+ super.connect()
+ this.changeCountry()
+ }
+
+ changeCountry(_) {
+ const countryIso = this.countryTarget.value
+
+ if (countryIso == 'US') {
+ this.stateSelectContainerTarget.classList.remove('hidden')
+ } else {
+ this.stateSelectContainerTarget.classList.add('hidden')
+ this.stateTarget.value = ''
+ }
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/active_storage_upload_controller.js b/admin/app/javascript/spree/admin/controllers/active_storage_upload_controller.js
new file mode 100644
index 0000000000..d9da1097e7
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/active_storage_upload_controller.js
@@ -0,0 +1,166 @@
+import { Controller } from '@hotwired/stimulus'
+
+import Uppy from '@uppy/core'
+import Dashboard from '@uppy/dashboard'
+import ImageEditor from '@uppy/image-editor'
+import ActiveStorageUpload from 'spree/admin/helpers/uppy_active_storage'
+
+export default class extends Controller {
+ static targets = ['thumb', 'toolbar', 'remove', 'placeholder']
+
+ static values = {
+ fieldName: String,
+ thumbWidth: Number,
+ thumbHeight: Number,
+ autoSubmit: Boolean,
+ multiple: { type: Boolean, default: false },
+ crop: { type: Boolean, default: false },
+ allowedFileTypes: { type: Array, default: [] }
+ }
+
+ connect() {
+ this.uppy = new Uppy({
+ autoProceed: true,
+ allowMultipleUploads: false,
+ restrictions: {
+ allowedFileTypes: this.allowedFileTypesValue.length ? this.allowedFileTypesValue : undefined
+ },
+ debug: true
+ })
+
+ this.uppy.use(ActiveStorageUpload, {
+ directUploadUrl: document.querySelector("meta[name='direct-upload-url']").getAttribute('content')
+ })
+
+ let dashboardOptions = {}
+ if (this.cropValue == true) {
+ dashboardOptions = {
+ autoOpen: 'imageEditor'
+ }
+ } else {
+ dashboardOptions = {
+ closeAfterFinish: true
+ }
+ }
+
+ this.uppy.use(Dashboard, dashboardOptions)
+
+ if (this.cropValue == true) {
+ this.uppy.use(ImageEditor, {
+ cropperOptions: {
+ aspectRatio: this.thumbWidthValue / this.thumbHeightValue
+ }
+ })
+ }
+
+ this.uppy.on('file-editor:complete', (updatedFile) => {
+ console.log('File editing complete:', updatedFile)
+ // Remove the old file from Uppy's file list
+ this.uppy.removeFile(updatedFile.id)
+ // Add the updated file to Uppy
+ this.uppy.addFile({
+ name: updatedFile.name,
+ type: updatedFile.type,
+ data: updatedFile.data,
+ source: 'local',
+ isRemote: false
+ })
+ })
+
+ this.uppy.on('upload-success', (file, response) => {
+ this.handleUI(file, response)
+ })
+
+ this.uppy.on('file-editor:complete', (updatedFile, result) => {
+ this.handleUI(updatedFile, result)
+ })
+
+ this.uppy.on('dashboard:modal-closed', () => {
+ this.uppy.clear()
+ })
+ }
+
+ open(event) {
+ event.preventDefault()
+ this.uppy.getPlugin('Dashboard').openModal()
+ }
+
+ remove(event) {
+ event.preventDefault()
+
+ if (window.confirm('Are you sure?')) {
+ if (this.hasThumbTarget) {
+ // handle thumb preview
+ this.thumbTarget.style = 'display: none !important'
+ this.thumbTarget.dataset.imageSignedId = null
+ this.thumbTarget.src = ''
+ }
+
+ // hide toolbar if attached
+ if (this.hasToolbarTarget) {
+ this.toolbarTarget.style = 'display: none !important'
+ }
+
+ // mark for removal (on the backend)
+ if (this.hasRemoveTarget) {
+ this.removeTarget.value = '1'
+ }
+
+ if (this.hasPlaceholderTarget) {
+ this.placeholderTarget.style.display = null
+ }
+
+ if (this.autoSubmitValue == true) {
+ this.element.closest('form').requestSubmit()
+ }
+
+ this.uppy.clear()
+ }
+ }
+
+ handleUI(file, response) {
+ this.placeholderTarget.style = 'display: none !important'
+
+ const signedId = response.signed_id
+
+ if (this.hasThumbTarget) {
+ this.thumbTarget.src = URL.createObjectURL(file.data)
+ this.thumbTarget.style.display = null
+ this.thumbTarget.dataset.imageSignedId = signedId
+ this.thumbTarget.width = this.thumbWidthValue
+ this.thumbTarget.height = this.thumbHeightValue
+ }
+
+ // Remove existing hidden field for this file, if any
+ const existingField = this.element.querySelector(`input[name="${this.fieldNameValue}"]`)
+ if (existingField) {
+ existingField.remove()
+ }
+
+ const hiddenField = document.createElement('input')
+
+ hiddenField.setAttribute('type', 'hidden')
+ hiddenField.setAttribute('value', signedId)
+
+ if (this.multipleValue) {
+ hiddenField.setAttribute('name', `${this.fieldNameValue}[]`)
+ } else {
+ hiddenField.setAttribute('name', this.fieldNameValue)
+ }
+
+ this.element.appendChild(hiddenField)
+
+ // show toolbar if attached
+ if (this.hasToolbarTarget) {
+ this.toolbarTarget.style.display = null
+ }
+
+ if (this.hasRemoveTarget) {
+ this.removeTarget.value = null
+ }
+
+ if (this.autoSubmitValue == true) {
+ this.element.closest('form').requestSubmit()
+ }
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/asset_uploader_controller.js b/admin/app/javascript/spree/admin/controllers/asset_uploader_controller.js
new file mode 100644
index 0000000000..2dcde944ac
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/asset_uploader_controller.js
@@ -0,0 +1,58 @@
+import { Controller } from '@hotwired/stimulus'
+import { post } from '@rails/request.js'
+import Uppy from '@uppy/core'
+import Dashboard from '@uppy/dashboard'
+import ActiveStorageUpload from 'spree/admin/helpers/uppy_active_storage'
+
+export default class extends Controller {
+ static values = {
+ assetClass: { type: String, default: 'Spree::Image' },
+ viewableId: String,
+ viewableType: String,
+ multiple: { type: Boolean, default: false },
+ type: { type: String, default: 'image' },
+ allowedFileTypes: { type: Array, default: [] }
+ }
+
+ connect() {
+ this.uppy = new Uppy({
+ autoProceed: true,
+ allowMultipleUploads: this.multipleValue,
+ debug: true,
+ restrictions: {
+ allowedFileTypes: this.allowedFileTypesValue.length ? this.allowedFileTypesValue : undefined
+ }
+ })
+
+ this.uppy.use(ActiveStorageUpload, {
+ directUploadUrl: document.querySelector("meta[name='direct-upload-url']").getAttribute('content')
+ })
+
+ this.uppy.use(Dashboard, {
+ closeAfterFinish: true
+ })
+
+ this.uppy.on('upload-success', (file, response) => {
+ this.handleSuccessResult(response)
+ })
+ }
+
+ open(event) {
+ event.preventDefault()
+ this.uppy.getPlugin('Dashboard').openModal()
+ }
+
+ handleSuccessResult(response) {
+ post('/admin/assets', {
+ body: JSON.stringify({
+ asset: {
+ type: this.assetClassValue,
+ viewable_type: this.viewableTypeValue,
+ viewable_id: this.viewableIdValue,
+ attachment: response.signed_id
+ }
+ }),
+ responseKind: 'turbo-stream'
+ })
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/autocomplete_select_controller.js b/admin/app/javascript/spree/admin/controllers/autocomplete_select_controller.js
new file mode 100644
index 0000000000..9a5b26ada2
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/autocomplete_select_controller.js
@@ -0,0 +1,36 @@
+import { Controller } from "@hotwired/stimulus"
+import TomSelect from 'tom-select/dist/esm/tom-select.complete.js';
+
+// this is a very simple autocomplete select controller that uses TomSelect
+// by default it does not support remote data fetching or adding new options
+// that scenarios are handled in the more robust select_controller.js
+export default class extends Controller {
+ connect() {
+ let selectedValue = this.element.value
+
+ let plugins = []
+
+ if (this.element.multiple) {
+ plugins = ['remove_button']
+ }
+
+ this.select = new TomSelect(this.element ,{
+ create: false,
+ maxOptions: this.element.children.length,
+ selectOnTab: true,
+ allowEmptyOption: false,
+ plugins: plugins
+ })
+ if (!this.element.multiple) {
+ this.select.on('type', () => {
+ this.select.clear()
+ })
+ this.select.on('change', (value) => {
+ if (value) selectedValue = value
+ })
+ this.select.on('blur', () => {
+ this.select.setValue(selectedValue)
+ })
+ }
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/better_slider_controller.js b/admin/app/javascript/spree/admin/controllers/better_slider_controller.js
new file mode 100644
index 0000000000..4d519e3f62
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/better_slider_controller.js
@@ -0,0 +1,23 @@
+import { Controller } from '@hotwired/stimulus'
+
+export default class extends Controller {
+ static targets = ['currentValueLabel', 'rangeInput']
+ static values = { labelForMin: String, unit: String }
+
+ connect() {
+ this.rangeInputTarget.addEventListener('input', this.updateCurrentValueLabel.bind(this))
+ this.updateCurrentValueLabel()
+ }
+
+ updateCurrentValueLabel() {
+ if (this.rangeInputTarget.value === this.rangeInputTarget.min && this.labelForMinValue.length) {
+ this.currentValueLabelTarget.innerText = this.labelForMinValue
+ } else {
+ this.currentValueLabelTarget.innerText = this.rangeInputTarget.value + this.unitValue
+ }
+ }
+
+ disconnect() {
+ this.rangeInputTarget.removeEventListener('input', this.updateCurrentValueLabel.bind(this))
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/block_form_controller.js b/admin/app/javascript/spree/admin/controllers/block_form_controller.js
new file mode 100644
index 0000000000..35237766f1
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/block_form_controller.js
@@ -0,0 +1,11 @@
+import { Controller } from '@hotwired/stimulus'
+
+export default class extends Controller {
+ static targets = ['form', 'type']
+
+ addBlock(event) {
+ event.preventDefault()
+ this.typeTarget.value = event.params.type
+ this.formTarget.requestSubmit()
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/bootstrap_tabs_controller.js b/admin/app/javascript/spree/admin/controllers/bootstrap_tabs_controller.js
new file mode 100644
index 0000000000..b9a822f044
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/bootstrap_tabs_controller.js
@@ -0,0 +1,9 @@
+import { Controller } from '@hotwired/stimulus'
+
+export default class extends Controller {
+ static targets = ['input']
+
+ change({ params: { tab } }) {
+ this.inputTarget.value = tab
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/bulk_operation_controller.js b/admin/app/javascript/spree/admin/controllers/bulk_operation_controller.js
new file mode 100644
index 0000000000..29ec76e71f
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/bulk_operation_controller.js
@@ -0,0 +1,78 @@
+import CheckboxSelectAll from 'stimulus-checkbox-select-all'
+
+export default class extends CheckboxSelectAll {
+ static targets = ['panel', 'form', 'counter']
+
+ connect() {
+ super.connect()
+ this.togglePanel()
+ this.toggleRowBackground()
+ }
+
+ toggle(e) {
+ super.toggle(e)
+ this.togglePanel()
+ this.toggleRowBackground()
+ }
+
+ refresh() {
+ super.refresh()
+ this.togglePanel()
+ this.toggleRowBackground()
+ }
+
+ cancel(e) {
+ e.preventDefault()
+ this.checkboxTargets.forEach((checkbox) => {
+ checkbox.checked = false
+ })
+ this.checkboxAllTargets.forEach((checkbox) => {
+ checkbox.checked = false
+ })
+ this.hidePanel()
+ this.removeRowBackground()
+ }
+
+ hidePanel() {
+ this.panelTarget.classList.add('animate__fadeOutDown')
+ this.panelTarget.classList.add('d-none')
+ }
+
+ togglePanel() {
+ if (this.checked.length > 0) {
+ this.panelTarget.classList.remove('animate__fadeOutDown')
+ this.panelTarget.classList.remove('d-none')
+ if (this.counterTarget) {
+ this.counterTarget.textContent = this.checked.length
+ }
+ } else {
+ this.hidePanel()
+ }
+ }
+
+ removeRowBackground() {
+ this.element.querySelectorAll('tr').forEach((row) => {
+ row.classList.remove('bg-active')
+ })
+ }
+
+ toggleRowBackground() {
+ this.element.querySelectorAll('tr').forEach((row) => {
+ row.classList.remove('bg-active')
+ })
+ this.element.querySelectorAll('.row.bg-active').forEach((row) => {
+ row.classList.remove('bg-active')
+ })
+ this.checked.forEach((checkbox) => {
+ if (checkbox.closest('tr')) checkbox.closest('tr').classList.add('bg-active')
+ else if (checkbox.closest('.row')) checkbox.closest('.row').classList.add('bg-active')
+ })
+ }
+
+ setBulkAction(e) {
+ this.formTarget.action = e.target.dataset.url
+ if (e.target.dataset.method) {
+ this.formTarget.method = e.target.dataset.method
+ }
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/calculator_fields_controller.js b/admin/app/javascript/spree/admin/controllers/calculator_fields_controller.js
new file mode 100644
index 0000000000..4717c0502c
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/calculator_fields_controller.js
@@ -0,0 +1,24 @@
+import { Controller } from "@hotwired/stimulus"
+
+export default class extends Controller {
+ static targets = ["container"]
+
+ replaceFields(event) {
+ const selectedCalculator = event.target.value
+
+ const calculatorName = selectedCalculator
+ .split('::')
+ .pop()
+ .replace(/([A-Z])/g, '_$1')
+ .toLowerCase()
+ .replace(/^_/, '')
+
+ const template = document.getElementById(`${calculatorName}_fields`)
+
+ if (template) {
+ this.containerTarget.innerHTML = template.innerHTML
+ } else {
+ console.error(`Template not found for calculator: ${selectedCalculator}`)
+ }
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/calendar_range_controller.js b/admin/app/javascript/spree/admin/controllers/calendar_range_controller.js
new file mode 100644
index 0000000000..6d50972f78
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/calendar_range_controller.js
@@ -0,0 +1,52 @@
+import { Controller } from "@hotwired/stimulus"
+import { easepick } from '@easepick/core';
+import { RangePlugin } from '@easepick/range-plugin';
+import { PresetPlugin } from '@easepick/preset-plugin';
+
+export default class extends Controller {
+ static targets = [ "picker", "dateFrom", "dateTo", "label" ]
+
+ connect() {
+ this.picker = new easepick.create({
+ element: this.pickerTarget,
+ inline: true,
+ css: [
+ 'https://cdn.jsdelivr.net/npm/@easepick/[email protected]/dist/index.css',
+ 'https://cdn.jsdelivr.net/npm/@easepick/[email protected]/dist/index.css',
+ 'https://cdn.jsdelivr.net/npm/@easepick/[email protected]/dist/index.css',
+ ],
+ doc: document,
+ plugins: [RangePlugin, PresetPlugin],
+ RangePlugin: {
+ tooltip: true,
+ startDate: this.dateFromTarget.value,
+ endDate: this.dateToTarget.value,
+ },
+ PresetPlugin: {
+ customLabels: ['Today', 'Yesterday',
+ 'Last 7 Days', 'Last 30 Days',
+ 'This Month', 'Last Month'],
+ position: 'left'
+ },
+ })
+
+ this.picker.on('render', () => {
+ this.picker.ui.container.style.boxShadow = 'none';
+ });
+
+ this.picker.on('select', (event) => {
+ const data = event.detail;
+ this.dateFromTarget.value = data.start
+ this.dateToTarget.value = data.end
+
+ // https://stackoverflow.com/questions/68624668/how-can-i-submit-a-form-on-input-change-with-turbo-streams
+ this.pickerTarget.closest('form').requestSubmit()
+
+ this.labelTarget.innerHTML = this.pickerTarget.innerHTML
+ })
+ }
+
+ open() {
+ this.picker.show()
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/clipboard_controller.js b/admin/app/javascript/spree/admin/controllers/clipboard_controller.js
new file mode 100644
index 0000000000..84f8c8e1c2
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/clipboard_controller.js
@@ -0,0 +1,17 @@
+import Clipboard from 'stimulus-clipboard'
+
+export default class extends Clipboard {
+ copy(event) {
+ event.preventDefault()
+
+ const text = this.sourceTarget.value || this.sourceTarget.innerHTML
+
+ // https://stackoverflow.com/questions/73148190/copy-html-content-to-clipboard
+ navigator.clipboard.write([new ClipboardItem({
+ 'text/plain': new Blob([text], {type: 'text/plain'}),
+ 'text/html': new Blob([text], {type: 'text/html'})
+ })])
+
+ this.copied()
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/color_palette_controller.js b/admin/app/javascript/spree/admin/controllers/color_palette_controller.js
new file mode 100644
index 0000000000..317ecdbfce
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/color_palette_controller.js
@@ -0,0 +1,22 @@
+import { Controller } from "@hotwired/stimulus"
+
+export default class extends Controller {
+ static targets = [
+ "primaryColor",
+ "textColor",
+ "borderColor",
+ "buttonTextColor",
+ "backgroundColor"
+ ]
+
+ selectPalette(event) {
+ this.primaryColorTarget.value = event.params.primaryColor
+ this.textColorTarget.value = event.params.textColor
+ this.borderColorTarget.value = event.params.borderColor
+ this.buttonTextColorTarget.value = event.params.buttonTextColor
+ this.backgroundColorTarget.value = event.params.backgroundColor
+
+ // we need only one event to trigger the change
+ this.primaryColorTarget.dispatchEvent(new InputEvent('change'))
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/color_picker_controller.js b/admin/app/javascript/spree/admin/controllers/color_picker_controller.js
new file mode 100644
index 0000000000..6d4af139fb
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/color_picker_controller.js
@@ -0,0 +1,52 @@
+import { Controller } from "@hotwired/stimulus"
+import Pickr from '@simonwep/pickr'
+
+export default class extends Controller {
+ static targets = ["picker", "input", "value"]
+ static values = { clear: Boolean }
+
+ initialize() {
+ this.initPicker();
+ }
+
+ initPicker() {
+ this.picker = Pickr.create({
+ el: this.pickerTarget,
+ theme: 'classic',
+ default: this.inputTarget.value,
+ useAsButton: true,
+
+ components: {
+ preview: true,
+ opacity: true,
+ hue: true,
+
+ interaction: {
+ hex: true,
+ rgba: true,
+ hsla: false,
+ hsva: false,
+ cmyk: false,
+ input: true,
+ clear: this.hasClearValue ? this.clearValue : false,
+ save: false,
+ comparison: false,
+ },
+ },
+ })
+
+ this.picker.on('change', (color, _instance) => {
+ this.pickerTarget.style.background = color.toRGBA().toString(0);
+ this.inputTarget.value = color.toHEXA().toString()
+ this.valueTarget.innerHTML = color.toHEXA().toString()
+ this.inputTarget.dispatchEvent(new InputEvent('change'))
+ })
+
+ this.picker.on('clear', () => {
+ this.pickerTarget.style.background = 'white';
+ this.inputTarget.value = '';
+ this.valueTarget.innerHTML = '';
+ this.inputTarget.dispatchEvent(new InputEvent('change'))
+ })
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/filters_controller.js b/admin/app/javascript/spree/admin/controllers/filters_controller.js
new file mode 100644
index 0000000000..023bd56ac2
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/filters_controller.js
@@ -0,0 +1,61 @@
+import { Controller } from "@hotwired/stimulus";
+
+export default class extends Controller {
+ static targets = ["input", "badgesContainer", "badgeTemplate"];
+
+ connect() {
+ this.inputTargets.forEach((input) => {
+ this.createBadgeFor(input);
+ });
+ }
+
+ createBadgeFor(input, tomSelect = false) {
+ if (
+ input.tagName === "SELECT" &&
+ input.dataset.selectTarget &&
+ !input.classList.contains("tomselected")
+ ) {
+ input.addEventListener("tomSelectInitialized", () => {
+ this.createBadgeFor(input, true);
+ });
+ } else if (input.value !== null && input.value.length !== 0) {
+ let labelEl;
+ if (tomSelect) {
+ labelEl = document.querySelector(`label[for="${input.id}-ts-control"]`);
+ } else {
+ labelEl = document.querySelector(`label[for="${input.id}"]`);
+ }
+
+ let label;
+ if (labelEl) {
+ label = labelEl.textContent;
+ } else if (input.dataset.badgeName) {
+ label = input.dataset.badgeName;
+ } else {
+ label = input.placeholder;
+ }
+
+ let ransackValue;
+ if (input.tagName === "SELECT") {
+ ransackValue = Array.from(input.selectedOptions)
+ .map((option) => option.text)
+ .join(", ");
+ } else {
+ ransackValue = input.value;
+ }
+
+ label = DOMPurify.sanitize(`${label.trim()}: ${ransackValue.trim()}`);
+
+ const newUrl = new URL(window.location.href);
+ const newSearchParams = newUrl.searchParams;
+ newSearchParams.delete(input.name);
+ newUrl.search = newSearchParams.toString();
+
+ const filterHTML = this.badgeTemplateTarget.innerHTML
+ .replace(/LABEL/g, label)
+ .replace(/DELETE_URL/g, newUrl.toString());
+
+ this.badgesContainerTarget.insertAdjacentHTML("beforeend", filterHTML);
+ }
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/flatfile_uploader_controller.js b/admin/app/javascript/spree/admin/controllers/flatfile_uploader_controller.js
new file mode 100644
index 0000000000..49834e04ed
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/flatfile_uploader_controller.js
@@ -0,0 +1,46 @@
+import { Controller } from '@hotwired/stimulus'
+import { initializeFlatfile } from '@flatfile/javascript'
+
+import createSubmitDataListener from '../flatfile/create_submit_data_listener'
+import { productsWorkbook } from '../flatfile/products_workbook'
+import { customersWorkbook } from '../flatfile/customers_workbook'
+import { postsWorkbook } from '../flatfile/posts_workbook'
+
+export default class extends Controller {
+ static values = {
+ publishableKey: { type: String },
+ environmentId: { type: String },
+ kind: { type: String, default: 'products' },
+ productsPropertiesCount: { type: Number, default: 10 }
+ }
+
+ open(event) {
+ event.preventDefault()
+
+ const flatfileOptions = {
+ name: `Import ${this.kindValue}`,
+ publishableKey: this.publishableKeyValue,
+ environmentId: this.environmentIdValue,
+ workbook: this.workbook,
+ listener: createSubmitDataListener(this.kindValue),
+ sidebarConfig: {
+ showSidebar: false
+ }
+ }
+
+ initializeFlatfile(flatfileOptions)
+ }
+
+ get workbook() {
+ switch (this.kindValue) {
+ case 'products':
+ return productsWorkbook(this.productsPropertiesCountValue)
+ case 'customers':
+ return customersWorkbook
+ case 'posts':
+ return postsWorkbook
+ default:
+ return productsWorkbook
+ }
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/font_picker_controller.js b/admin/app/javascript/spree/admin/controllers/font_picker_controller.js
new file mode 100644
index 0000000000..f034d465eb
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/font_picker_controller.js
@@ -0,0 +1,55 @@
+import { Controller } from '@hotwired/stimulus'
+import TomSelect from 'tom-select/dist/esm/tom-select.complete.js'
+
+export default class extends Controller {
+ static values = {
+ fontsFromGoogle: Array
+ }
+
+ connect() {
+ this.prepareLinkTag()
+ this.element.classList.remove('d-none')
+ this.tomSelect = new TomSelect(this.element, {
+ create: false,
+ maxOptions: 110,
+ render: {
+ item: (data, _escape) => {
+ return `<div style="font-family: '${data.text}'">${data.text}</div>`
+ },
+ option: (data, _escape) => {
+ return `<div style="font-family: '${data.text}'">${data.text}</div>`
+ }
+ }
+ })
+ }
+
+ disconnect() {
+ if (this.tomSelect) {
+ this.tomSelect.destroy()
+ }
+ if (this.linkEl) {
+ this.linkEl.remove()
+ }
+ }
+
+ prepareLinkTag() {
+ if (
+ typeof this.linkEl !== 'undefined' ||
+ !this.fontsFromGoogleValue.length ||
+ document.getElementById('font-picker-styles')
+ ) {
+ return
+ }
+ const fontsAsQueryString = this.fontsFromGoogleValue
+ .map((f) => f.replaceAll(' ', '+'))
+ .join('&family=')
+ const fontsUrl = `https://fonts.googleapis.com/css2?family=${fontsAsQueryString}&display=swap`
+
+ this.linkEl = document.createElement('link')
+ this.linkEl.id = 'font-picker-styles'
+ this.linkEl.href = fontsUrl
+ this.linkEl.rel = 'stylesheet'
+
+ document.head.appendChild(this.linkEl)
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/index.js b/admin/app/javascript/spree/admin/controllers/index.js
deleted file mode 100644
index 384a0e13fa..0000000000
--- a/admin/app/javascript/spree/admin/controllers/index.js
+++ /dev/null
@@ -1,4 +0,0 @@
-// Import and register all your controllers from the importmap via controllers/**/*_controller
-import { application } from "controllers/application"
-import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading"
-eagerLoadControllersFrom("controllers", application)
\ No newline at end of file
diff --git a/admin/app/javascript/spree/admin/controllers/media_form_controller.js b/admin/app/javascript/spree/admin/controllers/media_form_controller.js
new file mode 100644
index 0000000000..16a5f4c65b
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/media_form_controller.js
@@ -0,0 +1,33 @@
+import { Controller } from '@hotwired/stimulus'
+import { destroy } from '@rails/request.js'
+
+export default class extends Controller {
+ static targets = ['checkbox', 'deleteButton']
+
+ static values = {
+ deleteUrl: String
+ }
+
+ deleteSelected = async (e) => {
+ const idsToDelete = this.checkboxTargets.filter((el) => el.checked).map((el) => el.value)
+
+ if (idsToDelete.length && window.confirm('Are you sure?')) {
+ this.deleteButtonTarget.disabled = true
+
+ destroy(this.deleteUrlValue, {
+ body: {
+ ids: idsToDelete
+ },
+ responseKind: 'turbo-stream'
+ })
+ }
+ }
+
+ showDeleteButton = () => {
+ if (this.checkboxTargets.some((el) => el.checked)) {
+ this.deleteButtonTarget.classList.remove('d-none')
+ } else {
+ this.deleteButtonTarget.classList.add('d-none')
+ }
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/multi_input_controller.js b/admin/app/javascript/spree/admin/controllers/multi_input_controller.js
new file mode 100644
index 0000000000..84869b7b66
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/multi_input_controller.js
@@ -0,0 +1,75 @@
+import { Controller } from '@hotwired/stimulus'
+
+export default class extends Controller {
+ static targets = ['input']
+
+ static values = {
+ preloadedValues: Array
+ }
+
+ connect() {
+ this.element.reset = this.reset.bind(this)
+ this.element.values = this.values.bind(this)
+ this.element.setValues = this.setValues.bind(this)
+ this.lastInput = null
+ this.setValues(this.preloadedValuesValue)
+ }
+
+ reset() {
+ this.inputTargets.forEach((container, i) => {
+ if (i > 0) {
+ container.remove()
+ } else {
+ const input = container.querySelector('input')
+ input.value = ''
+ }
+ })
+ this.lastInput = this.inputTargets[0].querySelector('input')
+ }
+
+ values() {
+ return this.inputTargets
+ .map((c) => c.querySelector('input'))
+ .map((input) => input?.value)
+ .filter((value) => value?.length > 0)
+ }
+
+ setValues(values) {
+ this.reset()
+ values.forEach((value, i) => {
+ if (i > 0) {
+ this.addInput()
+ }
+ this.inputTargets[i].querySelector('input').value = value
+ })
+ if (this.inputTargets.length === values.length) this.addInput()
+ }
+
+ handleInput(event) {
+ if (event.target.value.length > 0 && (this.lastInput === event.target || this.inputTargets.length === 1)) {
+ this.addInput()
+ }
+ }
+
+ handleKeyDown(event) {
+ if (event.key === 'Backspace' && event.target.value.length === 0 && this.inputTargets.length > 1) {
+ const inputContainer = event.target.closest('[data-multi-input-target="input"]')
+ this.removeInput(inputContainer)
+ }
+ }
+
+ removeInput(input) {
+ if (this.inputTargets.length > 1) {
+ input.remove()
+ }
+ }
+
+ addInput() {
+ const inputToClone = this.inputTargets[this.inputTargets.length - 1]
+ const newInputTemplate = inputToClone.cloneNode(true)
+ newInputTemplate.querySelector('input').value = ''
+ const newInputContainer = inputToClone.insertAdjacentElement('afterend', newInputTemplate)
+ const newInput = newInputContainer.querySelector('input')
+ this.lastInput = newInput
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/order_billing_address_controller.js b/admin/app/javascript/spree/admin/controllers/order_billing_address_controller.js
new file mode 100644
index 0000000000..43d9bdea48
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/order_billing_address_controller.js
@@ -0,0 +1,39 @@
+import { Controller } from '@hotwired/stimulus'
+
+export default class extends Controller {
+ connect() {
+ this.observer = new MutationObserver((mutations) => {
+ mutations.forEach((mutation) => {
+ if (mutation.target.required) {
+ mutation.target.disabled = true
+ }
+ })
+ })
+
+ this.hideForms()
+ const selectedBillingAddressType = this.element.querySelector('[name="billing_address_type"]:checked')
+
+ if (selectedBillingAddressType) {
+ const selectedBillingAddressTypeFormName = selectedBillingAddressType.dataset.orderBillingAddressFormNameParam
+ if (selectedBillingAddressTypeFormName) {
+ this.showForm({ params: { formName: selectedBillingAddressTypeFormName } })
+ }
+ }
+ }
+
+ showForm({ params: { formName } }) {
+ this.hideForms()
+ this.observer.disconnect()
+
+ const form = this.element.querySelector(`[data-form="${formName}"]`)
+ form.classList.remove('d-none')
+ form.querySelectorAll('input:required, select:required').forEach((input) => (input.disabled = false))
+ }
+
+ hideForms() {
+ this.observer.observe(this.element, { subtree: true, attributes: true, attributeFilter: ['required'] })
+
+ this.element.querySelectorAll('[data-form]').forEach((form) => form.classList.add('d-none'))
+ this.element.querySelectorAll('input:required, select:required').forEach((input) => (input.disabled = true))
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/page_builder_controller.js b/admin/app/javascript/spree/admin/controllers/page_builder_controller.js
new file mode 100644
index 0000000000..e2e3ffcac5
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/page_builder_controller.js
@@ -0,0 +1,314 @@
+import { Controller } from '@hotwired/stimulus'
+export default class extends Controller {
+ static targets = [
+ 'form',
+ 'fontForm',
+ 'previewContainer',
+ 'iframe',
+ 'sidebar',
+ 'sidebarIcon',
+ 'desktopButton',
+ 'mobileButton'
+ ]
+
+ static values = {
+ previewUrl: String
+ }
+
+ connect() {
+ this.resizeObserver = new ResizeObserver(() => {
+ this.removeOverlays()
+ this.initializeOverlays()
+ })
+ this.setResponsiveBreakpoint()
+ }
+
+ disconnect() {
+ this.resizeObserver.disconnect()
+ }
+
+ initialize() {
+ this.loadPreview()
+ }
+
+ loadPreview() {
+ this.iframeTarget.src = this.previewUrlValue
+ }
+
+ initializeVisualEditor() {
+ this.iframeDocument = this.iframeTarget.contentDocument
+ this.iframeWindow = this.iframeTarget.contentWindow
+
+ this.iframeDocument.addEventListener('turbo:frame-render', (event) => {
+ const url = new URL(event.detail.fetchResponse.response.url)
+ const activeOverlayId = url.searchParams.get('editor_id')
+
+ this.resizeObserver.observe(this.iframeDocument.body)
+
+ this.removeOverlays()
+ this.initializeOverlays(activeOverlayId)
+ })
+
+ this.iframeDocument.addEventListener('turbo:load', (event) => {
+ const url = new URL(event.detail.url)
+ const activeOverlayId = url.searchParams.get('editor_id')
+
+ this.resizeObserver.observe(this.iframeDocument.body)
+
+ this.removeOverlays()
+ this.initializeOverlays(activeOverlayId)
+ })
+
+ this.resizeObserver.observe(this.iframeDocument.body)
+
+ this.removeOverlays()
+ this.initializeOverlays()
+ }
+
+ removeOverlays() {
+ const overlays = this.iframeDocument.querySelectorAll('.editor-overlay')
+ overlays.forEach((el) => el.remove())
+ }
+
+ initializeOverlays(activeOverlayId = null) {
+ const elements = this.iframeDocument.querySelectorAll('[data-editor-id]')
+ elements.forEach((el) => this.initializeOverlay(el, activeOverlayId === el.dataset.editorId))
+ }
+
+ showSectionsSidebar() {
+ const button = document.getElementById('show-sections-sidebar')
+ if (button) {
+ button.click()
+ button.classList.remove('active')
+ }
+ }
+
+ initializeOverlay(el, isActive = false) {
+ const overlay = this.iframeDocument.createElement('div')
+ const id = el.dataset.editorId
+ const parentId = el.dataset.editorParentId || null // this is only present for blocks, not sections
+ const link = el.dataset.editorLink
+ overlay.classList.add('editor-overlay')
+ overlay.dataset.editorId = id
+
+ if (parentId) {
+ const parent = this.iframeDocument.querySelector(`[data-editor-id="${parentId}"]`)
+ if (parent) {
+ parent.parentNode.appendChild(overlay)
+ }
+ } else {
+ el.parentNode.appendChild(overlay)
+ }
+ let zIndex = 1088 // sections have 1088, blocks have 1089, links have 1090
+
+ switch (true) {
+ case id.startsWith('block'):
+ zIndex = 1089
+ break
+ case id.startsWith('link'):
+ zIndex = 1090
+ break
+ }
+
+ overlay.style.zIndex = zIndex
+
+ const { left, top } = el.getBoundingClientRect()
+ overlay.style.position = 'absolute'
+ overlay.style.top = `${top + this.iframeWindow.scrollY}px`
+ overlay.style.left = `${left + this.iframeWindow.scrollX}px`
+ overlay.style.width = `${el.offsetWidth}px`
+ overlay.style.height = `${el.offsetHeight}px`
+
+ overlay.addEventListener('click', (_event) => {
+ this.clearActiveOverlays()
+ this.iframeWindow.makeOverlayActive(id)
+ window.top.document.getElementById('page_sidebar').src = link
+ this.showSectionsSidebar()
+ })
+
+ const editorToolbar = document.getElementById('editor-toolbar-' + id)
+ if (editorToolbar) {
+ const overlayToolbar = this.iframeDocument.createElement('div')
+ overlayToolbar.classList.add('editor-overlay-toolbar')
+ overlayToolbar.innerHTML = editorToolbar.innerHTML
+ overlay.appendChild(overlayToolbar)
+
+ const toolbarHigher = overlayToolbar.querySelector(
+ '.editor-toolbar-higher'
+ )
+ const toolbarLower = overlayToolbar.querySelector('.editor-toolbar-lower')
+ const toolbarEdit = overlayToolbar.querySelector('.editor-toolbar-edit')
+ const toolbarDelete = overlayToolbar.querySelector(
+ '.editor-toolbar-delete'
+ )
+
+ if (toolbarHigher) {
+ toolbarHigher.addEventListener('click', (event) => {
+ event.stopPropagation()
+ const moveButton = document.getElementById(
+ 'editor-toolbar-higher-' + id
+ )
+ if (moveButton) moveButton.click()
+
+ // this is only needed for sections, not blocks
+ if (!parentId) {
+ const turboFrame = el.parentNode
+ if (turboFrame) {
+ turboFrame.previousSibling.before(turboFrame)
+ this.iframeWindow.scrollToOverlay(overlay)
+ }
+ } else {
+ el.parentNode.insertBefore(el, el.previousSibling)
+ }
+ this.removeOverlays()
+ this.initializeOverlays()
+ })
+ }
+ if (toolbarLower) {
+ toolbarLower.addEventListener('click', (event) => {
+ event.stopPropagation()
+ const moveButton = document.getElementById(
+ 'editor-toolbar-lower-' + id
+ )
+ if (moveButton) moveButton.click()
+
+ // this is only needed for sections, not blocks
+ if (!parentId) {
+ const turboFrame = el.parentNode
+ if (turboFrame) {
+ turboFrame.nextSibling.after(turboFrame)
+ this.iframeWindow.scrollToOverlay(overlay)
+ }
+ } else {
+ el.parentNode.insertBefore(el.nextSibling, el)
+ }
+ this.removeOverlays()
+ this.initializeOverlays()
+ })
+ }
+ if (toolbarEdit) {
+ toolbarEdit.addEventListener('click', (event) => {
+ event.stopPropagation()
+ this.clearActiveOverlays()
+ this.iframeWindow.makeOverlayActive(id)
+ window.top.document.getElementById('page_sidebar').src = link
+ this.showSectionsSidebar()
+ this.showSidebarMobile()
+ })
+ }
+ if (toolbarDelete) {
+ toolbarDelete.addEventListener('click', (event) => {
+ event.stopPropagation()
+ const deleteButton = document.getElementById(
+ 'editor-toolbar-delete-' + id
+ )
+ if (deleteButton) deleteButton.click()
+ })
+ }
+
+ if (isActive) this.iframeWindow.makeOverlayActive(id)
+ }
+
+ overlay.addEventListener('mouseenter', (_event) => {
+ const sidebarElement = document.querySelector(
+ '[data-page-builder-editor-id-param="' + id + '"]'
+ )
+ if (sidebarElement) sidebarElement.classList.add('hover')
+ })
+ overlay.addEventListener('mouseout', (_event) => {
+ const sidebarElement = document.querySelector(
+ '[data-page-builder-editor-id-param="' + id + '"]'
+ )
+ if (sidebarElement) sidebarElement.classList.remove('hover')
+ })
+ }
+
+ clearActiveOverlays(event) {
+ if (event?.currentTarget?.classList.contains('back')) {
+ this.hideSidebarMobile()
+ }
+
+ this.iframeDocument
+ .querySelectorAll('.editor-overlay')
+ .forEach((overlayEl) => {
+ overlayEl.classList.remove('editor-overlay-active')
+ overlayEl.classList.remove('editor-overlay-hover')
+ })
+ }
+
+ makeOverlayActive(event) {
+ this.showSectionsSidebar() // making sure the page sidebar is open
+ const editorId = event.params.editorId
+ this.clearActiveOverlays()
+ this.iframeWindow.makeOverlayActive(editorId)
+ }
+
+ toggleHighlightElement(event) {
+ const editorId = event.params.editorId
+ if (this.iframeWindow) this.iframeWindow.toggleHighlightElement(editorId)
+ }
+
+ refreshPreview(_event) {
+ // save the preview and re-render iframe
+ this.formTarget.requestSubmit()
+ }
+
+ refreshFontPreview(_event) {
+ // save the preview and re-render iframe
+ this.fontFormTarget.requestSubmit()
+ }
+
+ setResponsiveBreakpoint(event) {
+ event?.preventDefault()
+
+ const view = event ? event?.params.breakpoint : sessionStorage.getItem('breakpoint');
+
+ if (view === 'desktop') {
+ sessionStorage.setItem('breakpoint', 'desktop');
+
+ this.previewContainerTarget.classList.remove('mobileLiveView')
+ this.previewContainerTarget.classList.add('desktopLiveView')
+ this.desktopButtonTarget.classList.add('active')
+ this.mobileButtonTarget.classList.remove('active')
+ } else {
+ sessionStorage.setItem('breakpoint', 'mobile');
+
+ this.previewContainerTarget.classList.remove('desktopLiveView')
+ this.previewContainerTarget.classList.add('mobileLiveView')
+ this.desktopButtonTarget.classList.remove('active')
+ this.mobileButtonTarget.classList.add('active')
+ }
+ }
+
+ addSection(event) {
+ event.stopPropagation()
+
+ this.showSectionsSidebar()
+
+ window.top.document.getElementById(
+ 'page_sidebar'
+ ).src = `${window.top.location.origin}/admin/page_previews/id/sections/new`
+
+ this.showSidebarMobile()
+ }
+
+ showSidebarMobile(event) {
+ if (event?.currentTarget?.classList.contains('from-hamburger')) {
+ ;[...event.currentTarget.parentNode.children].forEach((el) => {
+ if (event.currentTarget !== el) el.classList.remove('active')
+ })
+ document.querySelector('.mobile-hamburger').click()
+ }
+
+ document.body.classList.add('mobile_sidebar_open')
+ }
+
+ hideSidebarMobile() {
+ document.body.classList.remove('mobile_sidebar_open')
+ }
+
+ deleteCallback() {
+ this.removeOverlays()
+ this.initializeOverlays()
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/password_toggle_controller.js b/admin/app/javascript/spree/admin/controllers/password_toggle_controller.js
new file mode 100644
index 0000000000..cb04af7131
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/password_toggle_controller.js
@@ -0,0 +1,14 @@
+import { Controller } from "@hotwired/stimulus"
+
+export default class extends Controller {
+ static targets = ["unhide"]
+
+ password(e) {
+ if (this.unhideTarget.type === "password") {
+ this.unhideTarget.type = "text"
+ } else {
+ this.unhideTarget.type = "password"
+ }
+ }
+}
+
diff --git a/admin/app/javascript/spree/admin/controllers/product_form_controller.js b/admin/app/javascript/spree/admin/controllers/product_form_controller.js
new file mode 100644
index 0000000000..8cbc9db31e
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/product_form_controller.js
@@ -0,0 +1,70 @@
+import { Controller } from '@hotwired/stimulus'
+
+export default class extends Controller {
+ static targets = [
+ 'trackInventoryCheckbox',
+ 'quantityForm',
+ 'availableOn',
+ 'makeActiveAt',
+ 'discontinueOn',
+ 'status',
+ 'pricesForm'
+ ]
+
+ static values = {
+ hasVariants: Boolean
+ }
+
+ toggleQuantityTracked() {
+ this.toggleQuantityFormVisibility()
+
+ this.dispatch('toggle-quantity-tracked')
+ }
+
+ hasVariantsValueChanged() {
+ this.toggleQuantityFormVisibility()
+ this.togglePricesFormVisibility()
+ }
+
+ switchAvailabilityDatesFields(event) {
+ let status = event.target.value
+ if (status === 'draft') {
+ this.show(this.availableOnTarget)
+ this.show(this.makeActiveAtTarget)
+ } else if (status === 'active') {
+ this.show(this.availableOnTarget)
+ this.hide(this.makeActiveAtTarget)
+ } else {
+ this.hide(this.availableOnTarget)
+ this.hide(this.makeActiveAtTarget)
+ }
+ }
+
+ show(element) {
+ element.classList.remove('d-none')
+ }
+
+ hide(element) {
+ element.classList.add('d-none')
+ }
+
+ toggleQuantityFormVisibility() {
+ if (this.hasQuantityFormTarget) {
+ if (!this.hasVariantsValue && this.trackInventoryCheckboxTarget.checked) {
+ this.quantityFormTarget.classList.remove('d-none')
+ } else {
+ this.quantityFormTarget.classList.add('d-none')
+ }
+ }
+ }
+
+ togglePricesFormVisibility() {
+ if (this.hasPricesFormTarget) {
+ if (this.hasVariantsValue) {
+ this.pricesFormTarget.classList.add('d-none')
+ } else {
+ this.pricesFormTarget.classList.remove('d-none')
+ }
+ }
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/range_input_controller.js b/admin/app/javascript/spree/admin/controllers/range_input_controller.js
new file mode 100644
index 0000000000..9c623eb5da
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/range_input_controller.js
@@ -0,0 +1,9 @@
+import { Controller } from "@hotwired/stimulus"
+
+export default class extends Controller {
+ static targets = [ 'input', 'preview' ]
+
+ updatePreview() {
+ this.previewTarget.innerHTML = this.inputTarget.value
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/replace_controller.js b/admin/app/javascript/spree/admin/controllers/replace_controller.js
new file mode 100644
index 0000000000..64c60381dc
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/replace_controller.js
@@ -0,0 +1,15 @@
+import { Controller } from "@hotwired/stimulus"
+
+export default class extends Controller {
+ static targets = [ 'from', 'to' ]
+
+ replace() {
+ this.fromTarget.classList.add('d-none')
+ this.toTarget.classList.remove('d-none')
+ }
+
+ revert() {
+ this.fromTarget.classList.remove('d-none')
+ this.toTarget.classList.add('d-none')
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/row_link_controller.js b/admin/app/javascript/spree/admin/controllers/row_link_controller.js
new file mode 100644
index 0000000000..87ba349b68
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/row_link_controller.js
@@ -0,0 +1,18 @@
+import { Controller } from "@hotwired/stimulus"
+
+// Connects to data-controller="row-link"
+export default class extends Controller {
+ static targets = ["link"]
+
+ openLink(event) {
+ if (event.target.tagName === 'A') return
+
+ event.preventDefault()
+ if (this.linkTarget.target === '_blank') {
+ window.open(this.linkTarget.href, '_blank')
+ return
+ }
+
+ window.Turbo.visit(this.linkTarget.href, { action: "advance" })
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/rule_form_controller.js b/admin/app/javascript/spree/admin/controllers/rule_form_controller.js
new file mode 100644
index 0000000000..d939cd14d7
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/rule_form_controller.js
@@ -0,0 +1,17 @@
+import { Controller } from "@hotwired/stimulus"
+
+export default class extends Controller {
+ static targets = ['value', 'template']
+
+ replace(event) {
+ const inputString = event.target.value;
+ const parts = inputString.split("::");
+ const lastPart = parts[parts.length - 1];
+
+ const template = this.templateTargets.find((template) => template.id == `rule-form-template-${lastPart}`)
+
+ if (template) {
+ this.valueTarget.innerHTML = template.innerHTML
+ }
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/search_picker_controller.js b/admin/app/javascript/spree/admin/controllers/search_picker_controller.js
new file mode 100644
index 0000000000..9e0ebcebe5
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/search_picker_controller.js
@@ -0,0 +1,45 @@
+import { Controller } from '@hotwired/stimulus'
+
+export default class extends Controller {
+ static targets = ['checkbox', 'submit', 'search', 'results']
+
+ // hack needed for this to work with Bootstrap modals and turbo frames
+ connect() {
+ setTimeout(() => {
+ this.searchTarget.focus()
+ }, 200)
+ }
+
+ toggle(event) {
+ if (event.target.type == 'checkbox' || event.target.type == 'radio') {
+ this.refresh()
+ } else {
+ const input =
+ event.target.querySelector('input[type="checkbox"]') || event.target.querySelector('input[type="radio"]')
+ if (input?.disabled) return
+
+ switch (input?.type) {
+ case 'checkbox':
+ input.toggleAttribute('checked')
+ case 'radio':
+ if (input.disabled) break
+ input.checked = true
+ }
+ this.refresh()
+ }
+ }
+
+ refresh() {
+ let checked = this.checkboxTargets.filter((checkbox) => checkbox.checked)
+ if (checked.length > 0) {
+ this.submitTarget.disabled = false
+ } else {
+ this.submitTarget.disabled = true
+ }
+ }
+
+ closeAndClear() {
+ this.searchTarget.value = ''
+ this.resultsTarget.innerHTML = ''
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/section_form_controller.js b/admin/app/javascript/spree/admin/controllers/section_form_controller.js
new file mode 100644
index 0000000000..9478c29647
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/section_form_controller.js
@@ -0,0 +1,14 @@
+import { Controller } from "@hotwired/stimulus"
+
+export default class extends Controller {
+ static targets = [
+ 'form',
+ 'type'
+ ]
+
+ addSection(event) {
+ event.preventDefault()
+ this.typeTarget.value = event.params.type
+ this.formTarget.requestSubmit()
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/select_controller.js b/admin/app/javascript/spree/admin/controllers/select_controller.js
new file mode 100644
index 0000000000..49182eb00b
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/select_controller.js
@@ -0,0 +1,117 @@
+import { Controller } from "@hotwired/stimulus"
+import TomSelect from 'tom-select/dist/esm/tom-select.complete.js';
+import { get } from '@rails/request.js'
+
+export default class extends Controller {
+ static values = {
+ url: String, // remote URL to fetch options
+ options: Array, // JSON array of options
+ activeOption: String, // array or single value of selected options,
+ emptyOption: { type: String, default: null }, // empty option put at the top of the list
+ multiple: { type: Boolean, default: false },
+ valueField: { type: String, default: 'id' },
+ searchField: { type: String, default: 'name' },
+ labelField: { type: String, default: 'name' },
+ sortField: { type: String, default: 'name' },
+ create: { type: Boolean, default: false },
+ remoteSearch: { type: Boolean, default: false }, // this will wait for search input before fetching options
+ remoteSearchParams: Object,
+ remoteSearchActiveOption: String
+ }
+ static targets = [ "input" ]
+
+ async connect() {
+ this.tomSelectedInitializedEvent = new CustomEvent('tomSelectInitialized', { bubbles: true} )
+ if (this.urlValue) {
+ if (this.remoteSearchValue) {
+ this.initTomSelect()
+ } else {
+ const response = await get(this.urlValue, { contentType: 'application/json' })
+
+ if (response.ok) {
+ const options = await response.json
+ this.initTomSelect(options)
+ }
+ }
+ } else {
+ this.initTomSelect(this.optionsValue)
+ }
+ }
+
+ disconnect() {
+ if (this.select) {
+ this.select.destroy()
+ }
+ }
+
+ initTomSelect(options = []) {
+ const settings = {
+ maxOptions: 1500,
+ lockOptgroupOrder: true,
+ valueField: this.valueFieldValue,
+ searchField: this.searchFieldValue,
+ labelField: this.labelFieldValue,
+ sortField: this.sortFieldValue,
+ create: this.createValue,
+ onInitialize: () => {
+ this.inputTarget.dispatchEvent(this.tomSelectedInitializedEvent)
+ }
+ }
+
+ if (this.urlValue && this.remoteSearchValue) {
+ const loadUrl = this.urlValue
+ const searchParams = this.remoteSearchParamsValue
+
+ settings.load = async function(query, callback) {
+ const params = new URLSearchParams({ q: query, ...searchParams })
+ const url = loadUrl + '?' + params.toString()
+
+ const response = await get(url, { contentType: 'application/json' })
+
+ if (response.ok) {
+ const options = await response.json
+ options.length > 0 ? callback(options) : callback([])
+ } else {
+ callback()
+ }
+ }
+
+ if (this.remoteSearchActiveOptionValue) {
+ const items = JSON.parse(this.remoteSearchActiveOptionValue)
+ settings.options = items
+ settings.items = items.map(item => item.id)
+ }
+ }
+
+ if (options.length > 0) {
+ if (this.emptyOptionValue) {
+ let groupedOptions = options.map(function (option) {
+ option.group = 'non-empty'
+ return option
+ })
+
+ groupedOptions.unshift({ group: 'empty', id: ' ', name: this.emptyOptionValue })
+
+ settings.options = groupedOptions
+ settings.optgroupField = 'group'
+ settings.optgroups = [
+ { value: 'empty', label: '' },
+ { value: 'non-empty', label: '' }
+ ]
+ } else {
+ settings.options = options
+ }
+ }
+
+ if (this.multipleValue) {
+ settings.maxItems = null
+ settings.plugins = ['remove_button']
+ if (this.activeOptionValue) settings.items = JSON.parse(this.activeOptionValue)
+ } else {
+ if (this.activeOptionValue) settings.items = [this.activeOptionValue]
+ }
+
+ this.inputTarget.classList.remove('d-none')
+ this.select = new TomSelect(this.inputTarget, settings)
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/seo_form_controller.js b/admin/app/javascript/spree/admin/controllers/seo_form_controller.js
new file mode 100644
index 0000000000..8910eec43f
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/seo_form_controller.js
@@ -0,0 +1,116 @@
+import { Controller } from '@hotwired/stimulus'
+
+export default class extends Controller {
+ static targets = [
+ 'titlePreview',
+ 'slugPreview',
+ 'descriptionPreview',
+ 'preview',
+ 'inputsContainer',
+ 'titleInput',
+ 'descriptionInput',
+ 'slugInput',
+ 'sourceTitleInput',
+ 'sourceDescriptionInput',
+ 'sourceExcerptInput',
+ 'placeholder'
+ ]
+
+ static values = {
+ editor: { type: String, default: 'trix' }
+ }
+
+ connect() {
+ this.sourceTitleInputTarget.addEventListener('input', this.updatePreviews)
+
+ if (this.editorValue == 'tinymce') {
+ this.connectTinymceEditor()
+ } else {
+ this.connectTrixEditors()
+ }
+ }
+
+ connectTrixEditors() {
+ document.addEventListener("trix-initialize", () => {
+ if (this.hasSourceDescriptionInputTarget) {
+ this.sourceDescriptionEditorTarget = this.sourceDescriptionInputTarget.editor
+ this.sourceDescriptionInputTarget.addEventListener('trix-change', this.updatePreviews)
+
+ if (this.hasSourceExcerptInputTarget) {
+ this.sourceExcerptEditorTarget = this.sourceExcerptInputTarget.editor
+ this.sourceExcerptInputTarget.addEventListener('trix-change', this.updatePreviews)
+ }
+ }
+
+ this.updatePreviews()
+ })
+ }
+
+ connectTinymceEditor() {
+ const descriptionEditorId = this.sourceDescriptionInputTarget.id
+
+ tinymce.on('AddEditor', (e) => {
+ if (e.editor.id !== descriptionEditorId) return
+ this.sourceDescriptionEditorTarget = tinymce.get(descriptionEditorId)
+ this.sourceDescriptionEditorTarget.on('input', this.updatePreviews)
+ this.sourceDescriptionEditorTarget.on('init', this.updatePreviews)
+ })
+ }
+
+ updatePreviews = () => {
+ if (this.metaTitle.trim().length === 0 && this.metaDescription.trim().length === 0) {
+ this.titlePreviewTarget.textContent = ''
+ this.slugPreviewTarget.textContent = ''
+ this.descriptionPreviewTarget.textContent = ''
+
+ this.previewTarget.classList.add('d-none')
+ this.placeholderTarget.classList.remove('d-none')
+
+ return
+ }
+
+ this.previewTarget.classList.remove('d-none')
+ this.placeholderTarget.classList.add('d-none')
+
+ this.titlePreviewTarget.textContent = this.metaTitle
+ this.slugPreviewTarget.textContent = this.slugInputTarget.value
+ this.descriptionPreviewTarget.textContent = this.metaDescription
+ }
+
+ toggleInputs() {
+ this.inputsContainerTarget.classList.toggle('d-none')
+ }
+
+ get metaTitle() {
+ return this.titleInputTarget.value.length ? this.titleInputTarget.value : this.sourceTitleInputTarget.value
+ }
+
+ get metaDescription() {
+ const metaDescription = this.descriptionInputTarget.value.length
+ ? this.descriptionInputTarget.value
+ : this.sourceTextEditorContent
+
+ if (metaDescription.length > 320) {
+ return metaDescription.substring(0, 320) + '...'
+ }
+
+ return metaDescription
+ }
+
+ get sourceTextEditorContent() {
+ if (!this.hasSourceDescriptionInputTarget) return ''
+
+ if (this.editorValue == 'tinymce') {
+ return this.sourceDescriptionEditorTarget.getContent({ format: 'text' })
+ } else {
+ const descriptionEditorContent = this.sourceDescriptionEditorTarget.getDocument().toString()
+
+ if (this.sourceExcerptEditorTarget) {
+ const excerptEditorDocument = this.sourceExcerptEditorTarget.getDocument()
+ return excerptEditorDocument.isEmpty() ? descriptionEditorContent : excerptEditorDocument.toString()
+ } else {
+ return descriptionEditorContent
+ }
+ }
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/slug_form_controller.js b/admin/app/javascript/spree/admin/controllers/slug_form_controller.js
new file mode 100644
index 0000000000..ff237fd322
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/slug_form_controller.js
@@ -0,0 +1,17 @@
+import { Controller } from '@hotwired/stimulus'
+
+export default class extends Controller {
+ static targets = [
+ 'name',
+ 'url',
+ ]
+
+ updateUrlFromName() {
+ const name = this.nameTarget.value
+ const url = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)+/g, '')
+ this.urlTarget.value = url
+
+ // TODO: do ajax call and check if url is available
+ // if not, append a number to the end to make it unique
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/sortable_tree_controller.js b/admin/app/javascript/spree/admin/controllers/sortable_tree_controller.js
new file mode 100644
index 0000000000..d19310c153
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/sortable_tree_controller.js
@@ -0,0 +1,55 @@
+import { Controller } from "@hotwired/stimulus"
+import { Sortable } from "sortablejs"
+import { put } from '@rails/request.js'
+
+export default class extends Controller {
+ static values = { handle: String }
+
+ connect() {
+ const itemSortable = {
+ ...this.options
+ }
+
+ let containers = null
+ containers = this.element.querySelectorAll("[data-sortable-tree-parent-id-value]")
+
+ for (let i = 0; i < containers.length; i++) {
+ new Sortable(containers[i], itemSortable)
+ }
+ }
+
+ async end({ item, newIndex, to }) {
+ if (!item.dataset.sortableTreeUpdateUrlValue) return
+
+ const data = {
+ [item.dataset.sortableTreeResourceNameValue]: {
+ new_parent_id: to.dataset.sortableTreeParentIdValue,
+ new_position_idx: newIndex
+ }
+ }
+
+ const response = await put(item.dataset.sortableTreeUpdateUrlValue, { body: data, responseKind: 'json' })
+
+ if (!response.ok) {
+ alert("This move could not be saved.")
+ }
+ }
+
+ get options() {
+ return {
+ group: {
+ name: "sortable-tree",
+ pull: true,
+ put: true
+ },
+ handle: this.handleValue || undefined,
+ swapThreshold: 0.5,
+ emptyInsertThreshold: 8,
+ dragClass: "item-dragged",
+ draggable: ".draggable",
+ animation: 350,
+ forceFallback: false,
+ onEnd: this.end
+ }
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/stock_transfer_controller.js b/admin/app/javascript/spree/admin/controllers/stock_transfer_controller.js
new file mode 100644
index 0000000000..b0576dee25
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/stock_transfer_controller.js
@@ -0,0 +1,87 @@
+import NestedForm from '@stimulus-components/rails-nested-form'
+
+export default class extends NestedForm {
+ static targets = [
+ 'target',
+ 'template',
+ 'sourceLocationId',
+ 'destinationLocationId',
+ 'sourceInput',
+ 'destinationInput',
+ 'newVariantAddButton',
+ 'newVariantStockLocationId',
+ 'newVariantOmitIds'
+ ]
+
+ updateSourceLocation({ target: { value } }) {
+ this.newVariantStockLocationIdTarget.value = value
+ this.sourceInputTargets.forEach((input) => {
+ input.value = value
+ })
+ }
+
+ updateDestinationLocation({ target: { value } }) {
+ const variantAddButtonTooltip = this.newVariantAddButtonTarget.querySelector('.with-tip')
+
+ if (value != '') {
+ this.newVariantAddButtonTarget.removeAttribute('disabled')
+
+ this.variantAddButtonTooltipTitle = variantAddButtonTooltip.getAttribute('data-original-title')
+ variantAddButtonTooltip.setAttribute('data-original-title', '')
+ } else {
+ this.newVariantAddButtonTarget.setAttribute('disabled', '')
+
+ if (this.variantAddButtonTooltipTitle)
+ variantAddButtonTooltip.setAttribute('data-original-title', this.variantAddButtonTooltipTitle)
+ }
+
+ this.destinationInputTargets.forEach((input) => {
+ input.value = value
+ })
+ }
+
+ updateQuantity({
+ target: {
+ value,
+ dataset: { variantId }
+ }
+ }) {
+ this.element.querySelector(`[data-source-movement]:has(input[value='${variantId}']) [data-source-quantity]`).value =
+ -parseInt(value)
+ }
+
+ add(e) {
+ e.preventDefault()
+
+ const selectedVariant = document.querySelector('input[name="stock_transfer[variant_id]"]:checked')
+ const selectedVariantId = selectedVariant.value
+ const variantImage = selectedVariant.closest('.search-picker__option').querySelector('.variant-image')
+ const variantInfo = selectedVariant.closest('.search-picker__option').querySelector('.variant-info')
+ const variantName = variantInfo.querySelector('.variant-name')
+ variantName.innerHTML = variantName.innerText
+ this.newVariantOmitIdsTarget.value = [this.newVariantOmitIdsTarget.value, selectedVariantId]
+ .filter((v) => v?.length)
+ .join(',')
+
+ const content = this.templateTarget.innerHTML
+ .replace(/NEW_RECORD/g, new Date().getTime().toString())
+ .replace(/NEW_RECORD2/g, new Date().getTime().toString())
+ .replace(/VARIANT_ID/g, selectedVariantId)
+ .replace(/SOURCE_ID/g, this.sourceLocationIdTarget.value)
+ .replace(/DESTINATION_ID/g, this.destinationLocationIdTarget.value)
+ .replace(/VARIANT_IMAGE/g, variantImage.innerHTML)
+ .replace(/VARIANT_INFO/g, variantInfo.innerHTML)
+
+ this.targetTarget.insertAdjacentHTML('beforebegin', content)
+
+ const event = new CustomEvent('rails-nested-form:add', { bubbles: true })
+ this.element.dispatchEvent(event)
+ }
+
+ remove(e) {
+ super.remove(e)
+ const variantId = e.target.dataset.variantId
+ this.element.querySelector(`[data-source-movement]:has(input[value='${variantId}'])`).remove()
+ this.newVariantOmitIdsTarget.value = this.newVariantOmitIdsTarget.value.split(',').filter((v) => v !== variantId).join(',')
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/store_form_controller.js b/admin/app/javascript/spree/admin/controllers/store_form_controller.js
new file mode 100644
index 0000000000..fc0482a305
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/store_form_controller.js
@@ -0,0 +1,16 @@
+import { Controller } from '@hotwired/stimulus'
+import countryCurrency from '../../helpers/country_currency'
+export default class extends Controller {
+ static targets = ['currency']
+
+ updateCurrency(e) {
+ const selectController = this.application.getControllerForElementAndIdentifier(
+ this.currencyTarget,
+ 'autocomplete-select'
+ )
+
+ if (selectController?.select && countryCurrency[e.target.value]) {
+ selectController.select.setValue(countryCurrency[e.target.value])
+ }
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/unit_system_controller.js b/admin/app/javascript/spree/admin/controllers/unit_system_controller.js
new file mode 100644
index 0000000000..b20037e857
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/unit_system_controller.js
@@ -0,0 +1,27 @@
+import { Controller } from "@hotwired/stimulus"
+
+export default class extends Controller {
+ static targets = ["body", "weightUnit"]
+
+ unitSystemHandler(){
+ let unitSystemByMeasurement = {
+ "metric": [
+ ["Kilogram (kg)", "kg"],
+ ["Gram (g)", "g"],
+ ],
+ "imperial": [
+ ["Pound (lb)", "lb"],
+ ["Ounce (oz)", "oz"]
+ ]
+ }
+ let unitSystem = this.bodyTarget.value
+ let weightUnits = unitSystemByMeasurement[unitSystem]
+ let reqUnits = "";
+
+ weightUnits.forEach((unit) => {
+ reqUnits += "<option value=" + unit[1] + ">" + unit[0] + "</option>";
+ })
+
+ this.weightUnitTarget.innerHTML = reqUnits
+ }
+}
\ No newline at end of file
diff --git a/admin/app/javascript/spree/admin/controllers/variants_form_controller.js b/admin/app/javascript/spree/admin/controllers/variants_form_controller.js
new file mode 100644
index 0000000000..1b90564edd
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/variants_form_controller.js
@@ -0,0 +1,971 @@
+import CheckboxSelectAll from 'stimulus-checkbox-select-all'
+import { Sortable } from 'sortablejs'
+
+export default class extends CheckboxSelectAll {
+ static targets = [
+ 'optionTemplate',
+ 'optionValueTemplate',
+ 'optionsContainer',
+ 'optionFormTemplate',
+ 'newOptionForm',
+ 'newOptionValuesInput',
+ 'newOptionNameInput',
+ 'newOptionButton',
+ 'newOptionButtonLabel',
+ 'option',
+ 'variantsContainer',
+ 'variantTemplate',
+ 'variantsTable',
+ 'deleteButton',
+ 'checkboxAll',
+ 'checkbox',
+ 'stockItemsCount'
+ ]
+
+ static values = {
+ productId: String,
+ options: Object,
+ variants: Array,
+ stock: Object,
+ prices: Object,
+ currentCurrency: String,
+ currencies: Array,
+ variantIds: Object,
+ currentStockLocationId: String,
+ stockLocations: Array
+ }
+
+ connect() {
+ super.connect()
+ this.optionNameOptions = this.newOptionNameInputTarget.options
+ this.sortable = new Sortable(this.optionsContainerTarget, {
+ group: 'options',
+ animation: 150,
+ onEnd: this.reorderOptions.bind(this),
+ handle: '.draggable',
+ filter: '.color-option',
+ draggable: '.options-creator__option'
+ })
+ this.ignoredVariants = new Set()
+ this.productFormController = this.application.getControllerForElementAndIdentifier(
+ this.element.closest('[data-controller*="product-form"]'),
+ 'product-form'
+ )
+
+ // Set ignoredVariants to all the variants that are not on the server
+ const existingVariantsOnServer = Object.keys(this.variantIdsValue)
+ if (existingVariantsOnServer.length > 0) {
+ this.ignoredVariants = new Set(
+ this.variantsValue
+ .map((variant) => variant.internalName)
+ .filter((internalName) => !existingVariantsOnServer.includes(internalName))
+ )
+ }
+ }
+
+ toggleQuantityTracked() {
+ this.element.querySelectorAll('.column-quantity').forEach((el) => el.classList.toggle('d-none'))
+
+ this.variantTemplateTarget.content
+ .querySelectorAll('.column-quantity')
+ .forEach((el) => el.classList.toggle('d-none'))
+ }
+
+ toggle(e) {
+ super.toggle(e)
+ this.toggleDeleteButton()
+ }
+
+ refresh() {
+ super.refresh()
+
+ // Set indeterminate state for parent checkboxes
+ this.element.querySelectorAll('input[id^="parent_checkbox_"]').forEach((checkbox) => {
+ checkbox.indeterminate = false
+ })
+
+ // Set checked state for parent checkboxes based on the amount of checked children
+ const firstOptionKeys = new Set(this.checked.map((c) => c.value.split('/')[0]))
+ firstOptionKeys.forEach((key) => {
+ const parentCheckbox = this.element.querySelector(`input[id="parent_checkbox_${key}"]`)
+ if (!parentCheckbox) return
+
+ const childCheckboxes = Array.from(this.element.querySelectorAll(`input[value^="${key}/"]`))
+ const allChildrenChecked = childCheckboxes.length > 0 && childCheckboxes.every((c) => c.checked)
+
+ parentCheckbox.checked = allChildrenChecked
+ parentCheckbox.indeterminate = !allChildrenChecked && childCheckboxes.some((c) => c.checked)
+ })
+
+ this.toggleDeleteButton()
+ }
+
+ toggleDeleteButton() {
+ if (this.checked.length > 0) {
+ this.deleteButtonTarget.classList.remove('d-none')
+ } else {
+ this.deleteButtonTarget.classList.add('d-none')
+ }
+ }
+
+ deleteSelected() {
+ const newStockValue = this.stockValue
+ const newPricesValue = this.pricesValue
+ this.checked.forEach((checkbox) => {
+ const internalName = checkbox.value
+
+ this.ignoredVariants.add(internalName)
+ const variant = this.variantsContainerTarget.querySelector(`[data-variant-name="${internalName}"]`)
+
+ const nestingLevel = internalName.split('/').length
+ if (nestingLevel === 1) {
+ const firstOptionKey = Object.keys(this.optionsValue)[0]
+ const newOptionValues = this.optionsValue[firstOptionKey].values.filter((value) => value !== internalName)
+ if (newOptionValues.length === 0) {
+ const newOptionsValue = this.optionsValue
+ delete newOptionsValue[firstOptionKey]
+ this.optionsValue = newOptionsValue
+ this.optionsContainerTarget.querySelector(`#option-${firstOptionKey}`).remove()
+ } else {
+ this.optionsValue = {
+ ...this.optionsValue,
+ [firstOptionKey]: {
+ ...this.optionsValue[firstOptionKey],
+ values: newOptionValues
+ }
+ }
+
+ this.optionsContainerTarget.querySelector(`#option-${firstOptionKey} [data-name="${internalName}"]`).remove()
+ }
+ checkbox.checked = false
+ }
+
+ delete newStockValue[internalName]
+ delete newPricesValue[internalName]
+ variant.remove()
+ })
+
+ this.stockValue = newStockValue
+ this.pricesValue = newPricesValue
+
+ this.checkboxAllTarget.checked = false
+ this.refresh()
+ this.refreshParentInputs()
+ }
+
+ reorderOptions(event) {
+ const optionId = event.item.id.replace('option-', '')
+ const newPosition = event.newDraggableIndex + 1
+ const oldPosition = event.oldDraggableIndex + 1
+ const options = Object.keys(this.optionsValue).reduce((acc, key) => {
+ if (key === optionId) {
+ acc[key] = { ...this.optionsValue[key], position: newPosition }
+ } else if (newPosition < oldPosition) {
+ if (this.optionsValue[key].position >= newPosition && this.optionsValue[key].position < oldPosition) {
+ acc[key] = { ...this.optionsValue[key], position: this.optionsValue[key].position + 1 }
+ } else {
+ acc[key] = this.optionsValue[key]
+ }
+ } else {
+ if (this.optionsValue[key].position > oldPosition && this.optionsValue[key].position <= newPosition) {
+ acc[key] = { ...this.optionsValue[key], position: this.optionsValue[key].position - 1 }
+ } else {
+ acc[key] = this.optionsValue[key]
+ }
+ }
+ return acc
+ }, {})
+ this.optionsValue = options
+ }
+
+ updateShopLocationCountOnHand() {
+ const inputs = this.variantsContainerTarget.querySelectorAll(
+ `input[data-slot='[stock_items_attributes][${this.currentStockLocationIdValue}][count_on_hand]_input'][name$='[count_on_hand]']`
+ )
+
+ const sum = Array.from(inputs).reduce((acc, input) => {
+ if (input.value === '') return acc
+ return acc + parseInt(input.value)
+ }, 0)
+ this.stockItemsCountTarget.textContent = sum
+ }
+
+ updateStockLocationId({ target: { value: newStockLocationId } }) {
+ this.currentStockLocationIdValue = newStockLocationId
+ this.stockLocationsValue.forEach((stockLocationId) => {
+ this.variantsContainerTarget
+ .querySelectorAll(`input[data-slot='[stock_items_attributes][${stockLocationId}][count_on_hand]_input']`)
+ .forEach((el) => {
+ if (stockLocationId === newStockLocationId) {
+ el.classList.remove('d-none')
+ el.classList.add('d-block')
+ } else {
+ el.classList.remove('d-block')
+ el.classList.add('d-none')
+ }
+ })
+ })
+ this.updateShopLocationCountOnHand()
+ }
+
+ updateCurrency({ target: { value: newCurrency } }) {
+ this.currentCurrencyValue = newCurrency
+ this.currenciesValue.forEach((currency) => {
+ this.variantsContainerTarget
+ .querySelectorAll(
+ `.price-input-container:has(input[data-slot="[prices_attributes][${currency}][amount]_input"])`
+ )
+ .forEach((el) => {
+ if (currency === newCurrency) {
+ el.classList.remove('d-none')
+ el.classList.add('d-flex')
+ } else {
+ el.classList.remove('d-flex')
+ el.classList.add('d-none')
+ }
+ })
+ })
+ }
+
+ optionsValueChanged(value, previousValue) {
+ if (this.hasNewOptionButtonTarget) {
+ const label = this.newOptionButtonLabelTarget
+
+ if (Object.values(value).filter(Boolean).length) {
+ label.textContent = label.dataset.hasOptionsText
+ } else {
+ label.textContent = label.dataset.noOptionsText
+ }
+ }
+ this.refreshTomSelect()
+ this.variantsValue = this.generateVariants(value)
+
+ // We want to clear the ignoredVariants when the options change
+ if (previousValue && Object.keys(previousValue).length === 0) return
+ this.ignoredVariants = new Set()
+ }
+
+ calculateVariantName(variant, keys, i) {
+ let name = ''
+ let internalName = name
+ if (i === 0) {
+ name = variant[keys[i]]
+ internalName = name
+ } else {
+ const namesPath = keys.slice(1, keys.length).map((key) => variant[key])
+ name = namesPath.join(' / ')
+ internalName = `${variant[keys[0]]}/${namesPath.join('/')}`
+ }
+
+ return { name, internalName }
+ }
+
+ updateParentCountOnHand(event) {
+ const { variantName } = event.target.closest('[data-variants-form-target="variant"]').dataset
+ const stockLocationId = event.target.dataset.stockLocationId
+ const childrenCountOnHand = this.variantsContainerTarget.querySelectorAll(
+ `[data-variant-name^="${variantName}/"] input[data-slot="[stock_items_attributes][${stockLocationId}][count_on_hand]_input"]`
+ )
+ const parentCountOnHand = event.target.value
+
+ childrenCountOnHand.forEach((countOnHandInput) => {
+ countOnHandInput.value = parentCountOnHand
+ })
+
+ const childrenCountOnHandKeys = this.variantsValue
+ .filter((variant) => variant.internalName.startsWith(variantName))
+ .map((variant) => variant.internalName)
+
+ childrenCountOnHandKeys.forEach((key) => {
+ this.updateStockItemForVariant(key, { count_on_hand: parentCountOnHand }, stockLocationId)
+ })
+
+ this.updateShopLocationCountOnHand()
+ }
+
+ updateParentPrice(event) {
+ const { variantName } = event.target.closest('[data-variants-form-target="variant"]').dataset
+ const currency = event.target.dataset.currency
+ const childrenPrices = this.variantsContainerTarget.querySelectorAll(
+ `[data-variant-name^="${variantName}/"] input[data-slot="[prices_attributes][${currency}][amount]_input"]`
+ )
+ const parentPrice = event.target.value
+
+ childrenPrices.forEach((priceInput) => {
+ priceInput.value = parentPrice
+ })
+ const childrenPricesKeys = this.variantsValue
+ .filter((variant) => variant.internalName.startsWith(variantName))
+ .map((variant) => variant.internalName)
+
+ childrenPricesKeys.forEach((key) => {
+ this.updatePriceForVariant(key, parentPrice, currency)
+ })
+ }
+
+ selectChildVariants(event) {
+ const { variantName } = event.target.closest('[data-variants-form-target="variant"]').dataset
+
+ const children = this.variantsContainerTarget.querySelectorAll(
+ `[data-variant-name^="${variantName}/"] input[type="checkbox"]`
+ )
+
+ children.forEach((child) => {
+ child.checked = event.target.checked
+ })
+
+ this.refresh()
+ }
+
+ prepareParentVariant(existingVariant, internalName) {
+ this.currenciesValue.forEach((currency) => {
+ const parentPriceInput = existingVariant.querySelector(
+ `input[data-slot="[prices_attributes][${currency}][amount]_input"]`
+ )
+ parentPriceInput.name = ''
+ parentPriceInput.dataset.action = `input->variants-form#updateParentPrice`
+ })
+ this.stockLocationsValue.forEach((stockLocationId) => {
+ const parentCountOnHandInput = existingVariant.querySelector(
+ `input[data-slot="[stock_items_attributes][${stockLocationId}][count_on_hand]_input"]`
+ )
+ parentCountOnHandInput.name = ''
+ parentCountOnHandInput.dataset.action = 'input->variants-form#updateParentCountOnHand'
+ })
+
+ const checkbox = existingVariant.querySelector('input[type="checkbox"][id^="checkbox_"]')
+ if (!checkbox) return
+ const checkboxLabel = existingVariant.querySelector('label[for^="checkbox_"]')
+ checkbox.id = `parent_checkbox_${internalName}`
+ checkboxLabel.htmlFor = `parent_checkbox_${internalName}`
+ checkbox.dataset.action = 'click->variants-form#selectChildVariants'
+ checkbox.value = internalName
+ }
+
+ updatePrice(event) {
+ const { variantName } = event.target.closest('[data-variants-form-target="variant"]').dataset
+ const currency = event.target.dataset.currency
+ const nestingLevel = variantName.split('/').length
+ this.updatePriceForVariant(variantName, event.target.value, currency)
+ if (nestingLevel > 1) {
+ const parentName = variantName.split('/')[0]
+ this.updateParentPriceRange(parentName, currency)
+ }
+ }
+
+ replaceBlankWithZero(event) {
+ if (event.target.value === '') {
+ event.target.value = 0
+ }
+ }
+
+ updateCountOnHand(event) {
+ const variantEl = event.target.closest('[data-variants-form-target="variant"]')
+ const variantName = variantEl.dataset.variantName
+
+ const nestingLevel = variantName.split('/').length
+ const stockLocationId = event.target.dataset.stockLocationId
+ const countOnHand = event.target.value || 0
+
+ this.updateStockItemForVariant(variantName, { count_on_hand: countOnHand }, stockLocationId)
+
+ if (nestingLevel > 1) {
+ const parentName = variantName.split('/')[0]
+ this.updateParentStockSum(parentName, stockLocationId)
+ }
+
+ this.updateShopLocationCountOnHand()
+ }
+
+ updateParentPriceRange(variantName, currency) {
+ const parentPriceEl = this.variantsContainerTarget.querySelector(
+ `div:not(.nested)[data-variant-name="${variantName}"] [data-slot="[prices_attributes][${currency}][amount]_input"]`
+ )
+ if (!parentPriceEl) return
+
+ const currentVariantKeys = Array.from(
+ this.variantsContainerTarget.querySelectorAll(`[data-variant-name^="${variantName}/"]`)
+ ).map((el) => el.dataset.variantName)
+
+ const pricesVariation = new Set(
+ Object.keys(this.pricesValue)
+ .filter((key) => currentVariantKeys.includes(key))
+ .map((key) => this.priceForVariant(key, currency).amount)
+ )
+
+ pricesVariation.delete(null)
+
+ if (pricesVariation.size === 0) {
+ parentPriceEl.value = this.priceForVariant(variantName, currency).amount
+ parentPriceEl.placeholder = ''
+ return
+ }
+ const minPrice = Math.min(...pricesVariation)
+ const maxPrice = Math.max(...pricesVariation)
+
+ if (minPrice !== maxPrice) {
+ parentPriceEl.value = null
+ parentPriceEl.placeholder = `${minPrice} - ${maxPrice}`
+ } else {
+ parentPriceEl.value = minPrice
+ }
+ }
+
+ updateParentStockSum(variantName, stockLocationId) {
+ const parentStockEl = this.variantsContainerTarget.querySelector(
+ `div:not(.nested)[data-variant-name="${variantName}"] [data-slot="[stock_items_attributes][${stockLocationId}][count_on_hand]_input"]`
+ )
+ if (!parentStockEl) return
+
+ const currentVariantKeys = Array.from(
+ this.variantsContainerTarget.querySelectorAll(`[data-variant-name^="${variantName}/"]`)
+ ).map((el) => el.dataset.variantName)
+
+ if (currentVariantKeys.length === 0) {
+ parentStockEl.value = this.stockItemForVariant(variantName, stockLocationId).count_on_hand
+ parentStockEl.placeholder = ''
+ this.updateShopLocationCountOnHand()
+ return
+ }
+
+ const countsOnHand = Object.keys(this.stockValue)
+ .filter((key) => currentVariantKeys.includes(key))
+ .map((key) => this.stockItemForVariant(key, stockLocationId).count_on_hand)
+
+ const sum = countsOnHand.reduce((acc, value) => acc + parseInt(value) || 0, 0)
+
+ parentStockEl.placeholder = String(sum)
+ parentStockEl.value = null
+ }
+
+ variantsValueChanged() {
+ let keys = Object.keys(this.variantsValue[0] || {}).filter((key) => key !== 'internalName')
+
+ const currentVariants = new Set()
+
+ if (keys.length) {
+ this.variantsTableTarget.classList.remove('d-none')
+
+ const nestingLevel = Math.min(keys.length, 2)
+ let idx = 0
+
+ for (let i = 0; i < nestingLevel; i++) {
+ this.variantsValue.forEach((variant) => {
+ const { name, internalName } = this.calculateVariantName(variant, keys, i)
+ if (currentVariants.has(internalName) || this.ignoredVariants.has(internalName)) {
+ idx++
+ return
+ }
+ currentVariants.add(internalName)
+
+ const existingVariant = this.variantsContainerTarget.querySelector(`[data-variant-name="${internalName}"]`)
+ if (existingVariant) {
+ if (i === 0 && nestingLevel > 1) {
+ existingVariant.querySelectorAll("input[type='hidden']").forEach((input) => input.remove())
+
+ this.prepareParentVariant(existingVariant, internalName)
+ }
+ idx++
+ return
+ }
+
+ const template = this.variantTemplateTarget.content.cloneNode(true)
+ const variantNameContainer = template.querySelector('[data-slot="variantName"]')
+ const variantTarget = template.querySelector('[data-variants-form-target="variant"]')
+ variantTarget.dataset.variantName = internalName
+
+ const variantId = this.variantIdsValue[internalName]
+ if (variantId) {
+ const variantEditButton = variantTarget.querySelector('[data-slot="variantEditButton"]')
+
+ if (variantEditButton) {
+ variantEditButton.href = `/admin/products/${this.productIdValue}/variants/${variantId}/edit`
+ variantEditButton.classList.remove('invisible')
+ }
+ }
+
+ let previousVariant = null
+
+ if (i > 0) {
+ const { internalName: parentInternalName } = this.calculateVariantName(variant, keys, 0)
+ const variantsInThisGroup = this.variantsContainerTarget.querySelectorAll(
+ `[data-variant-name^="${parentInternalName}/"]`
+ )
+ if (variantsInThisGroup.length > 0) {
+ // If there are already variants in this option type then we want to render this variant after the last variant in the group
+ previousVariant = variantsInThisGroup[variantsInThisGroup.length - 1]
+ } else {
+ // Otherwise we want to render this variant after the parent variant
+ previousVariant = this.variantsContainerTarget.querySelector(
+ `[data-variant-name="${parentInternalName}"]`
+ )
+ }
+ variantTarget.classList.add('nested')
+ } else if (nestingLevel > 1) {
+ template.querySelectorAll("input[type='hidden']").forEach((input) => input.remove())
+ this.prepareParentVariant(template, internalName)
+ }
+
+ if (i === nestingLevel - 1) {
+ const inputs = this.createInputsForVariant(keys, variant, idx)
+ inputs.forEach((input) => {
+ variantTarget.appendChild(input)
+ })
+
+ const checkbox = template.querySelector('input[type="checkbox"]#checkbox_')
+ if (checkbox) {
+ const checkboxLabel = template.querySelector('label[for="checkbox_"]')
+ checkbox.id = `checkbox_${internalName}`
+ checkboxLabel.htmlFor = `checkbox_${internalName}`
+ checkbox.value = internalName
+ }
+
+ this.preparePriceInputs(variantTarget, internalName, idx)
+
+ this.prepareStockInputs(variantTarget, internalName, idx)
+ }
+ idx++
+
+ variantNameContainer.textContent = name
+ if (previousVariant) {
+ previousVariant.after(template)
+ } else {
+ this.variantsContainerTarget.appendChild(template)
+ }
+ })
+ }
+ } else {
+ this.variantsTableTarget.classList.add('d-none')
+ }
+
+ this.variantsContainerTarget.querySelectorAll('[data-variants-form-target="variant"]').forEach((variant) => {
+ const variantName = variant.dataset.variantName
+ if (!currentVariants.has(variantName)) {
+ variant.remove()
+ }
+ })
+
+ // When going back from variant edit page the `variantsValueChanged` method is called before the `connect` method, so `this.productFormController` is not set yet
+ if (this.productFormController) {
+ this.productFormController.hasVariantsValue = this.variantsValue.length > 0
+ }
+
+ this.refreshParentInputs()
+ }
+
+ refreshParentInputs() {
+ const firstOption = Object.values(this.optionsValue)[0]
+ if (firstOption) {
+ firstOption.values.forEach((name) => {
+ this.currenciesValue.forEach((currency) => {
+ this.updateParentPriceRange(name, currency)
+ })
+ this.stockLocationsValue.forEach((stockLocationId) => {
+ this.updateParentStockSum(name, stockLocationId)
+ })
+ this.updateShopLocationCountOnHand()
+ })
+ }
+ }
+
+ createInputsForVariant(keys, variant, i) {
+ const inputs = []
+ if (this.variantIdsValue[variant.internalName]) {
+ const idInput = document.createElement('input')
+ idInput.type = 'hidden'
+ idInput.name = `product[variants_attributes][${i}][id]`
+ idInput.value = this.variantIdsValue[variant.internalName]
+ inputs.push(idInput)
+ }
+
+ keys.forEach((key) => {
+ const nameInput = document.createElement('input')
+ nameInput.type = 'hidden'
+ nameInput.name = `product[variants_attributes][${i}][options][][name]`
+ nameInput.value = key
+ inputs.push(nameInput)
+
+ const positionInput = document.createElement('input')
+ positionInput.type = 'hidden'
+ positionInput.name = `product[variants_attributes][${i}][options][][position]`
+ positionInput.value = Object.values(this.optionsValue)
+ .filter(Boolean)
+ .find((option) => option.name === key).position
+ inputs.push(positionInput)
+
+ const valueInput = document.createElement('input')
+ valueInput.type = 'hidden'
+ valueInput.name = `product[variants_attributes][${i}][options][][value]`
+ valueInput.value = variant[key]
+ inputs.push(valueInput)
+ })
+
+ return inputs
+ }
+
+ prepareStockInputs(variantTarget, internalName, idx) {
+ this.stockLocationsValue.forEach((stockLocationId, stockLocationIndex) => {
+ const stockInput = variantTarget.querySelector(
+ `input[data-slot="[stock_items_attributes][${stockLocationId}][count_on_hand]_input"]`
+ )
+ const stockIdInput = variantTarget.querySelector(
+ `input[data-slot="[stock_items_attributes][${stockLocationId}][id]_input"]`
+ )
+ const stockLocationIdInput = variantTarget.querySelector(
+ `input[data-slot="[stock_items_attributes][${stockLocationId}][stock_location_id]_input"]`
+ )
+ let stockItem = this.stockItemForVariant(internalName, stockLocationId)
+ if (!stockItem.id) {
+ const oldInternalName = internalName.split('/').slice(0, -1).join('/')
+ const oldStock = this.stockItemForVariant(oldInternalName, stockLocationId).count_on_hand ?? 0
+
+ stockItem.count_on_hand = oldStock
+
+ this.updateStockItemForVariant(internalName, stockItem, stockLocationId)
+ }
+
+ stockInput.name = `product[variants_attributes][${idx}][stock_items_attributes][${stockLocationIndex}][count_on_hand]`
+ stockLocationIdInput.name = `product[variants_attributes][${idx}][stock_items_attributes][${stockLocationIndex}][stock_location_id]`
+ stockIdInput.name = `product[variants_attributes][${idx}][stock_items_attributes][${stockLocationIndex}][id]`
+
+ stockInput.value = stockItem.count_on_hand
+ if (stockLocationId === this.currentStockLocationIdValue) {
+ stockInput.classList.remove('d-none')
+ stockInput.classList.add('d-block')
+ } else {
+ stockInput.classList.remove('d-block')
+ stockInput.classList.add('d-none')
+ }
+ if (stockItem.id) {
+ stockIdInput.value = stockItem.id
+ }
+ })
+ }
+
+ preparePriceInputs(variantTarget, internalName, idx) {
+ this.currenciesValue.forEach((currency, currencyIndex) => {
+ const priceInput = variantTarget.querySelector(
+ `input[data-slot="[prices_attributes][${currency}][amount]_input"]`
+ )
+ const currencyInput = variantTarget.querySelector(
+ `input[data-slot="[prices_attributes][${currency}][currency]_input"]`
+ )
+ const idInput = variantTarget.querySelector(`input[data-slot="[prices_attributes][${currency}][id]_input"]`)
+ priceInput.name = `product[variants_attributes][${idx}][prices_attributes][${currency}]`
+ if (currency === this.currentCurrencyValue) {
+ priceInput.parentElement.classList.remove('d-none')
+ priceInput.parentElement.classList.add('d-flex')
+ } else {
+ priceInput.parentElement.classList.remove('d-flex')
+ priceInput.parentElement.classList.add('d-none')
+ }
+
+ const existingPrice = this.priceForVariant(internalName, currency)
+ priceInput.value = existingPrice.amount
+ currencyInput.value = currency
+ if (existingPrice.id) {
+ idInput.value = existingPrice.id
+ }
+
+ priceInput.name = `product[variants_attributes][${idx}][prices_attributes][${currencyIndex}][amount]`
+ currencyInput.name = `product[variants_attributes][${idx}][prices_attributes][${currencyIndex}][currency]`
+ idInput.name = `product[variants_attributes][${idx}][prices_attributes][${currencyIndex}][id]`
+ })
+ }
+
+ addOption(name, option_values = [], id) {
+ let color = false
+ let position = Object.keys(this.optionsValue).length + 1
+ let newOptionsPositions = {}
+
+ const template = this.optionTemplate(name, option_values, id, color)
+
+ this.optionsValue = {
+ ...this.optionsValue,
+ ...newOptionsPositions,
+ [id.toLowerCase().replaceAll(' ', '-')]: {
+ name,
+ values: option_values,
+ position: position
+ }
+ }
+
+ if (position === 1) {
+ this.optionsContainerTarget.prepend(document.importNode(template, true))
+ } else {
+ this.optionsContainerTarget.appendChild(document.importNode(template, true))
+ }
+ }
+
+ handleNewOption(event) {
+ const newOptionName = this.newOptionNameInputTarget.options[this.newOptionNameInputTarget.selectedIndex].text
+ const newOptionId = this.newOptionNameInputTarget.value
+ const newOptionValues = this.newOptionValuesInputTarget.values()
+ if (
+ !newOptionName.length ||
+ this.optionsValue[newOptionId.toLowerCase().replaceAll(' ', '-')] ||
+ newOptionValues.length === 0 ||
+ Object.values(this.optionsValue)
+ .filter(Boolean)
+ .map((v) => v.name)
+ .includes(newOptionName)
+ ) {
+ return
+ }
+
+ this.addOption(newOptionName, newOptionValues, newOptionId)
+
+ this.hideNewOptionForm()
+ }
+
+ hideNewOptionForm() {
+ this.newOptionNameInputTarget.tomselect.clear()
+ this.newOptionValuesInputTarget.reset()
+
+ this.newOptionFormTarget.classList.add('d-none')
+
+ this.newOptionButtonTarget.classList.remove('d-none')
+ }
+
+ editOption(event) {
+ const { optionId } = event.params
+ const option = this.optionsContainerTarget.querySelector(`#option-${optionId}`)
+
+ const { name, values } = this.optionsValue[optionId]
+
+ const form = this.optionFormTemplate(name, values, optionId)
+
+ option.replaceWith(form)
+ }
+
+ saveOption(event) {
+ const { optionId } = event.params
+ const option = this.optionsContainerTarget.querySelector(`#option-${optionId.toLowerCase().replaceAll(' ', '-')}`)
+ const optionForm = option.closest('[data-slot="optionForm"]')
+ const optionNameSelect = option.querySelector('select[name="option_name"]')
+ const optionName = optionNameSelect.options[optionNameSelect.selectedIndex].text
+ const newId = optionNameSelect.value
+
+ if ((newId != optionId && this.optionsValue[newId.toLowerCase()]) || !optionName.length) {
+ return
+ }
+
+ let color = false
+ let position = this.optionsValue[optionId.toLowerCase()].position
+ let newOptionsPositions = {}
+
+ const optionValues = option.querySelector('[data-slot="optionValuesInput"]').values()
+
+ if (optionValues.length === 0) {
+ return
+ }
+
+ const template = this.optionTemplate(optionName, optionValues, newId, color)
+
+ if (color) {
+ this.optionsContainerTarget.prepend(template)
+ optionForm.remove()
+ } else {
+ optionForm.replaceWith(template)
+ }
+
+ const newOptions = {
+ ...this.optionsValue,
+ ...newOptionsPositions,
+ [newId.toLowerCase()]: {
+ ...this.optionsValue[optionId.toLowerCase()],
+ name: optionName,
+ values: optionValues,
+ position: position
+ }
+ }
+ if (optionId != newId) {
+ delete newOptions[optionId.toLowerCase()]
+ }
+
+ this.optionsValue = newOptions
+ }
+
+ showNewOptionForm(event) {
+ event.preventDefault()
+ this.newOptionFormTarget.classList.remove('d-none')
+ this.newOptionButtonTarget.classList.add('d-none')
+ }
+
+ optionTemplate(name, values, id, color = false) {
+ const template = this.optionTemplateTarget.content.cloneNode(true)
+ template.querySelectorAll('[data-variants-form-option-id-param]').forEach((el) => {
+ el.dataset.variantsFormOptionIdParam = id.toLowerCase().replaceAll(' ', '-')
+ })
+ const optionName = template.querySelector('[data-slot="optionName"]')
+ const optionValuesTemplates = this.optionValueTemplate(values)
+ const optionValuesContainer = template.querySelector('[data-slot="optionValuesContainer"]')
+ optionValuesTemplates.forEach((optionValueTemplate) => {
+ optionValuesContainer.appendChild(optionValueTemplate)
+ })
+ const mainContainer = template.querySelector('[data-variants-form-target="option"]')
+ mainContainer.id = 'option-' + id.toLowerCase().replaceAll(' ', '-')
+
+ optionName.textContent = name
+ if (color) {
+ mainContainer.classList.add('color-option')
+ mainContainer.querySelector('.draggable').disabled = true
+ }
+ return template
+ }
+
+ discardOption(event) {
+ const { optionId } = event.params
+ const option = this.optionsContainerTarget.querySelector(`#option-${optionId}`)
+ const optionName = this.optionsValue[optionId.toLowerCase()].name
+ option.remove()
+ this.optionsValue = { ...this.optionsValue, [optionId.toLowerCase()]: null }
+ this.refreshParentInputs()
+ }
+
+ optionFormTemplate(optionName, optionValues, id) {
+ const template = this.optionFormTemplateTarget.content.cloneNode(true)
+
+ const optionNameSelect = template.querySelector('select[name="option_name"]')
+
+ let optionExists = false
+ // If options includes the optionName, set it as selected
+ optionNameSelect.querySelectorAll('option').forEach((option) => {
+ if (option.value === id) {
+ option.selected = true
+ optionExists = true
+ }
+ })
+ // Otherwise, create a new option, and select it
+ if (!optionExists) {
+ const newOption = document.createElement('option')
+ newOption.text = optionName
+ newOption.value = id
+ newOption.selected = true
+ optionNameSelect.appendChild(newOption)
+ }
+
+ const optionValuesInput = template.querySelector('[data-slot="optionValuesInput"]')
+ optionValuesInput.dataset.multiInputPreloadedValuesValue = JSON.stringify(optionValues)
+
+ template.querySelectorAll('[data-variants-form-option-id-param]').forEach((el) => {
+ el.dataset.variantsFormOptionIdParam = id
+ })
+
+ const mainContainer = template.querySelector('[data-slot="optionForm"]')
+ mainContainer.id = 'option-' + id.toLowerCase().replaceAll(' ', '-')
+
+ return template
+ }
+
+ optionValueTemplate(values) {
+ const templates = []
+
+ values.forEach((value) => {
+ const template = this.optionValueTemplateTarget.content.cloneNode(true)
+ const optionValueNameEl = template.querySelector('[data-slot="optionValueName"]')
+ optionValueNameEl.textContent = value
+ optionValueNameEl.dataset.name = value
+
+ templates.push(template)
+ })
+
+ return templates
+ }
+
+ refreshTomSelect() {
+ 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)
+ 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()
+ }
+
+ generateVariants(optionsValue) {
+ const options = Object.values(optionsValue)
+ .filter(Boolean)
+ .sort((a, b) => a.position - b.position)
+
+ if (options.length === 0) {
+ return []
+ }
+
+ const optionValues = options.map((option) => option.values)
+ const optionNames = options.map((option) => option.name)
+
+ const cartesianProduct = this.cartesianProduct(optionValues)
+
+ return cartesianProduct.map((variant) => {
+ variant = Array.isArray(variant) ? variant : [variant]
+ const variantObj = variant.reduce((acc, value, index) => {
+ acc[options[index].name] = value
+ return acc
+ }, {})
+ variantObj.internalName = this.calculateVariantName(variantObj, optionNames, optionNames.length - 1).internalName
+ return variantObj
+ })
+ }
+
+ cartesianProduct(arr) {
+ return arr.reduce((a, b) => a.flatMap((d) => b.map((e) => [d, e].flat())))
+ }
+
+ stockItemForVariant(variantName, stockLocationId) {
+ const existingStock = this.stockValue[variantName]?.[stockLocationId]
+ if (existingStock) return existingStock
+
+ return { count_on_hand: 0, backorderable: false, id: null }
+ }
+
+ updateStockItemForVariant(variantName, newStockItem, stockLocationId) {
+ const existingStockItem = this.stockItemForVariant(variantName, stockLocationId)
+ this.stockValue = {
+ ...this.stockValue,
+ [variantName]: {
+ ...this.stockValue[variantName],
+ [stockLocationId]: {
+ ...existingStockItem,
+ ...newStockItem
+ }
+ }
+ }
+ }
+
+ priceForVariant(variantName, currency) {
+ const existingPrice = this.pricesValue[variantName]?.[currency.toLowerCase()]
+ if (existingPrice) {
+ return {
+ ...existingPrice,
+ amount: existingPrice.amount ? parseFloat(existingPrice.amount) : existingPrice.amount
+ }
+ }
+
+ return { amount: null, id: null }
+ }
+
+ updatePriceForVariant(variantName, newPrice, currency) {
+ const existingPrice = this.priceForVariant(variantName, currency)
+ this.pricesValue = {
+ ...this.pricesValue,
+ [variantName]: {
+ ...this.pricesValue[variantName],
+ [currency.toLowerCase()]: {
+ ...existingPrice,
+ amount: parseFloat(newPrice)
+ }
+ }
+ }
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/webhook_subscriber_events_controller.js b/admin/app/javascript/spree/admin/controllers/webhook_subscriber_events_controller.js
new file mode 100644
index 0000000000..f65ab5241d
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/webhook_subscriber_events_controller.js
@@ -0,0 +1,19 @@
+import { Controller } from '@hotwired/stimulus'
+
+export default class extends Controller {
+ static targets = ['eventsCheckboxesContainer', 'subscribeToAll']
+
+ hideCheckboxes() {
+ this.eventsCheckboxesContainerTarget.classList.add('d-none')
+ }
+
+ showCheckboxes() {
+ this.eventsCheckboxesContainerTarget.classList.remove('d-none')
+ }
+
+ initialize() {
+ if (this.subscribeToAllTarget.checked) {
+ this.hideCheckboxes()
+ }
+ }
+}
diff --git a/admin/app/javascript/spree/admin/helpers/uppy_active_storage.js b/admin/app/javascript/spree/admin/helpers/uppy_active_storage.js
new file mode 100644
index 0000000000..aa8d510f67
--- /dev/null
+++ b/admin/app/javascript/spree/admin/helpers/uppy_active_storage.js
@@ -0,0 +1,210 @@
+/* eslint-disable no-undef */
+import BasePlugin from "@uppy/core/lib/BasePlugin.js"
+import { createId } from "@paralleldrive/cuid2"
+// const Translator = require('@uppy/utils/lib/Translator');
+// const { Provider, Socket } = require('@uppy/companion-client');
+// const emitSocketProgress = require('@uppy/utils/lib/emitSocketProgress');
+// const getSocketHost = require('@uppy/utils/lib/getSocketHost');
+import { RateLimitedQueue } from '@uppy/utils/lib/RateLimitedQueue'
+import { DirectUpload } from "@rails/activestorage"
+
+export default class ActiveStorageUpload extends BasePlugin {
+ constructor(uppy, opts) {
+ super(uppy, opts)
+
+ this.id = opts.id || "ActiveStorageUpload"
+ this.title = opts.title || "ActiveStorageUpload"
+ this.type = "uploader"
+
+ const defaultOptions = {
+ limit: 0,
+ timeout: 30 * 1000,
+ directUploadUrl: null,
+ headers: {}
+ }
+
+ this.opts = Object.assign({}, defaultOptions, opts)
+
+ // Simultaneous upload limiting is shared across all uploads with this plugin.
+ if (typeof this.opts.limit === "number" && this.opts.limit !== 0) {
+ this.limitUploads = new RateLimitedQueue(this.opts.limit)
+ } else {
+ this.limitUploads = fn => fn
+ }
+
+ this.handleUpload = this.handleUpload.bind(this)
+ }
+
+ install() {
+ this.uppy.addUploader(this.handleUpload)
+ }
+
+ uninstall() {
+ this.uppy.removeUploader(this.handleUpload)
+ }
+
+ handleUpload(fileIDs) {
+ if (fileIDs.length === 0) {
+ this.uppy.log("[ActiveStorage] No files to upload!")
+ return Promise.resolve()
+ }
+
+ this.uppy.log("[ActiveStorage] Uploading...")
+ const files = fileIDs.map(fileID => this.uppy.getFile(fileID))
+
+ return this.uploadFiles(files).then(() => null)
+ }
+
+ upload(file, current, total) {
+ this.uppy.log(`uploading ${current} of ${total}`)
+
+ return new Promise((resolve, reject) => {
+ const timer = this.createProgressTimeout(this.opts.timeout, error => {
+ //xhr.abort();
+ this.uppy.emit("upload-error", file, error)
+ reject(error)
+ })
+
+ var directHandlers = {
+ directUploadWillStoreFileWithXHR: null,
+ directUploadDidProgress: null,
+ }
+ directHandlers.directUploadDidProgress = ev => {
+ this.uppy.log(`[XHRUpload] ${id} progress: ${ev.loaded} / ${ev.total}`)
+ timer.progress()
+
+ if (ev.lengthComputable) {
+ this.uppy.emit("upload-progress", file, {
+ uploader: this,
+ bytesUploaded: ev.loaded,
+ bytesTotal: ev.total,
+ })
+ }
+ }
+ directHandlers.directUploadWillStoreFileWithXHR = request => {
+ request.upload.addEventListener("progress", event =>
+ directHandlers.directUploadDidProgress(event)
+ )
+ }
+
+ const { data, meta } = file
+
+ if (!data.name && meta.name) {
+ data.name = meta.name
+ }
+
+ const upload = new DirectUpload(data, this.opts.directUploadUrl, directHandlers, this.opts.headers);
+ const id = createId()
+
+ upload.create((error, blob) => {
+ this.uppy.log(`[XHRUpload] ${id} finished`)
+ timer.done()
+
+ if (error) {
+ const response = {
+ status: "error",
+ }
+
+ this.uppy.setFileState(file.id, { response })
+
+ this.uppy.emit("upload-error", file, error)
+ return reject(error)
+ } else {
+ const response = {
+ status: "success",
+ directUploadSignedId: blob.signed_id,
+ }
+
+ this.uppy.setFileState(file.id, { response })
+
+ this.uppy.emit("upload-success", file, blob)
+
+ return resolve(file)
+ }
+ })
+
+ this.uppy.on("file-removed", removedFile => {
+ if (removedFile.id === file.id) {
+ timer.done()
+ upload.abort && upload.abort()
+ }
+ })
+
+ this.uppy.on("upload-cancel", fileID => {
+ if (fileID === file.id) {
+ timer.done()
+ upload.abort && upload.abort()
+ }
+ })
+
+ this.uppy.on("cancel-all", () => {
+ timer.done()
+ upload.abort && upload.abort()
+ })
+ })
+ }
+
+ uploadFiles(files) {
+ const actions = files.map((file, i) => {
+ const current = parseInt(i, 10) + 1
+ const total = files.length
+
+ if (file.error) {
+ return () => Promise.reject(new Error(file.error))
+ } else {
+ this.uppy.emit("upload-start", [file])
+ return this.upload.bind(this, file, current, total)
+ }
+ })
+
+ const promises = actions.map(action => {
+ const limitedAction = this.limitUploads(action)
+ return limitedAction()
+ })
+
+ return Promise.allSettled(promises)
+ }
+
+ // Helper to abort upload requests if there has not been any progress for `timeout` ms.
+ // Create an instance using `timer = createProgressTimeout(10000, onTimeout)`
+ // Call `timer.progress()` to signal that there has been progress of any kind.
+ // Call `timer.done()` when the upload has completed.
+ createProgressTimeout(timeout, timeoutHandler) {
+ const uppy = this.uppy
+ const self = this
+ let isDone = false
+
+ function onTimedOut() {
+ uppy.log("[XHRUpload] timed out")
+ const error = new Error(self.i18n("timedOut", { seconds: Math.ceil(timeout / 1000) }))
+ timeoutHandler(error)
+ }
+
+ let aliveTimer = null
+ function progress() {
+ // Some browsers fire another progress event when the upload is
+ // cancelled, so we have to ignore progress after the timer was
+ // told to stop.
+ if (isDone) return
+
+ if (timeout > 0) {
+ if (aliveTimer) clearTimeout(aliveTimer)
+ aliveTimer = setTimeout(onTimedOut, timeout)
+ }
+ }
+
+ function done() {
+ uppy.log("[XHRUpload] timer done")
+ if (aliveTimer) {
+ clearTimeout(aliveTimer)
+ aliveTimer = null
+ }
+ isDone = true
+ }
+
+ return {
+ progress,
+ done,
+ }
+ }
+}
diff --git a/admin/config/importmap.rb b/admin/config/importmap.rb
index a5b10a2d8d..e8008f3600 100644
--- a/admin/config/importmap.rb
+++ b/admin/config/importmap.rb
@@ -15,18 +15,91 @@ pin "mapkick/bundle", to: "mapkick.bundle.js", preload: ["application-spree-admi
pin 'jquery', to: 'jquery3.min.js', preload: ["application-spree-admin"]
# Bootstrap 4 does not want to work with importmaps, after long debugging I found this comment which helped https://github.com/twbs/bootstrap-rubygem/issues/257#issuecomment-1707196465. Bootstrap has to be imported from jsdelivr.
pin "bootstrap", to: 'https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js', preload: ["application-spree-admin"]
-pin "@stimulus-components/auto-submit", to: "https://ga.jspm.io/npm:@stimulus-components/[email protected]/dist/stimulus-auto-submit.mjs", preload: ["application-spree-admin"]
-pin "@stimulus-components/rails-nested-form", to: "https://ga.jspm.io/npm:@stimulus-components/[email protected]/dist/stimulus-rails-nested-form.mjs", preload: ["application-spree-admin"]
-pin "stimulus-notification", to: "https://ga.jspm.io/npm:[email protected]/dist/stimulus-notification.mjs", preload: ["application-spree-admin"]
-pin "stimulus-password-visibility", to: "https://ga.jspm.io/npm:[email protected]/dist/stimulus-password-visibility.mjs", preload: ["application-spree-admin"]
-pin "stimulus-reveal-controller", to: "https://ga.jspm.io/npm:[email protected]/dist/stimulus-reveal-controller.mjs", preload: ["application-spree-admin"]
-pin "stimulus-sortable", to: "https://ga.jspm.io/npm:[email protected]/dist/stimulus-sortable.mjs", preload: ["application-spree-admin"]
-pin "stimulus-textarea-autogrow", to: "https://ga.jspm.io/npm:[email protected]/dist/stimulus-textarea-autogrow.mjs", preload: ["application-spree-admin"]
-pin "tailwindcss-stimulus-components", to: "https://ga.jspm.io/npm:[email protected]/dist/tailwindcss-stimulus-components.module.js", preload: ["application-spree-admin"]
-pin "hotkeys-js", to: "https://ga.jspm.io/npm:[email protected]/dist/hotkeys.esm.js", preload: ["application-spree-admin"]
-pin "sortablejs", to: "https://ga.jspm.io/npm:[email protected]/modular/sortable.esm.js", preload: ["application-spree-admin"]
-pin "stimulus-use", to: "https://ga.jspm.io/npm:[email protected]/dist/index.js", preload: ["application-spree-admin"]
+# Stimulus components
+pin "@stimulus-components/auto-submit", to: "https://ga.jspm.io/npm:@stimulus-components/[email protected]/dist/stimulus-auto-submit.mjs", preload: false
+pin "@stimulus-components/rails-nested-form", to: "https://ga.jspm.io/npm:@stimulus-components/[email protected]/dist/stimulus-rails-nested-form.mjs", preload: false
+pin "stimulus-notification", to: "https://ga.jspm.io/npm:[email protected]/dist/stimulus-notification.mjs", preload: false
+pin "stimulus-password-visibility", to: "https://ga.jspm.io/npm:[email protected]/dist/stimulus-password-visibility.mjs", preload: false
+pin "stimulus-reveal-controller", to: "https://ga.jspm.io/npm:[email protected]/dist/stimulus-reveal-controller.mjs", preload: false
+pin "stimulus-sortable", to: "https://ga.jspm.io/npm:[email protected]/dist/stimulus-sortable.mjs", preload: false
+pin "stimulus-textarea-autogrow", to: "https://ga.jspm.io/npm:[email protected]/dist/stimulus-textarea-autogrow.mjs", preload: false
+pin "tailwindcss-stimulus-components", to: "https://ga.jspm.io/npm:[email protected]/dist/tailwindcss-stimulus-components.module.js", preload: false
+pin "hotkeys-js", to: "https://ga.jspm.io/npm:[email protected]/dist/hotkeys.esm.js", preload: false
+pin "sortablejs", to: "https://ga.jspm.io/npm:[email protected]/modular/sortable.esm.js", preload: false
+pin "stimulus-use", to: "https://ga.jspm.io/npm:[email protected]/dist/index.js", preload: false
+pin "stimulus-checkbox-select-all", to: "https://ga.jspm.io/npm:[email protected]/dist/stimulus-checkbox-select-all.mjs", preload: false
+pin "stimulus-clipboard", to: "https://ga.jspm.io/npm:[email protected]/dist/stimulus-clipboard.mjs", preload: false
+#
+
+#Uppy
+pin "@uppy/core", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/index.js",preload: false
+pin "@uppy/dashboard", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/index.js",preload: false
+pin "@uppy/image-editor", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/index.js",preload: false
+pin "@transloadit/prettier-bytes", to: "https://ga.jspm.io/npm:@transloadit/[email protected]/dist/prettierBytes.js",preload: false
+pin "@uppy/informer", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/index.js",preload: false
+pin "@uppy/provider-views", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/index.js",preload: false
+pin "@uppy/status-bar", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/index.js",preload: false
+pin "@uppy/store-default", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/index.js",preload: false
+pin "@uppy/thumbnail-generator", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/index.js",preload: false
+pin "@uppy/utils/lib/FOCUSABLE_ELEMENTS", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/FOCUSABLE_ELEMENTS.js",preload: false
+pin "@uppy/utils/lib/Translator", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/Translator.js",preload: false
+pin "@uppy/utils/lib/VirtualList", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/VirtualList.js",preload: false
+pin "@uppy/utils/lib/dataURItoBlob", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/dataURItoBlob.js",preload: false
+pin "@uppy/utils/lib/emaFilter", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/emaFilter.js",preload: false
+pin "@uppy/utils/lib/findAllDOMElements", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/findAllDOMElements.js",preload: false
+pin "@uppy/utils/lib/findDOMElement", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/findDOMElement.js",preload: false
+pin "@uppy/utils/lib/generateFileID", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/generateFileID.js",preload: false
+pin "@uppy/utils/lib/getDroppedFiles", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/getDroppedFiles/index.js",preload: false
+pin "@uppy/utils/lib/getFileNameAndExtension", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/getFileNameAndExtension.js",preload: false
+pin "@uppy/utils/lib/getFileType", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/getFileType.js",preload: false
+pin "@uppy/utils/lib/getTextDirection", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/getTextDirection.js",preload: false
+pin "@uppy/utils/lib/getTimeStamp", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/getTimeStamp.js",preload: false
+pin "@uppy/utils/lib/isDragDropSupported", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/isDragDropSupported.js",preload: false
+pin "@uppy/utils/lib/isObjectURL", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/isObjectURL.js",preload: false
+pin "@uppy/utils/lib/isPreviewSupported", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/isPreviewSupported.js",preload: false
+pin "@uppy/utils/lib/prettyETA", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/prettyETA.js",preload: false
+pin "@uppy/utils/lib/remoteFileObjToLocal", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/remoteFileObjToLocal.js",preload: false
+pin "@uppy/utils/lib/toArray", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/toArray.js",preload: false
+pin "@uppy/utils/lib/truncateString", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/truncateString.js",preload: false
+pin "classnames", to: "https://ga.jspm.io/npm:[email protected]/index.js",preload: false
+pin "cropperjs", to: "https://ga.jspm.io/npm:[email protected]/dist/cropper.js",preload: false
+pin "eventemitter3", to: "https://ga.jspm.io/npm:[email protected]/index.mjs",preload: false
+pin "exifr/dist/mini.esm.mjs", to: "https://ga.jspm.io/npm:[email protected]/dist/mini.esm.mjs",preload: false
+pin "lodash/", to: "https://ga.jspm.io/npm:[email protected]/",preload: false
+pin "memoize-one", to: "https://ga.jspm.io/npm:[email protected]/dist/memoize-one.esm.js",preload: false
+pin "mime-match", to: "https://ga.jspm.io/npm:[email protected]/index.js",preload: false
+pin "namespace-emitter", to: "https://ga.jspm.io/npm:[email protected]/index.js",preload: false
+pin "nanoid/non-secure", to: "https://ga.jspm.io/npm:[email protected]/non-secure/index.js",preload: false
+pin "p-queue", to: "https://ga.jspm.io/npm:[email protected]/dist/index.js",preload: false
+pin "p-timeout", to: "https://ga.jspm.io/npm:[email protected]/index.js",preload: false
+pin "preact", to: "https://ga.jspm.io/npm:[email protected]/dist/preact.module.js",preload: false
+pin "preact/hooks", to: "https://ga.jspm.io/npm:[email protected]/hooks/dist/hooks.module.js",preload: false
+pin "shallow-equal", to: "https://ga.jspm.io/npm:[email protected]/dist/index.modern.mjs",preload: false
+pin "wildcard", to: "https://ga.jspm.io/npm:[email protected]/index.js", preload: false
+pin "@paralleldrive/cuid2", to: "https://ga.jspm.io/npm:@paralleldrive/[email protected]/index.js", preload: false
+pin "@uppy/core/lib/BasePlugin.js", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/BasePlugin.js", preload: false
+pin "@uppy/utils/lib/RateLimitedQueue", to: "https://ga.jspm.io/npm:@uppy/[email protected]/lib/RateLimitedQueue.js", preload: false
+pin "@noble/hashes/crypto", to: "https://ga.jspm.io/npm:@noble/[email protected]/crypto.js", preload: false
+pin "@noble/hashes/sha3", to: "https://ga.jspm.io/npm:@noble/[email protected]/sha3.js", preload: false
+#
+
+#Tom Select
+pin "tom-select/dist/esm/tom-select.complete.js", to: "https://ga.jspm.io/npm:[email protected]/dist/esm/tom-select.complete.js",preload: false
+pin "@orchidjs/sifter", to: "https://ga.jspm.io/npm:@orchidjs/[email protected]/dist/esm/sifter.js", preload: false
+pin "@orchidjs/unicode-variants", to: "https://ga.jspm.io/npm:@orchidjs/[email protected]/dist/esm/index.js", preload: false
+#
+
+# Easepick
+pin "@easepick/core", to: "https://ga.jspm.io/npm:@easepick/[email protected]/dist/index.esm.js", preload: false
+pin "@easepick/preset-plugin", to: "https://ga.jspm.io/npm:@easepick/[email protected]/dist/index.esm.js", preload: false
+pin "@easepick/range-plugin", to: "https://ga.jspm.io/npm:@easepick/[email protected]/dist/index.esm.js", preload: false
+pin "@easepick/base-plugin", to: "https://ga.jspm.io/npm:@easepick/[email protected]/dist/index.esm.js", preload: false
+pin "@easepick/datetime", to: "https://ga.jspm.io/npm:@easepick/[email protected]/dist/index.esm.js", preload: false
+#
+
+
+pin "@simonwep/pickr", to: "https://ga.jspm.io/npm:@simonwep/[email protected]/dist/pickr.min.js", preload: false
pin_all_from Spree::Admin::Engine.root.join("app/javascript/spree/admin/controllers"), under: "spree/admin/controllers", to: "spree/admin/controllers", preload: ["application-spree-admin"]
pin_all_from Spree::Admin::Engine.root.join("app/javascript/spree/admin/helpers"), under: "spree/admin/helpers", to: "spree/admin/helpers", preload: ["application-spree-admin"]