Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />

    <title>title</title>
  </head>
  <body>
    Select file
    <input type="file" id="fileinput" />

    <br />
    <br />
    Flat output
    <pre
      style=" max-height: 500px; overflow: auto; border: 1px solid black; min-height: 100px "
    ><code id="outputflat"></code></pre>

    <br />
    <br />
    <br />
    <br />
    Tree output
    <pre
      style=" max-height: 500px; overflow: auto; border: 1px solid black; min-height: 100px "
    ><code id="outputastree"></code></pre>

    <script>
      function handleFileSelect(evt) {
        var files = evt.target.files; // FileList object

        // files is a FileList of File objects. List some properties.
        // var output = [];
        for (var i = 0, f; (f = files[i]); i++) {
          if (!f.type.match("text/csv")) {
            continue;
          }

          var reader = new FileReader();

          // Closure to capture the file information.
          reader.onload = (function(theFile) {
            return function(e) {
              // Render thumbnail.
              // var span = document.createElement('span');
              // span.innerHTML = ['<img class="thumb" src="', e.target.result,
              //                   '" title="', escape(theFile.name), '"/>'].join('');
              // document.getElementById('list').insertBefore(span, null);
              // console.log("Got file text");
              // console.log(e.target.result);

              convertData(e.target.result);
            };
          })(f);

          // Read in the image file as a data URL.
          reader.readAsText(f);

          //   output.push(
          //     "<li><strong>",
          //     escape(f.name),
          //     "</strong> (",
          //     f.type || "n/a",
          //     ") - ",
          //     f.size,
          //     " bytes, last modified: ",
          //     f.lastModifiedDate
          //       ? f.lastModifiedDate.toLocaleDateString()
          //       : "n/a",
          //     "</li>"
          //   );
        }
        // document.getElementById("list").innerHTML =
        //   "<ul>" + output.join("") + "</ul>";
      }

      document
        .getElementById("fileinput")
        .addEventListener("change", handleFileSelect, false);

      function convertData(text) {
        function CSVToArray(text) {
          var re_valid = /^\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*(?:,\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*)*$/;
          var re_value = /(?!\s*$)\s*(?:'([^'\\]*(?:\\[\S\s][^'\\]*)*)'|"([^"\\]*(?:\\[\S\s][^"\\]*)*)"|([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*))\s*(?:,|$)/g;
          // Return NULL if input string is not well formed CSV string.
          if (!re_valid.test(text)) return null;
          var a = []; // Initialize array to receive values.
          text.replace(
            re_value, // "Walk" the string using replace with callback.
            function(m0, m1, m2, m3) {
              // Remove backslash from \' in single quoted values.
              if (m1 !== undefined) a.push(m1.replace(/\\'/g, "'"));
              // Remove backslash from \" in double quoted values.
              else if (m2 !== undefined) a.push(m2.replace(/\\"/g, '"'));
              else if (m3 !== undefined) a.push(m3);
              return ""; // Return empty string.
            }
          );
          // Handle special case of empty last value.
          if (/,\s*$/.test(text)) a.push("");
          return a;
        }

        // const csvData = text.split(/\r?\n/).map(row => row.split("\,"));
        const csvData = text.split(/\r?\n/).map(row => CSVToArray(row));

        const root = {
          children: {},
          parent: null
        };
        let maxDepth = 0;

        // console.log(csvData);
        for (let r = 1; r < csvData.length; r += 1) {
          const row = csvData[r];
          let nextNode = root;
          let currentPath = [];
          for (let c = 0; c < row.length; c += 1) {
            const col = row[c];
            if (col.length === 0) {
              continue;
            }
            currentPath.push(col);
            if (!nextNode.children[col]) {
              nextNode.children[col] = {
                title: col,
                children: {},
                path: [...currentPath],
                depth: currentPath.length - 1,
                parent: nextNode,
                position: Object.keys(nextNode.children).length + 1
              };
              if (currentPath.length - 1 > maxDepth) {
                maxDepth = currentPath.length - 1;
              }
            }
            nextNode = nextNode.children[col];
          }
        }

        // console.log(allItems);
        // console.log(root);
        const rootAsJson = JSON.stringify(
          root,
          (key, obj) => {
            // console.log(key, obj);
            if (key === "parent") {
              if (!obj || !obj.path) {
                return null;
              }
              return obj.path.join(" > ");
            }
            return obj;
          },
          3
        );
        // console.log(rootAsJson);

        // const out = Object.values(allItems)
        document.getElementById("outputastree").innerHTML = rootAsJson;

        function pad(n) {
          let s = String(n);
          while (s.length < 4) {
            s = "0" + s;
          }
          return s;
        }

        const flatList = [];
        function traverseNode(node) {
          node.id = 0;
          let parent = node;
          let nodeDepth = node.depth;
          while (parent) {
            if (typeof parent.position === "number") {
              let p = parent.position;
              for (let i = nodeDepth; i > parent.depth; i -= 1) {
                p = p * 1000;
              }
              node.id += p;
            }
            parent = parent.parent;
          }
          flatList.push({
            id: node.id,
            label: node.title,
            title: node.title,
            value: node.path.join(" > "),
            position: node.position,
            parent: node.parent.id
          });
          Object.values(node.children).map(traverseNode);
        }

        Object.values(root.children).map(traverseNode);

        document.getElementById("outputflat").innerHTML = JSON.stringify(
          flatList,
          null,
          3
        );
      }
    </script>
  </body>
</html>

            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console