<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>{{mytitle}}</title>
        <script src="https://d3js.org/d3.v5.min.js" charset="utf-8"></script>
        <!--<script src="d3-save-svg.min.js"></script>-->
        <script type="text/javascript">
          !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define("d3-save-svg",["exports"],t):t(e.d3_save_svg={})}(this,function(e){"use strict";function t(e,t){window.URL=window.URL||window.webkitURL;var n=new Blob(e.source,{type:"text/xml"}),i=window.URL.createObjectURL(n),o=document.body,r=document.createElement("a");o.appendChild(r),r.setAttribute("download",t+".svg"),r.setAttribute("href",i),r.style.display="none",r.click(),r.parentNode.removeChild(r),setTimeout(function(){window.URL.revokeObjectURL(i)},10)}function n(e){function t(e){var t,n,i,r,s=window.getComputedStyle(e),a="";for(t=0,n=s.length;n>t;t++)i=s[t],r=s.getPropertyValue(i),r!==o.getPropertyValue(i)&&"height"!==i&&"width"!==i&&(a+=i+":"+r+";");e.setAttribute("style",a)}function n(e){function t(e){if(e&&e.hasChildNodes())for(var i=e.firstChild;i;)1===i.nodeType&&"SCRIPT"!=i.nodeName&&(n.push(i),t(i)),i=i.nextSibling}var n=[];return n.push(e),t(e),n}var i=window.document.createElementNS(u.svg,"svg");window.document.body.appendChild(i);for(var o=window.getComputedStyle(i),r=n(e),s=r.length;s--;)t(r[s]);i.parentNode.removeChild(i)}function i(e){e.setAttribute("version","1.1"),e.removeAttribute("xmlns"),e.removeAttribute("xlink"),e.hasAttributeNS(u.xmlns,"xmlns")||e.setAttributeNS(u.xmlns,"xmlns",u.svg),e.hasAttributeNS(u.xmlns,"xmlns:xlink")||e.setAttributeNS(u.xmlns,"xmlns:xlink",u.xlink),n(e);var t=new XMLSerializer,i=t.serializeToString(e),o='<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">',r=e.getBoundingClientRect(),s={top:r.top,left:r.left,width:r.width,height:r.height,"class":e.getAttribute("class"),id:e.getAttribute("id"),childElementCount:e.childElementCount,source:[o+i]};return s}function o(e){for(var t=new Uint8Array(e),n=t.length,i=[];n--;)i[n]=String.fromCharCode(t[n]);var o=window.btoa(i.join(""));return o}function r(e,t){var n,i=new XMLHttpRequest(e);i.open("GET",e,!0),i.responseType="arraybuffer",i.callback=t,i.onload=function(){n=o(this.response),this.callback(null,n)},i.onerror=function(){t("B64 ERROR",null)},i.send()}function s(e){var t=/^\s*data:([a-z]+\/[a-z0-9\-]+(;[a-z\-]+\=[a-z\-]+)?)?(;base64)?,[a-z0-9\!\$\&\'\,\(\)\*\+\,\;\=\-\.\_\~\:\@\/\?\%\s]*\s*$/i;return!!e.match(t)}function a(e,n){if("svg"!==e.nodeName||1!==e.nodeType)throw"Need an svg element input";var n=n||{},o=i(e,n),r=d(o),s=n.filename||r,o=i(e);t(o,s)}function l(e){var t=e.querySelectorAll("image");[].forEach.call(t,function(e){var t=e.getAttribute("href");s(t)||r(t,function(t,n){e.setAttributeNS(u.xlink,"href","data:image/png;base64,"+n)})})}function d(e){var t="untitled";return e.id?t=e.id:e["class"]?t=e["class"]:window.document.title&&(t=window.document.title.replace(/[^a-z0-9]/gi,"-").toLowerCase()),t}var u={svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"},w="0.0.2";e.version=w,e.save=a,e.embedRasterImages=l});
        </script>

    </head>
    <style> /* set the CSS */
        body { font: 24px Arial;
               height: 100%; }
        html { height: 100%; }

        div.tooltip { 
            position: absolute;     
            text-align: left;     
            /*width: 80px;          
            height: 100px;*/
            overflow: auto;
            display: block;
            padding: 2px;       
            font: 12px Arial;    
            background: white; 
            border: 0px;    
            border-radius: 8px;     
            pointer-events: none;     
        }
    </style>
    <pre id="path_data" hidden>
        {{ path_data }}
    </pre>
    <pre id="annotation_data" hidden>
        {{ annotation_data }}
    </pre>
    <pre id="line_data" hidden>
        {{ line_data }}
    </pre>
    <pre id="legend_data" hidden>
        {{ legend_data }}
    </pre>

    <pre id="meta_data"
         height={{height}}
         width={{width}}
         hidden></pre>

    <body>
        <h>{{mytitle}}</h> <button type="button" id="export">Export SVG</button>
        <div id="viz" style="width:95%;height:80%;border:black 1px solid;"> </div>
        <div id="legend" style="width:95%;height:200px;"> </div>
        <script type="text/javascript">
        const path_dataset = JSON.parse(d3.select('pre#path_data').text());
        const line_dataset = JSON.parse(d3.select('pre#line_data').text());
        const legend_dataset = JSON.parse(d3.select('pre#legend_data').text());
        const annotation_dataset = JSON.parse(d3.select('pre#annotation_data').html());
        const height = d3.select('pre#meta_data').attr('height')
        const width = d3.select('pre#meta_data').attr('width')

        // Define the div for the tooltip
        var div = d3.select("body").append("div") 
            .attr("class", "tooltip")       
            .style("opacity", 0);

        var zoom = d3.zoom()
                    //.center([width / 2, height / 2])
                    .scaleExtent([1, 50])
                    .on("zoom", zoomed);
        function _decode(s){return s.replace(/@DBLQ/g, '"').replace(/@LT/g, '<').replace(/@GT/g, '>').replace(/@SL/g, '/');}
        function zoomed() {
            // g.attr("transform", d3.event.transform);
            links.attr("transform",
                       "translate(" + d3.event.transform.x + "," + d3.event.transform.y + ") scale(" + d3.event.transform.k + ")");
            tt.attr("transform",
                       "translate(" + d3.event.transform.x + "," + d3.event.transform.y + ") scale(" + d3.event.transform.k + ")");
        }

        const svg = d3.select("div#viz").append("svg")
                    .attr("viewBox", [0, 0, width, height].join(" "))
                    .attr("width", "100%")
                    .attr("height", "100%")
                    .append("g").call(zoom);
        //svg.append("g").call(zoom);
        //svg.append("tt").call(zoom);

        const rect = svg.append("rect")
                    .attr("width", "100%")
                    .attr("height", "100%")
                    .style("fill", "white")
                    .style("pointer-events", "all");

        const links = svg.append("g");

        links.selectAll("path")
                .data(path_dataset)
                .join("path")
                .attr("d", (d) => d.str_coords)
                //.attr("d", d3.line()((d) => d.coords))
                .attr("stroke", (d) => d.stroke)
                .attr("stroke-width", (d) => d.stroke_width)
                .attr("fill", "transparent")
                .attr("vector-effect", "non-scaling-stroke");

        const tt = svg.append("g");
        
        //Add the lines showing proportions
        links.selectAll("nodes")
              .data(line_dataset)
              .join("line")
              .attr("x1", (d) => d.x1)
              .attr("y1", (d) => d.y1)
              .attr("x2", (d) => d.x2)
              .attr("y2", (d) => d.y2)
              .attr("stroke", (d) => d.stroke)
              .attr("stroke-width", (d) => d.stroke_width)
              .attr("vector-effect", "non-scaling-stroke");
        //Add the tooltip
        tt.selectAll("line")
              .data(annotation_dataset)
              .join("line")
              .attr("x1", (d) => d.x1)
              .attr("y1", (d) => d.y1)
              .attr("x2", (d) => d.x2)
              .attr("y2", (d) => d.y2)
              .attr("stroke", 'transparent')
              .attr("stroke-width", 8)
              .attr("vector-effect", "non-scaling-stroke")
              .on("mouseover", function(d) {    
                    div.transition()    
                        .duration(200)    
                        .style("opacity", 1.0);    
                    div.html(_decode(d.annotation.join("<br/>")))
                        .style("left", (d3.event.pageX) + "px")   
                        .style("top", (d3.event.pageY - 28) + "px");
                    })          
                .on("mouseout", function(d) {   
                    div.transition()    
                        .duration(500)    
                        .style("opacity", 0); 
                });

        // Add one dot in the legend for each name.
        var legend_svg = d3.select("div#legend").attr("height", (20 + legend_dataset.length*(size+5)) + "px")
                    .append("svg")
                    .attr("width", "100%")
                    .attr("height", "100%")
                    .append("g")

        var size = 20
        legend_svg.selectAll("squares")
                  .data(legend_dataset)
                  .enter()
                  .append("rect")
                    .attr("x", 10)
                    .attr("y", function(d,i){ return 10 + i*(size+5)})
                    .attr("width", size)
                    .attr("height", size)
                    .style("fill", function(d){ return d.color})

        legend_svg.selectAll("labels")
                  .data(legend_dataset)
                  .enter()
                  .append("text")
                    .attr("x", 10 + size*1.2)
                    .attr("y", function(d,i){ return 10 + i*(size+5) + (size/2)})
                    .style("fill", function(d){ return d.color})
                    .text(function(d){ return d.label})
                    .attr("text-anchor", "left")
                    .style("alignment-baseline", "middle")
        
        d3.select('button#export').on('click', function() {
              var config = { filename: 'hierdiff' }
              d3_save_svg.save(d3.select('svg').node(), config);
        });
        
    </script>

    </body>
</html>