// Sortable fields

$(document).on('turbolinks:load app:block-slot-after-insert', function() {
  var $fieldSets = $('.sortable-field-set');

  $fieldSets.each(function() {
    var $fieldSet = $(this);

    $fieldSet.sortable({
      items: '> .sortable-field',
      containment: $fieldSet,
      // tolerance: 'pointer',
      placeholder: 'sortable-placeholder',
      handle: '.sortable-field-set__handle',
      forcePlaceholderSize: true
    });

    $fieldSet.on('sortupdate.sortableFieldSets', function() {
      calculatePositions( $fieldSet );
    });

    function calculatePositions($fieldSet) {
      var $fields = $fieldSet.find('> .sortable-field');

      $fields.each(function(index) {
        var $field = $(this);
        var $input = $field.find('.sortable-field-set__position');

        $input.val(index);
      });
    }

    $(document).one('turbolinks:before-cache', function() {
      $fieldSet.off('sortupdate.sortableFieldSets');
      $fieldSet.sortable('destroy');
    });
  });
});

@@ -13,16 +13,346 @@
 fields%0A%0A
+// Sortable field sets can be nested multiple times, but need to follow this hierarchy:%0A// %3Cdiv class=%22sortable-field-set%22%3E%0A//   %3Cdiv class=%22sortable-field%22%3E%0A//     %3Cdiv class=%22sortable-field-set__handle%22%3E%3C/div%3E%0A//     %3Cdiv class=%22sortable-field-set__position%22%3E%0A//       %3Cinput type=%22hidden%22%3E%0A//     %3C/div%3E%0A//   %3C/div%3E%0A// %3C/div%3E%0A%0A
 $(docume
@@ -887,16 +887,179 @@
  %7D);%0A%0A  
+  $(document).one('turbolinks:before-cache', function() %7B%0A      $fieldSet.off('sortupdate.sortableFieldSets');%0A      $fieldSet.sortable('destroy');%0A    %7D);%0A  %7D);%0A%0A
   functi
@@ -1089,26 +1089,24 @@
 fieldSet) %7B%0A
-  
     var $fie
@@ -1149,26 +1149,24 @@
 eld');%0A%0A    
-  
 $fields.each
@@ -1186,26 +1186,24 @@
 ex) %7B%0A      
-  
 var $field =
@@ -1214,26 +1214,24 @@
 his);%0A      
- 
- 
 var $input =
@@ -1244,16 +1244,18 @@
 d.find('
+%3E 
 .sortabl
@@ -1279,204 +1279,41 @@
 tion
-');%0A%0A        $input.val(index);%0A      %7D);%0A    %7D%0A%0A    $(document).one('turbolinks:before-cache', function() %7B%0A      $fieldSet.off('sortupdate.sortableFieldSets');%0A      $fieldSet.sortable('destroy'
+ input');%0A%0A      $input.val(index
 );%0A 
@@ -1322,15 +1322,13 @@
  %7D);%0A  %7D
-);
 %0A%7D);%0A

Enable nested sortable field sets