自定义图表控件未在SAPui5中呈现

时间:2017-06-01 05:13:48

标签: custom-controls sapui5 sap-fiori



<html>

<head>
  <title>Patient Medication Adherence</title>
  <script src="http://d3js.org/d3.v2.js"></script>
</head>
<style>
  body {
    font: 11px sans-serif;
  }
  
  .axis path,
  .axis line {
    fill: none;
    stroke: #000;
    shape-rendering: crispEdges;
  }
  
  .dot {
    stroke: #000;
  }
  
  .tooltip {
    position: absolute;
    width: 200px;
    height: 28px;
    pointer-events: none;
  }
</style>

<body>

  <script>
    var cValue = function(d) {
      return d.time;
    };
    var textValue = function(d) {
      var time = parseInt(d.toString().substr(16, 2));
      if (time > 8 && time < 12) {
        return "Breakfast";
      } else if (time > 12 && time < 17) {
        return "Lunch";
      }
      if (time > 18 && time < 23) {
        return "Dinner";
      }
    };
    color = d3.scale.category10();

    var data = [{
        "date": "30-Dec-16",
        "Text": "Lunch",
        "time": "Mon Dec 30 2016 16:29:23 GMT+0530 (India Standard Time)",
        "close": "30"
      },
      {
        "date": "30-Dec-16",
        "Text": "Breakfast",
        "time": "Mon Jan 27 2017 11:29:23 GMT+0530 (India Standard Time)",
        "close": "20"
      },

      {
        "date": "30-Dec-16",
        "Text": "Dinner",
        "time": "Mon Feb 10 2017 21:29:23 GMT+0530 (India Standard Time)",
        "close": "10"
      },
      {
        "date": "01-Jan-17",
        "Text": "Lunch",
        "time": "Mon Dec 30 2016 16:29:23 GMT+0530 (India Standard Time)",
        "close": "30"
      },
      {
        "date": "01-Jan-17",
        "Text": "Breakfast",
        "time": "Mon Jan 27 2017 11:29:23 GMT+0530 (India Standard Time)",
        "close": "20"
      },

      {
        "date": "01-Jan-17",
        "Text": "Dinner",
        "time": "Mon Feb 10 2017 21:29:23 GMT+0530 (India Standard Time)",
        "close": "10"
      }
    ];
    var dateformat = d3.time.format("%H:%M").parse;
    var parseDate = d3.time.format("%d-%b-%y").parse;
    data.forEach(function(d) {
      d.date = parseDate(d.date);
      //d.time=formattedDateTime(d.time);
      //d3.time.format('%H %M')(new Date(d.time));
      var today = new Date()
      var time = new Date(d.time)
      today.setHours(time.getHours(), time.getMinutes(), time.getSeconds(), time.getMilliseconds())
      d.time = today;
    });



    var width = 1660;
    height = 700;
    padding = 100;
    var margin = {
        top: 20,
        right: 20,
        bottom: 30,
        left: 40
      },
      width = 1260 - margin.left - margin.right,
      height = 500 - margin.top - margin.bottom;
    // create an svg container
    var vis = d3.select("body").
    append("svg:svg")
      .attr("width", width)
      .attr("height", height);
    // add the graph canvas to the body of the webpage
    vis = d3.select("body").append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
      .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
    // define the y scale  (vertical)


    var mindate = new Date(2012, 0, 1),
      maxdate = new Date(2012, 0, 31);

    var start_of_day = new Date()
    start_of_day.setHours(0, 0, 0, 0)
    var end_of_day = new Date()
    end_of_day.setHours(23, 59, 59, 999)

    var yScale = d3.time.scale()
      .domain([start_of_day, end_of_day])
      .nice(d3.time.day) // values between 0 and 100
      .range([height - padding, padding]); // map these to the chart height, less padding.  
    //REMEMBER: y axis range has the bigger number first because the y value of zero is at the top of chart and increases as you go down.

    // define the x scale (horizontal)
    var mindate = new Date(2016, 11, 1),
      maxdate = new Date();

    var xScale = d3.time.scale()
      .domain([mindate, maxdate]) // values between for month of january
      .range([padding, width - padding * 2]); // map these the the chart width = total width minus padding at both sides


    // define the y axis

    var yValue = function(d) {
      return d.time;
    }; // data -> value
    var yMap = function(d) {
      return yScale(yValue(d));
    };
    var yAxis = d3.svg.axis()
      .orient("left")
      .scale(yScale).ticks(24).tickFormat(d3.time.format("%H:%M"));

    // define the x axis
    // setup x 
    var xValue = function(d) {
      return d.date;
    }; // data -> value
    // value -> display
    xMap = function(d) {
      return xScale(xValue(d));
    };
    var xAxis = d3.svg.axis()
      .orient("bottom")
      .scale(xScale).tickFormat(d3.time.format("%Y-%m-%d"));

    // draw y axis with labels and move in from the size by the amount of padding
    vis.append("g")
      .attr("transform", "translate(" + padding + ",0)")
      .style({
        'stroke': 'Black',
        'fill': 'none',
        'stroke-width': '1px'
      })

      .call(yAxis);

    // draw x axis with labels and move to the bottom of the chart area
    vis.append("g")
      .attr("class", "xaxis") // give it a class so it can be used to select only xaxis labels  below
      // .attr("transform", "translate(0," + (height - padding) + ")")
      .attr("transform", "translate(0," + (height - padding) + ")")
      .style({
        'stroke': 'Black',
        'fill': 'none',
        'stroke-width': '1px'
      })

      .call(xAxis);

    // draw dots

    vis.selectAll(".dot")
      .data(data)
      .enter().append("circle")
      .attr("class", "dot")
      .attr("r", 3.5)
      .attr("cx", xMap)
      .attr("cy", yMap)
      .style("fill", function(d) {
        var time = parseInt(d.time.toString().substr(16, 2));

        return color(cValue(d));
      })
      .on("mouseover", function(d) {
        tooltip.transition()
          .duration(200)
          .style("opacity", .9);
        tooltip.html(d["Cereal Name"] + "<br/> (" + xValue(d) +
            ", " + yValue(d) + ")")
          .style("left", (d3.event.pageX + 5) + "px")
          .style("top", (d3.event.pageY - 28) + "px");
      })
      .on("mouseout", function(d) {
        tooltip.transition()
          .duration(500)
          .style("opacity", 0);
      });

    // now rotate text on x axis
    // solution based on idea here: https://groups.google.com/forum/?fromgroups#!topic/d3-js/heOBPQF3sAY
    // first move the text left so no longer centered on the tick
    // then rotate up to get 45 degrees.
    vis.selectAll(".xaxis text") // select all the text elements for the xaxis
      .attr("transform", function(d) {
        return "translate(" + this.getBBox().height + "," + this.getBBox().height + ")";
      });
    // draw legend
    var legend = vis.selectAll(".legend")
      .data(color.domain())
      .enter().append("g")
      .attr("class", "legend")
      .attr("transform", function(d, i) {
        return "translate(0," + i * 20 + ")";
      });

    // draw legend colored rectangles
    legend.append("rect")
      .attr("x", width - 18)
      .attr("width", 18)
      .attr("height", 18)
      .style("fill", color);

    // draw legend text
    legend.append("text")
      .attr("x", width - 24)
      .attr("y", 9)
      .attr("dy", ".35em")
      .style("text-anchor", "end")
      .text(function(d) {
        return textValue(d);
      });
  </script>

