{%- macro jupyter_widgets(widgets_cdn_url, html_manager_semver_range, widget_renderer_url='') -%}

<script>
(function() {
  function addWidgetsRenderer() {
    var mimeElement = document.querySelector('script[type="application/vnd.jupyter.widget-view+json"]');
    var scriptElement = document.createElement('script');
    {% if widget_renderer_url %}   
    var widgetRendererSrc = '{{ widget_renderer_url }}';
    {% else %}
    var widgetRendererSrc = '{{ widgets_cdn_url }}@jupyter-widgets/html-manager@{{ html_manager_semver_range }}/dist/embed-amd.js';
    {%endif %}
    var widgetState;

    // Fallback for older version:
    try {
      widgetState = mimeElement && JSON.parse(mimeElement.innerHTML);

      if (widgetState && (widgetState.version_major < 2 || !widgetState.version_major)) {
        {% if widget_renderer_url %}   
        var widgetRendererSrc = '{{ widget_renderer_url }}';
        {% else %}
        var widgetRendererSrc = '{{ widgets_cdn_url }}@jupyter-js-widgets@*/dist/embed.js';
        {%endif %}
      }
    } catch(e) {}

    scriptElement.src = widgetRendererSrc;
    document.body.appendChild(scriptElement);
  }

  document.addEventListener('DOMContentLoaded', addWidgetsRenderer);
}());
</script>

{%- endmacro %}
