Search code examples
javascriptjsonnestedalpine.jssortablejs

Difficulty Sorting Nested JSON Layer Tree with SortableJS in Alpine.js


I'm having trouble sorting my nested JSON layer tree using SortableJS in an Alpine.js application. I have a complex JSON structure representing layers, which can be nested multiple levels deep. My goal is to sort these layers and update the JSON structure accordingly.

Here's a simplified version of my layer structure and the relevant code:

// Pre-define theme
document.documentElement.setAttribute('data-theme', 'dark');

function App() {
  return {
    data: {
      layerStructure: [
        {
          "tag": "header",
          "type": "box",
          "name": "box",
          "id": "wnl0mxhml",
          "state": {
            "collapsed": false,
            "visible": true,
            "selected": false
          },
          "props": {
            "class": "p4dmvkj5v"
          },
          "children": [
            {
              "tag": "hgroup",
              "type": "box",
              "name": "box",
              "id": "xw0wqhizc",
              "state": {
                "collapsed": false,
                "visible": true,
                "selected": false
              },
              "props": {
                "class": "w78d2h"
              },
              "children": [
                {
                  "tag": "h1",
                  "type": "text",
                  "name": "text",
                  "id": "orfik88na",
                  "state": {
                    "collapsed": false,
                    "visible": true,
                    "selected": false
                  },
                  "props": {
                    "class": "n6zv2tuar"
                  },
                  "text": "App name"
                },
                {
                  "tag": "h2",
                  "type": "text",
                  "name": "text",
                  "id": "lzsntwjt3",
                  "state": {
                    "collapsed": false,
                    "visible": true,
                    "selected": false
                  },
                  "props": {
                    "class": "xqkuxhejp"
                  },
                  "text": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Commodi accusantium rem sint voluptatum quisquam cum. Nostrum dolorum alias doloribus quod accusantium odit vero dolor excepturi cumque mollitia? Laboriosam, dolore rem!"
                }
              ]
            }
          ]
        },
        {
          "tag": "main",
          "type": "box",
          "name": "box",
          "id": "o03yq4tqx",
          "state": {
            "collapsed": false,
            "visible": true,
            "selected": false
          },
          "props": {
            "class": "p4dmvkj5v"
          },
          "children": [
            {
              "tag": "figure",
              "type": "box",
              "name": "box",
              "id": "ary2rnlid",
              "state": {
                "collapsed": false,
                "visible": true,
                "selected": false
              },
              "children": [
                {
                  "tag": "img",
                  "type": "img",
                  "name": "img",
                  "id": "o4cwkc0zb",
                  "state": {
                    "collapsed": false,
                    "visible": true,
                    "selected": false
                  },
                  "props": {
                    "class": "cc7uwye7i",
                    "src": "imgs/image.webp",
                    "alt": "Polyrise"
                  }
                },
                {
                  "tag": "figcaption",
                  "type": "box",
                  "name": "box",
                  "id": "t57ciu00f",
                  "state": {
                    "collapsed": false,
                    "visible": true,
                    "selected": false
                  },
                  "children": [
                    {
                      "tag": "a",
                      "type": "text",
                      "name": "text",
                      "id": "u50q0cuz9",
                      "state": {
                        "collapsed": false,
                        "visible": true,
                        "selected": false
                      },
                      "props": {
                        "href": "https://michaelsboost.com/Polyrise/",
                        "target": "_blank"
                      },
                      "text": "michaelsboost.com/Polyrise"
                    }
                  ],
                  "text": "Image from"
                }
              ]
            }
          ]
        }
      ]
    },
    icons: {
      move: `<svg class="w-3" viewBox="0 0 512 512" style="color: unset;">
        <path 
          fill="currentColor" 
          d="M278.6 9.4c-12.5-12.5-32.8-12.5-45.3 0l-64 64c-9.2 9.2-11.9 22.9-6.9 34.9s16.6 19.8 29.6 19.8h32v96H128V192c0-12.9-7.8-24.6-19.8-29.6s-25.7-2.2-34.9 6.9l-64 64c-12.5 12.5-12.5 32.8 0 45.3l64 64c9.2 9.2 22.9 11.9 34.9 6.9s19.8-16.6 19.8-29.6V288h96v96H192c-12.9 0-24.6 7.8-29.6 19.8s-2.2 25.7 6.9 34.9l64 64c12.5 12.5 32.8 12.5 45.3 0l64-64c9.2-9.2 11.9-22.9 6.9-34.9s-16.6-19.8-29.6-19.8H288V288h96v32c0 12.9 7.8 24.6 19.8 29.6s25.7 2.2 34.9-6.9l64-64c12.5-12.5 12.5-32.8 0-45.3l-64-64c-9.2-9.2-22.9-11.9-34.9-6.9s-19.8 16.6-19.8 29.6v32H288V128h32c12.9 0 24.6-7.8 29.6-19.8s2.2-25.7-6.9-34.9l-64-64z"/>
      </svg>`
    },
    renderLayer(layer){
      let html = `<code 
          class="p-0 flex justify-between whitespace-nowrap min-w-min">
          <span>
            <button 
              data-move
              aria-label="sort layer"
              name="sort layer"
              class="bg-transparent border-0 p-2 text-xs cursor-grab focus:shadow-none" style="color: unset;">
              <span x-html="icons.move"></span>
            </button>
          </span>
          <button 
            aria-label="toggle selected layer"
            name="toggle selected layer"
            class="bg-transparent border-0 p-2 text-xs text-right capitalize"
            style="color: unset;">
            <span x-html="layer.name"></span>
          </button>
        </code>`;

      if(layer.children) {
        html += `<ul 
          class="mt-1 mb-1 ml-4"
          data-id="${layer.id}">
            <template x-for='layer in layer.children'>
              <li class="list-none select-none" x-html="renderLayer(layer)" data-id="${layer.id}"></li>
            </template>
          </ul>`;
      }

      return html;
    },
    init() {
      // Initialize SortableJS on the element with ID 'sortableContainer'
      const initializeSortable = element => {
        new Sortable(element, {
          group: 'shared', // Enable moving items between containers
          handle: '[data-move]',
          animation: 150,
          fallbackOnBody: true,
          swapThreshold: 0.65,
          onEnd: evt => {
            // Get the dragged item's ID
            const draggableId = evt.item.dataset.id;
            const draggableLayer = this.findLayerById(draggableId, this.data.layerStructure);
            const dropId = evt.to.dataset.id;
            console.log(draggableLayer);
            
            // Get the updated order
            const newOrder = Array.from(evt.from.children).map(item => item.dataset.id);
          
          // Update the layer structure based on new order
          // this.updateLayerStructure(draggableId, newOrder);
          }
        })
      };

      const containerElement = document.getElementById('sortableContainer');
      this.$nextTick(() => {
        initializeSortable(containerElement);
        containerElement.querySelectorAll('ul').forEach(ul => initializeSortable(ul));
      });
    },
    findLayerById(id, layers) {
      for (const layer of layers) {
        if (layer.id === id) return layer;
        if (layer.children) {
          const found = this.findLayerById(id, layer.children);
          if (found) return found;
        }
      }
      return null;
    },
    updateLayerStructure(id, newOrder) {
      // Find the layer by ID in the structure
      const layerToUpdate = this.findLayerById(id, this.data.layerStructure);
      if (layerToUpdate) {
        // Update the children order based on newOrder
        layerToUpdate.children = newOrder.map(itemId => this.findLayerById(itemId, this.data.layerStructure));
      }

      // Update your output element with the updated layer structure
      this.$refs.output.value = JSON.stringify(this.data.layerStructure, null, 2);
      this.$refs.output.textContent = JSON.stringify(this.data.layerStructure, null, 2);
    }
  }
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/picocss/2.0.6/pico.min.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css"/>

<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"></script>

<main x-data="App()" x-init="init()">
  <div 
    class="absolute inset-0 p-2 overflow-auto"
  >
    <div class="grid grid-cols-2 justify-between h-full gap-4">
      <!-- layers -->
      <div id="sortableContainer">
        <template x-for="layer in data.layerStructure">
          <ul class="mt-1 mb-1 ml-4" :data-id="layer.id">
            <li class="list-none select-none" x-html="renderLayer(layer)" :data-id="layer.id"></li>
          </ul>
        </template>
      </div>
      
      <!-- json -->
      <textarea x-ref="output" class="resize-none" placeholder="json code here" x-text="JSON.stringify(data.layerStructure, null, 2)"></textarea>
  </div>
</main>

<script src="https://michaelsboost.com/TailwindCSSMod/tailwind-mod.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.15.2/Sortable.min.js"></script>

I've tried several approaches to solve this issue, including:

  1. Implementing SortableJS with Alpine.js to allow dragging and dropping of nested layers.
  2. Utilizing the updateLayerStructure method to update the JSON structure based on the new order after sorting.
  3. Implementing the findLayerById function to recursively find a layer within the nested structure by its ID.

Additionally, I came across a related Stack Overflow post where a user provided a solution using SortableJS to serialize nested lists into JSON. Here is the reference to their approach: SortableJS Get Order from Nested List.

Despite these attempts, I haven't been able to achieve the desired functionality of directly updating specific nodes from HTML to JSON. Could you please suggest any alternative approaches or solutions to make sorting nested JSON layers work correctly with SortableJS in Alpine.js?


Solution

  • where are you setting the data-id?

    // Get the updated order
            const newOrder = Array.from(evt.from.children).map(item => item.dataset.id);
            
            // Update the layer structure based on new order
            this.updateLayerStructure(evt.item.dataset.id, newOrder);
    

    Also, this seems to be returning the template tag not the li,

    evt.from.children
    

    -- EDIT --

    ok, I think I have it working.

    I shrank the data set to be easier to see the changes.

    I removed the alpine template from the renderLayer function, and changed the display of the layer.name, as it was showing the wrong data sometimes. I changed the layer.name to layer.id for testing.

    I changed initializeSortable in a few ways, it now stores the sortable object in a array to get the sort order of each sortable object to build the output, and the onEnd was changed to use a new processing function.

    findLayerById was changed because it kept updating the data.layerStructure when used which would cause the page to freak out because it was used in the alpine x-for template.

    updateLayerStructure was removed since cant update the data.layerStructure as it updated the alpine template and screwed up the display

    processSortable3 was created to generate the output (yes third attempt)

    init was updated to display the first generated output.

    I have a working example at https://codepen.io/terreporter/pen/WNqrWga

    just need to have a way to add new items to the list and i think it would be a nice funcional nestable drag and drop editor.