</body>

</html>
&#13;
&#13;
&#13;

我是自定义控件的新手(使用D3.js和Sap ui5)。我阅读了一些教程并尝试了一下,但不知何故控件无法渲染。此外,控制台中不显示任何错误。

当我调试时,我看到渲染器函数和onAfterRendering函数被调用。任何帮助将受到高度赞赏。

&#13;
&#13;
//THis is my code written in Controller, where i Instantiate my custom chart control
jQuery.sap.require("hc.pe.managepatients.controller.D3Chart");
var oRadarHolder = this.getView().byId("radarHolder");
var oRadar = new hc.pe.managepatients.controller.D3Chart({
  axis: "{axis}",
  value: "{value}"
});
oRadarHolder.addContent(oRadar);
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData(

  [{
    "axis": "30-Dec-16",
    "Text": "Lunch",
    "value": "Mon Dec 30 2016 16:29:23 GMT+0530 (India Standard Time)",
    "close": "30"
  }, {
    "axis": "30-Dec-16",
    "Text": "Breakfast",
    "value": "Mon Jan 27 2017 11:29:23 GMT+0530 (India Standard Time)",
    "close": "20"
  }]);

oRadar.setModel(oModel);
this.getView().byId("radarHolder").addContent(oRadar);
&#13;
&#13;
&#13;

- &GT;

