import { component } from "d3-component";
import { select, local } from "d3-selection";

const codeMirrorLocal = local();

// User interface component for the code editor.
export default component("div", "shadow")
  .create(function ({ onChange }){
    const codeMirror = codeMirrorLocal
      .set(this, CodeMirror(this, {
        lineNumbers: false,
        mode: "htmlmixed"
      }));

    // Inlet provides the interactive sliders and color pickers.
    Inlet(codeMirror);

    codeMirror.on("change", function (editor, change){
      if(change.origin === "setValue") return;
      onChange(codeMirror.getValue());
    });
  })
  .render(function ({ content }){
    const codeMirror = codeMirrorLocal.get(this);
    if(codeMirror.getValue() !== content){ // TODO use timestamp here?
      codeMirror.setValue(content);
    }
  });

//export default function (dispatch, actions){
//  return function (selection, state){
//    var editor = selection.selectAll(".editor").data([1]);
//    editor = editor.merge(
//      editor.enter().append("div")
//        .attr("class", "editor shadow")
//        .each(function (){
//        }));
//
//    if(state.html){
//      editor.each(function (){
//      });
//    }
//  };
//}

@@ -231,20 +231,8 @@
 on (
-%7B onChange %7D
 )%7B%0A 
@@ -236,34 +236,26 @@
 %7B%0A    const 
-codeMirror
+my
  = codeMirro
@@ -260,23 +260,16 @@
 rorLocal
-%0A      
 .set(thi
@@ -270,16 +270,36 @@
 et(this,
+ %7B%0A      codeMirror:
  CodeMir
@@ -376,105 +376,84 @@
   %7D)
-);%0A
+,
 %0A    
-// Inlet provides the interactive sliders and color pickers.%0A    Inlet(codeMirror
+  onChange: undefined // Will be set in the render hook.%0A    %7D
 );%0A%0A    
 code
@@ -444,24 +444,27 @@
    %7D);%0A%0A    
+my.
 codeMirror.o
@@ -551,24 +551,42 @@
 turn;%0A      
+my.onChange && my.
 onChange(cod
@@ -582,16 +582,19 @@
 nChange(
+my.
 codeMirr
@@ -616,16 +616,108 @@
 %0A    %7D);
+%0A%0A    // Inlet provides the interactive sliders and color pickers.%0A    Inlet(my.codeMirror);
 %0A  %7D)%0A  
@@ -743,16 +743,26 @@
  content
+, onChange
  %7D)%7B%0A   
@@ -768,26 +768,18 @@
   const 
-codeMirror
+my
  = codeM
@@ -807,16 +807,19 @@
 %0A    if(
+my.
 codeMirr
@@ -876,24 +876,27 @@
 here?%0A      
+my.
 codeMirror.s
@@ -919,16 +919,44 @@
 ;%0A    %7D%0A
+    my.onChange = onChange;%0A
   %7D);%0A%0A/

Use correct listener in CodeMirror callbacks