Search code examples
d3.jsdartdart-polymer

How to embed a D3 chart in a Polymer.dart element?


Browser: Dartium Version 34.0.1847.0 (258268)

I want to embed D3 inside Polymer.dart elements and I'm just beginning to sort out how Dart and JS interoperate. I started by creating a vanilla HTML page using HTML5/CSS3/JS from D3's introductory tutorial on how to make a bar chart to be sure my D3 implementation worked in Dartium.

I then moved the D3 code into a custom polymer element (shown below) and its companion dart source file (not shown). How do I instruct D3 to perform its selection inside the shadow DOM?

<!-- D3 code copied from: http://bost.ocks.org/mike/bar/ -->
<polymer-element name="dart-js">
    <template>
        <!-- D3 style -->
        <style>
            .chart div {
                font: 10px sans-serif;
                background-color: steelblue;
                text-align: right;
                padding: 3px;
                margin: 1px;
                color: white;
            }
        </style>

        <content>
            <!-- D3 container -->
            <div class="chart">inside dart-js shadow-root</div>

            <!-- D3 JS -->
            <script type="application/javascript">
                console.log("inside content");

                var data = [4, 8, 15, 16, 23, 42];
                console.log("data: " + data); // data: 4,8,15,16,23,42

                console.log("select: <" + d3.select(".chart") + ">"); // select: <>

                // How do I instruct d3 to search inside the shadow DOM?
                d3.select(".chart")
                        .selectAll("div")
                        .data(data)
                        .enter().append("div")
                        .style("width", function (d) { return d * 10 + "px"; })
                        .text(function (d) { return d; })

            </script>
        </content>

    </template>
    <script type="application/dart;component=1" src="dart_js.dart"></script>
</polymer-element>

Solution

  • d3 can't find elements inside a shadowDOM but you look up the element in Dart and pass it to d3's select method.

    something like this (not tested)

    import 'dart:js' as js;
    
    js.context['d3'].callMethod('select', [shadowRoot.querySelector('.chart')]);
    

    more info about Dart-JS-interop: https://www.dartlang.org/articles/js-dart-interop/