jQuery.sap.require("sap/ui/thirdparty/d3");
jQuery.sap.declare("hc.pe.managepatients.controller.D3Chart");
sap.ui.core.Control.extend("hc.pe.managepatients.controller.D3Chart", {
  metadata: {
    properties: {
      "axis": {
        type: "string",
        group: "Misc",
        defaultValue: null
      },
      "value": {
        type: "string",
        group: "Misc",
        defaultValue: null
      }
    }
  },
  init: function() {
    console.log("Getting ready to weave a web");
    this.sParentId = "";
  },
  createChart: function() {
    /*
     * Called from renderer
     */
    console.log("hc.pe.managepatients.controls.D3Chart.createChart()");
    var oChartLayout = new sap.m.VBox({
      alignItems: sap.m.FlexAlignItems.Center,
      justifyContent: sap.m.FlexJustifyContent.Center
    });
    var oChartFlexBox = new sap.m.FlexBox({
      //height: "180 px",
      alignItems: sap.m.FlexAlignItems.Center
    });
    /* ATTENTION: Important
     * This is where the magic happens: we need a handle for our SVG to attach to. We can get this using .getIdForLabel()
     * Check this in the 'Elements' section of the Chrome Devtools:
     * By creating the layout and the Flexbox, we create elements specific for this control, and SAPUI5 takes care of
     * ID naming. With this ID, we can append an SVG tag inside the FlexBox
     */
    this.sParentId = oChartFlexBox.getIdForLabel();
    oChartLayout.addItem(oChartFlexBox);

    return oChartLayout;
  },
  renderer: function(oRm, oControl) {
    var layout = oControl.createChart();
    oRm.write("<div");
    oRm.writeControlData(layout); // writes the Control ID and enables event handling – important!
    oRm.writeClasses(); // there is no class to write, but this enables
    // support for ColorBoxContainer.addStyleClass(…)          
    oRm.write(">");
    oRm.renderControl(layout);
    oRm.addClass('verticalAlignment');
    oRm.write("</div>");
  },
  onAfterRendering: function() {
    var width = 1660;
    var height = 700;
    var padding = 100;
    var margin = {
        top: 20,
        right: 20,
        bottom: 30,
        left: 40
      },
      width = 1260 - margin.left - margin.right,
      height = 500 - margin.top - margin.bottom;
    var color;
    console.log("hc.pe.managepatients.controls.D3Chart.onAfterRendering()");
    console.log(this.sParentId);
    //var cItems = this.getItems();
    var data = [];
    /*  /*  for (var i = 0; i < cItems.length; i++) {
                var oEntry = {};
                for (var j in cItems[i].mProperties) {
                    oEntry[j] = cItems[i].mProperties[j];
                }
                data.push(oEntry);
            }*/
    */
    //console.log("Data:");
    //console.log(data);

    /*
     * ATTENTION: See .createChart()
     * Here we're picking up a handle to the "parent" FlexBox with the ID we got in .createChart()
     * Now simply .append SVG elements as desired
     * EVERYTHING BELOW THIS IS PURE D3.js
     */

    var vis = d3.select("#" + this.sParentId);
    vis.append("svg:svg")
      .attr("width", width)
      .attr("height", height);
    // add the graph canvas to the body of the webpage
    vis = d3.select("body").append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
      .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
    // define the y scale  (vertical)

    var mindate = new Date(2012, 0, 1),
      maxdate = new Date(2012, 0, 31);

    var start_of_day = new Date();
    start_of_day.setHours(0, 0, 0, 0);
    var end_of_day = new Date();
    end_of_day.setHours(23, 59, 59, 999);
    var yScale = d3.time.scale()
      .domain([start_of_day, end_of_day])
      .nice(d3.time.day) // values between 0 and 100
      .range([height - padding, padding]); // map these to the chart height, less padding.  
    //REMEMBER: y axis range has the bigger number first because the y value of zero is at the top of chart and increases as you go down.

    // define the x scale (horizontal)
    var mindate = new Date(2016, 11, 1),
      maxdate = new Date();

    var xScale = d3.time.scale()
      .domain([mindate, maxdate]) // values between for month of january
      .range([padding, width - padding * 2]); // map these the the chart width = total width minus padding at both sides

    // define the y axis

    var yValue = function(d) {
      return d.time;
    }; // data -> value
    var yMap = function(d) {
      return yScale(yValue(d));
    };
    var yAxis = d3.svg.axis()
      .orient("left")
      .scale(yScale).ticks(24).tickFormat(d3.time.format("%H:%M"));

    // define the x axis
    // setup x 
    var xValue = function(d) {
      return d.date;
    }; // data -> value
    // value -> display
    var xMap = function(d) {
      return xScale(xValue(d));
    };
    var xAxis = d3.svg.axis()
      .orient("bottom")
      .scale(xScale).tickFormat(d3.time.format("%Y-%m-%d"));

    // draw y axis with labels and move in from the size by the amountf of padding
    vis.append("g")
      .attr("transform", "translate(" + padding + ",0)")
      .style({
        'stroke': 'Black',
        'fill': 'none',
        'stroke-width': '1px'
      })

      .call(yAxis);

    // draw x axis with labels and move to the bottom of the chart area
    vis.append("g")
      .attr("class", "xaxis") // give it a class so it can be used to select only xaxis labels  below
      // .attr("transform", "translate(0," + (height - padding) + ")")
      .attr("transform", "translate(0," + (height - padding) + ")")
      .style({
        'stroke': 'Black',
        'fill': 'none',
        'stroke-width': '1px'
      })

      .call(xAxis);

    // draw dots

    vis.selectAll(".dot")
      //    .enter().append("circle")
      .attr("class", "dot")
      .attr("r", 3.5)
      .attr("cx", xMap)
      .attr("cy", yMap)
      .style("fill", function(d) {
        var time = parseInt(d.time.toString().substr(16, 2));

        return color(cValue(d));
      })
      .on("mouseover", function(d) {
        tooltip.transition()
          .duration(200)
          .style("opacity", .9);
        tooltip.html(d["Cereal Name"] + "<br/> (" + xValue(d) +
            ", " + yValue(d) + ")")
          .style("left", (d3.event.pageX + 5) + "px")
          .style("top", (d3.event.pageY - 28) + "px");
      })
      .on("mouseout", function(d) {
        tooltip.transition()
          .duration(500)
          .style("opacity", 0);
      });

    // now rotate text on x axis
    // solution based on idea here: https://groups.google.com/forum/?fromgroups#!topic/d3-js/heOBPQF3sAY
    // first move the text left so no longer centered on the tick
    // then rotate up to get 45 degrees.

    var cValue = function(d) {
      return d.time;
    };
    var textValue = function(d) {
      var time = parseInt(d.toString().substr(16, 2));
      if (time > 8 && time < 12) {
        return "Breakfast";
      } else if (time > 12 && time < 17) {
        return "Lunch";
      }
      if (time > 18 && time < 23) {
        return "Dinner";
      }
    };
    color = d3.scale.category10();

    var data = [{
        "date": "30-Dec-16",
        "Text": "Lunch",
        "time": "Mon Dec 30 2016 16:29:23 GMT+0530 (India Standard Time)",
        "close": "30"
      }, {
        "date": "30-Dec-16",
        "Text": "Breakfast",
        "time": "Mon Jan 27 2017 11:29:23 GMT+0530 (India Standard Time)",
        "close": "20"
      },

      {
        "date": "30-Dec-16",
        "Text": "Dinner",
        "time": "Mon Feb 10 2017 21:29:23 GMT+0530 (India Standard Time)",
        "close": "10"
      }, {
        "date": "01-Jan-17",
        "Text": "Lunch",
        "time": "Mon Dec 30 2016 16:29:23 GMT+0530 (India Standard Time)",
        "close": "30"
      }, {
        "date": "01-Jan-17",
        "Text": "Breakfast",
        "time": "Mon Jan 27 2017 11:29:23 GMT+0530 (India Standard Time)",
        "close": "20"
      },

      {
        "date": "01-Jan-17",
        "Text": "Dinner",
        "time": "Mon Feb 10 2017 21:29:23 GMT+0530 (India Standard Time)",
        "close": "10"
      }
    ];
    var dateformat = d3.time.format("%H:%M").parse;
    var parseDate = d3.time.format("%d-%b-%y").parse;
    data.forEach(function(d) {
      d.date = parseDate(d.date);
      //d.time=formattedDateTime(d.time);
      //d3.time.format('%H %M')(new Date(d.time));
      var today = new Date();
      var time = new Date(d.time);
      today.setHours(time.getHours(), time.getMinutes(), time.getSeconds(), time.getMilliseconds());
      d.time = today;
    });

    var width = 1660;
    var height = 700;
    var padding = 100;
    var margin = {
        top: 20,
        right: 20,
        bottom: 30,
        left: 40
      },
      width = 1260 - margin.left - margin.right,
      height = 500 - margin.top - margin.bottom;
    vis.selectAll(".xaxis text") // select all the text elements for the xaxis
      .attr("transform", function(d) {
        return "translate(" + this.getBBox().height + "," + this.getBBox().height + ")";
      });
    // draw legend
    var legend = vis.selectAll(".legend")
      .data(color.domain())
      .enter().append("g")
      .attr("class", "legend")
      .attr("transform", function(d, i) {
        return "translate(0," + i * 20 + ")";
      });

    // draw legend colored rectangles
    legend.append("rect")
      .attr("x", width - 18)
      .attr("width", 18)
      .attr("height", 18)
      .style("fill", color);

    // draw legend text
    legend.append("text")
      .attr("x", width - 24)
      .attr("y", 9)
      .attr("dy", ".35em")
      .style("text-anchor", "end")
      .text(function(d) {
        return textValue(d);
      });

    //Your D3.js code HERE

  }
});

0 个答案:

没有答案