The Unified and Autonomous Development Platform
Rewrite contribution stats page
robin shen2cdbe517f185
diff --git a/core/src/main/java/io/onedev/server/git/Contributor.java b/core/src/main/java/io/onedev/server/git/Contributor.javaindex 6c9707b2ff..ac75656962 100644--- a/core/src/main/java/io/onedev/server/git/Contributor.java+++ b/core/src/main/java/io/onedev/server/git/Contributor.java@@ -11,20 +11,27 @@ public class Contributor implements Serializable {private static final long serialVersionUID = 1L;- private final PersonIdent user;+ private final PersonIdent author;- private final Map<Day, Contribution> dailyContributions;+ private final Contribution totalContribution;- public Contributor(PersonIdent user, Map<Day, Contribution> dailyContributions) {- this.user = user;+ private final Map<Day, Integer> dailyContributions;++ public Contributor(PersonIdent author, Contribution totalContribution, Map<Day, Integer> dailyContributions) {+ this.author = author;+ this.totalContribution = totalContribution;this.dailyContributions = dailyContributions;}- public PersonIdent getUser() {- return user;+ public PersonIdent getAuthor() {+ return author;+ }++ public Contribution getTotalContribution() {+ return totalContribution;}- public Map<Day, Contribution> getDailyContributions() {+ public Map<Day, Integer> getDailyContributions() {return dailyContributions;}diff --git a/core/src/main/java/io/onedev/server/manager/CommitInfoManager.java b/core/src/main/java/io/onedev/server/manager/CommitInfoManager.javaindex 248273a823..83fdb14847 100644--- a/core/src/main/java/io/onedev/server/manager/CommitInfoManager.java+++ b/core/src/main/java/io/onedev/server/manager/CommitInfoManager.java@@ -43,12 +43,12 @@ public interface CommitInfoManager {Collection<String> getHistoryPaths(Project project, String path);/**- * Get list of contributions, ordered by day+ * Get overall contributions** @param project* project to get daily commits for* @return- * list of contributions, ordered by day+ * map of day to contribution*/Map<Day, Contribution> getOverallContributions(Project project);@@ -59,7 +59,7 @@ public interface CommitInfoManager {* project to get top contributors for* @param top* number of top contributors to get- * @param orderBy+ * @param type* type of contribution to order by* @param fromDay* from day@@ -68,8 +68,7 @@ public interface CommitInfoManager {* @return* list of top user contributors, reversely ordered by number of contributions*/- List<Contributor> getTopContributors(Project project, int top, Contribution.Type orderBy,- Day fromDay, Day toDay);+ List<Contributor> getTopContributors(Project project, int top, Contribution.Type type, Day fromDay, Day toDay);/*** Get source code line statistics over timediff --git a/core/src/main/java/io/onedev/server/manager/impl/DefaultCommitInfoManager.java b/core/src/main/java/io/onedev/server/manager/impl/DefaultCommitInfoManager.javaindex 84db3e6700..29c077d71a 100644--- a/core/src/main/java/io/onedev/server/manager/impl/DefaultCommitInfoManager.java+++ b/core/src/main/java/io/onedev/server/manager/impl/DefaultCommitInfoManager.java@@ -1204,7 +1204,7 @@ public class DefaultCommitInfoManager extends AbstractEnvironmentManager impleme@Sessional@Override- public List<Contributor> getTopContributors(Project project, int top, Contribution.Type orderBy,+ public List<Contributor> getTopContributors(Project project, int top, Contribution.Type type,Day fromDay, Day toDay) {Environment env = getEnv(project.getId().toString());Store defaultStore = getStore(env, DEFAULT_STORE);@@ -1217,35 +1217,39 @@ public class DefaultCommitInfoManager extends AbstractEnvironmentManager implemepublic List<Contributor> compute(Transaction txn) {Map<Integer, Contribution> overallContributions =deserializeContributions(readBytes(defaultStore, txn, OVERALL_CONTRIBUTIONS_KEY));- Map<Integer, Integer> orderByValues = new HashMap<>();+ Map<Integer, Contribution> totalContributions = new HashMap<>();for (int dayValue: overallContributions.keySet()) {if (dayValue >= fromDay.getValue() && dayValue <= toDay.getValue()) {ByteIterable dayKey = new IntByteIterable(dayValue);Map<Integer, Contribution> contributionsOnDay =deserializeContributions(readBytes(dailyContributionsStore, txn, dayKey));for (Map.Entry<Integer, Contribution> entry: contributionsOnDay.entrySet()) {- int orderByValue;- if (orderBy == Contribution.Type.COMMITS)- orderByValue = entry.getValue().getCommits();- else if (orderBy == Contribution.Type.ADDITIONS)- orderByValue = entry.getValue().getAdditions();- else- orderByValue = entry.getValue().getDeletions();Integer userIndex = entry.getKey();- Integer existingOrderByValue = orderByValues.get(userIndex);- if (existingOrderByValue != null)- orderByValue += existingOrderByValue;- orderByValues.put(userIndex, orderByValue);+ Contribution totalContribution = totalContributions.get(userIndex);+ if (totalContribution == null) {+ totalContribution = entry.getValue();+ } else {+ totalContribution = new Contribution(+ totalContribution.getCommits() + entry.getValue().getCommits(),+ totalContribution.getAdditions() + entry.getValue().getAdditions(),+ totalContribution.getDeletions() + entry.getValue().getDeletions());+ }+ totalContributions.put(userIndex, totalContribution);}}}- List<Integer> topUserIndexes = new ArrayList<>(orderByValues.keySet());+ List<Integer> topUserIndexes = new ArrayList<>(totalContributions.keySet());Collections.sort(topUserIndexes, new Comparator<Integer>() {@Overridepublic int compare(Integer o1, Integer o2) {- return orderByValues.get(o2) - orderByValues.get(o1);+ if (type == Contribution.Type.COMMITS)+ return totalContributions.get(o2).getCommits() - totalContributions.get(o1).getCommits();+ else if (type == Contribution.Type.ADDITIONS)+ return totalContributions.get(o2).getAdditions() - totalContributions.get(o1).getAdditions();+ else+ return totalContributions.get(o2).getDeletions() - totalContributions.get(o1).getDeletions();}});@@ -1255,7 +1259,7 @@ public class DefaultCommitInfoManager extends AbstractEnvironmentManager implemeSet<Integer> topUserIndexSet = new HashSet<>(topUserIndexes);- Map<Integer, Map<Day, Contribution>> userContributions = new HashMap<>();+ Map<Integer, Map<Day, Integer>> userContributions = new HashMap<>();for (int dayValue: overallContributions.keySet()) {if (dayValue >= fromDay.getValue() && dayValue <= toDay.getValue()) {@@ -1266,12 +1270,17 @@ public class DefaultCommitInfoManager extends AbstractEnvironmentManager implemefor (Map.Entry<Integer, Contribution> entry: contributionsOnDay.entrySet()) {Integer userIndex = entry.getKey();if (topUserIndexSet.contains(userIndex)) {- Map<Day, Contribution> contributionsByUser = userContributions.get(userIndex);+ Map<Day, Integer> contributionsByUser = userContributions.get(userIndex);if (contributionsByUser == null) {contributionsByUser = new HashMap<>();userContributions.put(userIndex, contributionsByUser);}- contributionsByUser.put(day, entry.getValue());+ if (type == Contribution.Type.COMMITS)+ contributionsByUser.put(day, entry.getValue().getCommits());+ else if (type == Contribution.Type.ADDITIONS)+ contributionsByUser.put(day, entry.getValue().getAdditions());+ else+ contributionsByUser.put(day, entry.getValue().getDeletions());}}}@@ -1281,10 +1290,10 @@ public class DefaultCommitInfoManager extends AbstractEnvironmentManager implemefor (int userIndex: topUserIndexes) {byte[] userBytes = readBytes(indexToUserStore, txn, new IntByteIterable(userIndex));- Map<Day, Contribution> contributionsByUser = userContributions.get(userIndex);+ Map<Day, Integer> contributionsByUser = userContributions.get(userIndex);if (userBytes != null && contributionsByUser != null) {PersonIdent user = ((NameAndEmail)SerializationUtils.deserialize(userBytes)).asPersonIdent();- contributors.add(new Contributor(user, contributionsByUser));+ contributors.add(new Contributor(user, totalContributions.get(userIndex), contributionsByUser));}}diff --git a/core/src/main/java/io/onedev/server/util/Day.java b/core/src/main/java/io/onedev/server/util/Day.javaindex 318d91e41a..ca19925fbf 100644--- a/core/src/main/java/io/onedev/server/util/Day.java+++ b/core/src/main/java/io/onedev/server/util/Day.java@@ -33,9 +33,6 @@ public class Day implements Serializable, Comparable<Day> {public Date getDate() {return dateTime.toDate();}- public DateTime getDateTime() {- return dateTime;- }public int getValue() {return (dateTime.getYear()<<16) | (dateTime.getMonthOfYear()<<8) | (dateTime.getDayOfMonth());diff --git a/core/src/main/java/io/onedev/server/web/page/project/stats/ContributionListPanel.html b/core/src/main/java/io/onedev/server/web/page/project/stats/ContributionListPanel.htmldeleted file mode 100644index 888f0065d6..0000000000--- a/core/src/main/java/io/onedev/server/web/page/project/stats/ContributionListPanel.html+++ /dev/null@@ -1,3 +0,0 @@-<wicket:panel>- <table wicket:id="table" class="table table-condensed"></table>-</wicket:panel>\ No newline at end of filediff --git a/core/src/main/java/io/onedev/server/web/page/project/stats/ContributionListPanel.java b/core/src/main/java/io/onedev/server/web/page/project/stats/ContributionListPanel.javadeleted file mode 100644index 0ca9a16c7c..0000000000--- a/core/src/main/java/io/onedev/server/web/page/project/stats/ContributionListPanel.java+++ /dev/null@@ -1,107 +0,0 @@-package io.onedev.server.web.page.project.stats;--import java.util.ArrayList;-import java.util.Iterator;-import java.util.List;--import org.apache.wicket.extensions.ajax.markup.html.repeater.data.table.AjaxNavigationToolbar;-import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;-import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;-import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;-import org.apache.wicket.extensions.markup.html.repeater.data.table.HeadersToolbar;-import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;-import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;-import org.apache.wicket.markup.html.basic.Label;-import org.apache.wicket.markup.html.panel.Panel;-import org.apache.wicket.markup.repeater.Item;-import org.apache.wicket.model.IModel;-import org.apache.wicket.model.Model;--import io.onedev.server.util.DateUtils;-import io.onedev.server.web.WebConstants;--@SuppressWarnings("serial")-class ContributionListPanel extends Panel {-- public ContributionListPanel(String id, IModel<List<DayContribution>> contributionsModel) {- super(id, contributionsModel);- }-- @Override- protected void onInitialize() {- super.onInitialize();-- List<IColumn<DayContribution, Void>> columns = new ArrayList<>();-- columns.add(new AbstractColumn<DayContribution, Void>(Model.of("Date")) {-- @Override- public void populateItem(Item<ICellPopulator<DayContribution>> cellItem, String componentId,- IModel<DayContribution> rowModel) {- cellItem.add(new Label(componentId, DateUtils.formatDate(rowModel.getObject().getDay().getDate())));- }- });-- columns.add(new AbstractColumn<DayContribution, Void>(Model.of("Commits")) {-- @Override- public void populateItem(Item<ICellPopulator<DayContribution>> cellItem, String componentId,- IModel<DayContribution> rowModel) {- cellItem.add(new Label(componentId, rowModel.getObject().getContribution().getCommits()));- }- });-- columns.add(new AbstractColumn<DayContribution, Void>(Model.of("Additions")) {-- @Override- public void populateItem(Item<ICellPopulator<DayContribution>> cellItem, String componentId,- IModel<DayContribution> rowModel) {- cellItem.add(new Label(componentId, rowModel.getObject().getContribution().getAdditions()));- }- });-- columns.add(new AbstractColumn<DayContribution, Void>(Model.of("Deletions")) {-- @Override- public void populateItem(Item<ICellPopulator<DayContribution>> cellItem, String componentId,- IModel<DayContribution> rowModel) {- cellItem.add(new Label(componentId, rowModel.getObject().getContribution().getDeletions()));- }- });-- SortableDataProvider<DayContribution, Void> dataProvider = new SortableDataProvider<DayContribution, Void>() {-- @Override- public Iterator<? extends DayContribution> iterator(long first, long count) {- if (first + count <= getContribution().size())- return getContribution().subList((int)first, (int)(first+count)).iterator();- else- return getContribution().subList((int)first, getContribution().size()).iterator();- }-- @Override- public long size() {- return getContribution().size();- }-- @Override- public IModel<DayContribution> model(DayContribution object) {- return Model.of(object);- }- };-- DataTable<DayContribution, Void> contributionTable =- new DataTable<DayContribution, Void>("table", columns, dataProvider, WebConstants.PAGE_SIZE);-- contributionTable.addTopToolbar(new HeadersToolbar<>(contributionTable, dataProvider));- contributionTable.addBottomToolbar(new AjaxNavigationToolbar(contributionTable));- contributionTable.setOutputMarkupId(true);- add(contributionTable);- }-- @SuppressWarnings("unchecked")- private List<DayContribution> getContribution() {- return (List<DayContribution>) getDefaultModelObject();- }--}diff --git a/core/src/main/java/io/onedev/server/web/page/project/stats/DayContribution.java b/core/src/main/java/io/onedev/server/web/page/project/stats/DayContribution.javadeleted file mode 100644index b11d5a0bea..0000000000--- a/core/src/main/java/io/onedev/server/web/page/project/stats/DayContribution.java+++ /dev/null@@ -1,34 +0,0 @@-package io.onedev.server.web.page.project.stats;--import java.io.Serializable;--import io.onedev.server.git.Contribution;-import io.onedev.server.util.Day;--class DayContribution implements Serializable, Comparable<DayContribution> {-- private static final long serialVersionUID = 1L;-- private final Day day;-- private final Contribution contribution;-- public DayContribution(Day day, Contribution contribution) {- this.day = day;- this.contribution = contribution;- }-- public Day getDay() {- return day;- }-- public Contribution getContribution() {- return contribution;- }-- @Override- public int compareTo(DayContribution o) {- return day.compareTo(o.day);- }--}\ No newline at end of filediff --git a/core/src/main/java/io/onedev/server/web/page/project/stats/ProjectContribsPage.html b/core/src/main/java/io/onedev/server/web/page/project/stats/ProjectContribsPage.htmlindex 0d958a3f5c..102775784f 100644--- a/core/src/main/java/io/onedev/server/web/page/project/stats/ProjectContribsPage.html+++ b/core/src/main/java/io/onedev/server/web/page/project/stats/ProjectContribsPage.html@@ -1,55 +1,15 @@<wicket:extend>- <select id="orderBy" wicket:id="orderBy" ></select>-- <div wicket:id="timeZoomContainer" class="timeZoom">- <div wicket:id="timeZoom">+ <div id="project-contribs">+ <div class="options clearfix">+ <span class="date-range pull-left clearfix"></span>+ <select class="contrib-type pull-right form-control">+ <option>Commits</option>+ <option>Additions</option>+ <option>Deletions</option>+ </select></div>+ <div class="note">Contributions to master, excluding merge commits</div>+ <div class="overall chart"></div>+ <div class="top-contributors container-fluid"></div></div>- <hr class="hr"/>- <div wicket:id="overallContributorsContainer" class="overallLineContainer">- <div wicket:id="overallContribution" id="overallLine" class="well"></div>-- </div>--- <hr/>-- <div class="top-contributors">- <hr/>- <div wicket:id="topContributorsContainer" class="userLine">- <div wicket:id="topContributors" class="well userInfo">- <div wicket:id="user" ></div>- <div wicket:id="userline" class="project-userlines"></div>- </div>- </div>- </div>--- <wicket:fragment wicket:id="timeZoomFrag">- <label wicket:id="time"></label>- </wicket:fragment>-- <wicket:fragment wicket:id="overallContributionFrag">- <div id="project-contribs" ></div>- </wicket:fragment>--- <wicket:fragment wicket:id="userFrag" >- <a wicket:id="avatar"></a>- <a wicket:id="link"></a>- <label wicket:id="No" style="float:right"></label>- <div>- <label id="commits" wicket:id="commits" ></label>- <label> </label>- <label id="additions" wicket:id="additions" ></label>- <label id="deletions" wicket:id="deletions" ></label>- </div>-- </wicket:fragment>-- <wicket:fragment wicket:id="userlineFrag" >- <div class="project-userline" ></div>- </wicket:fragment>--</wicket:extend>\ No newline at end of filediff --git a/core/src/main/java/io/onedev/server/web/page/project/stats/ProjectContribsPage.java b/core/src/main/java/io/onedev/server/web/page/project/stats/ProjectContribsPage.javaindex de315dcb58..f53e0b4536 100644--- a/core/src/main/java/io/onedev/server/web/page/project/stats/ProjectContribsPage.java+++ b/core/src/main/java/io/onedev/server/web/page/project/stats/ProjectContribsPage.java@@ -1,29 +1,10 @@package io.onedev.server.web.page.project.stats;-import java.util.ArrayList;-import java.util.Collections;-import java.util.List;+import java.util.HashMap;import java.util.Map;-import org.apache.commons.lang.StringUtils;-import org.apache.wicket.Component;-import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;-import org.apache.wicket.ajax.AjaxRequestTarget;-import org.apache.wicket.ajax.form.OnChangeAjaxBehavior;import org.apache.wicket.markup.head.IHeaderResponse;-import org.apache.wicket.markup.head.JavaScriptHeaderItem;import org.apache.wicket.markup.head.OnDomReadyHeaderItem;-import org.apache.wicket.markup.html.WebMarkupContainer;-import org.apache.wicket.markup.html.basic.Label;-import org.apache.wicket.markup.html.form.DropDownChoice;-import org.apache.wicket.markup.html.list.ListItem;-import org.apache.wicket.markup.html.list.ListView;-import org.apache.wicket.markup.html.panel.Fragment;-import org.apache.wicket.model.AbstractReadOnlyModel;-import org.apache.wicket.model.IModel;-import org.apache.wicket.model.LoadableDetachableModel;-import org.apache.wicket.model.PropertyModel;-import org.apache.wicket.request.cycle.RequestCycle;import org.apache.wicket.request.mapper.parameter.PageParameters;import com.fasterxml.jackson.core.JsonProcessingException;@@ -31,301 +12,17 @@ import com.fasterxml.jackson.databind.ObjectMapper;import io.onedev.server.OneDev;import io.onedev.server.git.Contribution;-import io.onedev.server.git.Contributor;import io.onedev.server.manager.CommitInfoManager;import io.onedev.server.security.SecurityUtils;-import io.onedev.server.util.Constants;import io.onedev.server.util.Day;-import io.onedev.server.web.behavior.AbstractPostAjaxBehavior;-import io.onedev.server.web.component.avatar.AvatarLink;-import io.onedev.server.web.component.link.UserLink;@SuppressWarnings("serial")public class ProjectContribsPage extends ProjectStatsPage {- private final int NUM_CONTRIBUTORS = 25;-- private final IModel<List<DayContribution>> overallContributionsModel =- new LoadableDetachableModel<List<DayContribution>>() {-- @Override- protected List<DayContribution> load() {- Map<Day, Contribution> map = OneDev.getInstance(CommitInfoManager.class).getOverallContributions(getProject());- return sort(map);- }-- };-- private String fromDayText;-- private String toDayText;--// private int gap;-- private int commits;-- private int additions;-- private int deletions;-- private String orderBy = Contribution.Type.COMMITS.name();-- private String [] Month = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};-public ProjectContribsPage(PageParameters params) {super(params);}- @Override- protected void onDetach() {- overallContributionsModel.detach();- super.onDetach();- }-- private List<DayContribution> sort(Map<Day, Contribution> map) {- List<DayContribution> list = new ArrayList<>();- for (Map.Entry<Day, Contribution> entry: map.entrySet())- list.add(new DayContribution(entry.getKey(), entry.getValue()));- Collections.sort(list);- return list;- }-- private String getJson(List<?> list) {- try {- return OneDev.getInstance(ObjectMapper.class).writeValueAsString(list);- } catch (JsonProcessingException e) {- throw new RuntimeException(e);- }- }--- private int CalculateCommits(List<DayContribution> list) {- int commitsCount=0;- for(DayContribution attribute : list) {- commitsCount+=attribute.getContribution().getCommits();- }- return commitsCount;- }- private int CalculateAdditions(List<DayContribution> list) {- int additionsCount=0;- for(DayContribution attribute : list) {- additionsCount+=attribute.getContribution().getAdditions();- }- return additionsCount;- }- private int CalculateDeletions(List<DayContribution> list) {- int deletionsCount=0;- for(DayContribution attribute : list) {- deletionsCount+=attribute.getContribution().getDeletions();- }- return deletionsCount;- }-- @Override- protected void onInitialize() {- super.onInitialize();- Map<Day, Contribution> map = OneDev.getInstance(CommitInfoManager.class).getOverallContributions(getProject());- List<DayContribution> OverallContributions=sort(map);- WebMarkupContainer timeZoomContainer=new WebMarkupContainer("timeZoomContainer");- WebMarkupContainer overallContributorsContainer =new WebMarkupContainer("overallContributorsContainer");- WebMarkupContainer topContributorsContainer =new WebMarkupContainer("topContributorsContainer");-- Fragment timeZoomfrag=new Fragment("timeZoom", "timeZoomFrag", ProjectContribsPage.this);- timeZoomfrag.add(new Label("time",new AbstractReadOnlyModel<String>() {-- @Override- public String getObject() {- // TODO Auto-generated method stub- Day fromDay;- if (StringUtils.isNotBlank(fromDayText)) {- fromDay = new Day(Constants.DATE_FORMATTER.parseDateTime(fromDayText));- } else {- fromDay = OverallContributions.get(0).getDay();- }-- Day toDay;- if (StringUtils.isNotBlank(toDayText)) {- toDay = new Day(Constants.DATE_FORMATTER.parseDateTime(toDayText));- } else {- toDay = OverallContributions.get(OverallContributions.size()-1).getDay();- }-- return (Month[fromDay.getDateTime().getMonthOfYear()-1]+" "+fromDay.getDateTime().getDayOfMonth()+","+fromDay.getDateTime().getYear()+" - "+Month[toDay.getDateTime().getMonthOfYear()-1]+" "+toDay.getDateTime().getDayOfMonth()+","+toDay.getDateTime().getYear());- }- }));--- timeZoomContainer.add(timeZoomfrag);- timeZoomContainer.setOutputMarkupId(true);- add(timeZoomContainer);- List<String> orderByChoices = new ArrayList<>();- for (Contribution.Type type: Contribution.Type.values())- orderByChoices.add(type.name());- DropDownChoice<String> choice=new DropDownChoice<String>("orderBy", new PropertyModel<String>(this, "orderBy"), orderByChoices) {-- };- choice.add(new OnChangeAjaxBehavior() {-- @Override- protected void onUpdate(AjaxRequestTarget target) {- //System.out.println("#########"+fromDayText+toDayText);- target.add(overallContributorsContainer);- target.add(topContributorsContainer);- }- });- add(choice);--- Fragment overallContributionfrag=new Fragment("overallContribution","overallContributionFrag",ProjectContribsPage.this);-- AbstractDefaultAjaxBehavior ondatazoom = new AbstractDefaultAjaxBehavior(){- @Override- protected void respond(AjaxRequestTarget _target)- {- String fromday = RequestCycle.get().getRequest().getRequestParameters().getParameterValue("fromday").toString();- String today = RequestCycle.get().getRequest().getRequestParameters().getParameterValue("today").toString();- fromDayText=fromday.replaceAll("/", "-");- toDayText=today.replaceAll("/", "-");- //System.out.println("<<<<<<<<"+fromDayText+toDayText);- _target.add(topContributorsContainer);- _target.add(timeZoomContainer);- }--- };- AbstractDefaultAjaxBehavior onrestore=new AbstractDefaultAjaxBehavior() {-- @Override- protected void respond(AjaxRequestTarget target) {- String fromday = RequestCycle.get().getRequest().getRequestParameters().getParameterValue("fromday").toString();- String today = RequestCycle.get().getRequest().getRequestParameters().getParameterValue("today").toString();- fromDayText=fromday.replaceAll("/", "-");- toDayText=today.replaceAll("/", "-");- //System.out.println("<<<<<<<<"+fromDayText+toDayText);- target.add(overallContributorsContainer);- }- };- overallContributionfrag.add(ondatazoom);- overallContributionfrag.add(onrestore);- overallContributionfrag.add(new AbstractPostAjaxBehavior() {- @Override- protected void respond(AjaxRequestTarget target) {- }- @Override- public void renderHead(Component component, IHeaderResponse response) {- super.renderHead(component, response);- String jsonContributionList = getJson(OverallContributions);-- Day fromDay;- if (StringUtils.isNotBlank(fromDayText)) {- fromDay = new Day(Constants.DATE_FORMATTER.parseDateTime(fromDayText));- } else {- fromDay = OverallContributions.get(0).getDay();- }-- Day toDay;- if (StringUtils.isNotBlank(toDayText)) {- toDay = new Day(Constants.DATE_FORMATTER.parseDateTime(toDayText));- } else {- toDay = OverallContributions.get(OverallContributions.size()-1).getDay();- }- int gapday=(int)((toDay.getDate().getTime()-fromDay.getDate().getTime())/ (1000*3600*24));- //System.out.println(">>>>>>startday"+fromDayText+" " + "today"+toDayText);- String script = String.format("onedev.server.stats.contribs.onDomReady(%s,'%s','%s','%s','%d');",jsonContributionList,- orderBy,fromDayText,toDayText,gapday- )- ;- response.render(OnDomReadyHeaderItem.forScript(script));- response.render(JavaScriptHeaderItem.forScript("function myFunction(fromday,today) {Wicket.Ajax.get({'u':'"+ ondatazoom.getCallbackUrl() +"&fromday=' + fromday+ '&today=' +today})}", "myFunction"));- response.render(JavaScriptHeaderItem.forScript("function redraw(fromday,today) {Wicket.Ajax.get({'u':'"+ onrestore.getCallbackUrl() +"&fromday=' + fromday+ '&today=' +today})}", "redraw"));-- }-- });-- overallContributorsContainer.add(overallContributionfrag);- overallContributorsContainer.setOutputMarkupId(true);- add(overallContributorsContainer);-- topContributorsContainer.setOutputMarkupId(true);- add(topContributorsContainer);- topContributorsContainer.add(new ListView<Contributor>("topContributors", new LoadableDetachableModel<List<Contributor>>() {-- @Override- protected List<Contributor> load() {- List<DayContribution> overallContributions = overallContributionsModel.getObject();- int size = overallContributions.size();- if (size != 0) {- Day fromDay;- if (StringUtils.isNotBlank(fromDayText)) {- fromDay = new Day(Constants.DATE_FORMATTER.parseDateTime(fromDayText));- } else {- fromDay = overallContributions.get(0).getDay();- }-- Day toDay;- if (StringUtils.isNotBlank(toDayText)) {- toDay = new Day(Constants.DATE_FORMATTER.parseDateTime(toDayText));- } else {- toDay = overallContributions.get(size-1).getDay();- }-- return OneDev.getInstance(CommitInfoManager.class)- .getTopContributors(getProject(), NUM_CONTRIBUTORS, Contribution.Type.valueOf(orderBy), fromDay, toDay);- } else {- return new ArrayList<>();- }- }-- }) {-- @Override- protected void populateItem(ListItem<Contributor> item) {- Contributor userContribution = item.getModelObject();- Fragment fragment = new Fragment("user", "userFrag", ProjectContribsPage.this);- fragment.add(new AvatarLink("avatar", userContribution.getUser()));- fragment.add(new UserLink("link", userContribution.getUser()));- int i=item.getIndex();- Map<Day,Contribution> dailyContributions=userContribution.getDailyContributions();- List<DayContribution> userDailyContribution=sort(dailyContributions);-- commits=CalculateCommits(userDailyContribution);- additions=CalculateAdditions(userDailyContribution);- deletions=CalculateDeletions(userDailyContribution);- fragment.add(new Label("commits",String.valueOf(commits)+"commits "));- fragment.add(new Label("additions",String.valueOf(additions)+"++"));- fragment.add(new Label("deletions",String.valueOf(deletions)+"--"));- fragment.add(new Label("No","#"+(i+1)));- item.add(fragment);- Fragment linefragment=new Fragment("userline", "userlineFrag", ProjectContribsPage.this);-- linefragment.add(new AbstractDefaultAjaxBehavior() {-- @Override- protected void respond(AjaxRequestTarget target) {- // TODO Auto-generated method stub-- }-- @Override- public void renderHead(Component component, IHeaderResponse response) {- super.renderHead(component, response);- String jsonUserDailyContribution=getJson(userDailyContribution);- Day startDay,endDay;- startDay=userDailyContribution.get(0).getDay();- endDay=userDailyContribution.get(userDailyContribution.size()-1).getDay();- int gapday=(int)((endDay.getDate().getTime()-startDay.getDate().getTime())/ (1000*3600*24));- String script = String.format(- "onedev.server.stats.contribs.ondrawLinesReady('%d',%s,'%s','%d');",i,jsonUserDailyContribution,orderBy,gapday);- response.render(OnDomReadyHeaderItem.forScript(script));- }- });- item.add(linefragment);- linefragment.setOutputMarkupId(true);- }- });- }-@Overrideprotected boolean isPermitted() {return SecurityUtils.canReadCode(getProject().getFacade());@@ -334,6 +31,26 @@ public class ProjectContribsPage extends ProjectStatsPage {@Overridepublic void renderHead(IHeaderResponse response) {super.renderHead(response);- response.render(JavaScriptHeaderItem.forReference(new ProjectStatsResourceReference()));++ CommitInfoManager commitInfoManager = OneDev.getInstance(CommitInfoManager.class);+ Map<Long, Integer[]> data = new HashMap<>();+ Map<Day, Contribution> overallContributions = commitInfoManager.getOverallContributions(getProject());+ for (Map.Entry<Day, Contribution> entry: overallContributions.entrySet()) {+ Contribution contribution = entry.getValue();+ Integer[] dataValue = new Integer[] {contribution.getCommits(), contribution.getAdditions(), contribution.getDeletions()};+ data.put(entry.getKey().getDate().getTime(), dataValue);+ }++ PageParameters params = TopContributorsResource.paramsOf(getProject());+ String topContributorsUrl = urlFor(new TopContributorsResourceReference(), params).toString();+ String jsonOfData;+ try {+ jsonOfData = OneDev.getInstance(ObjectMapper.class).writeValueAsString(data);+ } catch (JsonProcessingException e) {+ throw new RuntimeException(e);+ }+ String script = String.format("onedev.server.stats.contribs.onDomReady(%s, '%s');", jsonOfData, topContributorsUrl);+ response.render(OnDomReadyHeaderItem.forScript(script));}+}diff --git a/core/src/main/java/io/onedev/server/web/page/project/stats/ProjectStatsResourceReference.java b/core/src/main/java/io/onedev/server/web/page/project/stats/ProjectStatsResourceReference.javaindex 60cf18e8bb..435c600694 100644--- a/core/src/main/java/io/onedev/server/web/page/project/stats/ProjectStatsResourceReference.java+++ b/core/src/main/java/io/onedev/server/web/page/project/stats/ProjectStatsResourceReference.java@@ -7,6 +7,7 @@ import org.apache.wicket.markup.head.HeaderItem;import org.apache.wicket.markup.head.JavaScriptHeaderItem;import org.apache.wicket.request.resource.CssResourceReference;+import io.onedev.server.web.asset.doneevents.DoneEventsResourceReference;import io.onedev.server.web.asset.echarts.EChartsResourceReference;import io.onedev.server.web.page.base.BaseDependentResourceReference;@@ -22,6 +23,7 @@ public class ProjectStatsResourceReference extends BaseDependentResourceReferencpublic List<HeaderItem> getDependencies() {List<HeaderItem> dependencies = super.getDependencies();dependencies.add(JavaScriptHeaderItem.forReference(new EChartsResourceReference()));+ dependencies.add(JavaScriptHeaderItem.forReference(new DoneEventsResourceReference()));dependencies.add(CssHeaderItem.forReference(new CssResourceReference(ProjectStatsResourceReference.class, "project-stats.css")));return dependencies;diff --git a/core/src/main/java/io/onedev/server/web/page/project/stats/TopContributorsResource.java b/core/src/main/java/io/onedev/server/web/page/project/stats/TopContributorsResource.javanew file mode 100644index 0000000000..dd02808bf2--- /dev/null+++ b/core/src/main/java/io/onedev/server/web/page/project/stats/TopContributorsResource.java@@ -0,0 +1,107 @@+package io.onedev.server.web.page.project.stats;++import java.io.IOException;+import java.util.ArrayList;+import java.util.Date;+import java.util.HashMap;+import java.util.List;+import java.util.Map;++import org.apache.shiro.authz.UnauthorizedException;+import org.apache.wicket.request.cycle.RequestCycle;+import org.apache.wicket.request.mapper.parameter.PageParameters;+import org.apache.wicket.request.resource.AbstractResource;+import org.eclipse.jgit.lib.PersonIdent;++import com.fasterxml.jackson.databind.ObjectMapper;++import io.onedev.server.OneDev;+import io.onedev.server.git.Contribution;+import io.onedev.server.git.Contributor;+import io.onedev.server.manager.CommitInfoManager;+import io.onedev.server.manager.UserManager;+import io.onedev.server.model.Project;+import io.onedev.server.model.User;+import io.onedev.server.persistence.dao.Dao;+import io.onedev.server.security.SecurityUtils;+import io.onedev.server.util.Day;+import io.onedev.server.web.page.user.UserProfilePage;+import io.onedev.server.web.util.avatar.AvatarManager;++class TopContributorsResource extends AbstractResource {++ private static final long serialVersionUID = 1L;++ private static final String PARAM_PROJECT = "project";++ private static final String PARAM_FROM = "from";++ private static final String PARAM_TO = "to";++ private static final String PARAM_TYPE = "type";++ private static final int TOP_CONTRIBUTORS = 100;++ @Override+ protected ResourceResponse newResourceResponse(Attributes attributes) {+ PageParameters params = attributes.getParameters();+ Long projectId = params.get(PARAM_PROJECT).toLong();+ Day fromDay = new Day(new Date(params.get(PARAM_FROM).toLong()));+ Day toDay = new Day(new Date(params.get(PARAM_TO).toLong()));+ Contribution.Type type = Contribution.Type.valueOf(params.get(PARAM_TYPE).toString());++ ResourceResponse response = new ResourceResponse();+ response.setContentType("application/json");+ response.setWriteCallback(new WriteCallback() {++ @Override+ public void writeData(Attributes attributes) throws IOException {+ Project project = OneDev.getInstance(Dao.class).load(Project.class, projectId);++ if (!SecurityUtils.canReadCode(project.getFacade()))+ throw new UnauthorizedException();++ List<Contributor> topContributors = OneDev.getInstance(CommitInfoManager.class).getTopContributors(project, TOP_CONTRIBUTORS, type, fromDay, toDay);++ UserManager userManager = OneDev.getInstance(UserManager.class);+ AvatarManager avatarManager = OneDev.getInstance(AvatarManager.class);++ List<Map<String, Object>> data = new ArrayList<>();+ for (Contributor contributor: topContributors) {+ Map<String, Object> contributorData = new HashMap<>();+ PersonIdent author = contributor.getAuthor();+ User user = userManager.find(author);+ if (user != null) {+ contributorData.put("authorName", user.getDisplayName());+ contributorData.put("authorAvatarUrl", avatarManager.getAvatarUrl(user.getFacade()));+ contributorData.put("authorUrl", RequestCycle.get().urlFor(UserProfilePage.class, UserProfilePage.paramsOf(user)));+ } else {+ contributorData.put("authorName", author.getName());+ contributorData.put("authorAvatarUrl", avatarManager.getAvatarUrl(author));+ }+ contributorData.put("totalCommits", contributor.getTotalContribution().getCommits());+ contributorData.put("totalAdditions", contributor.getTotalContribution().getAdditions());+ contributorData.put("totalDeletions", contributor.getTotalContribution().getDeletions());++ Map<Long, Integer> dailyContributionsData = new HashMap<>();+ for (Map.Entry<Day, Integer> entry: contributor.getDailyContributions().entrySet()) {+ dailyContributionsData.put(entry.getKey().getDate().getTime(), entry.getValue());+ }+ contributorData.put("dailyContributions", dailyContributionsData);+ data.add(contributorData);+ }+ attributes.getResponse().write(OneDev.getInstance(ObjectMapper.class).writeValueAsBytes(data));+ }++ });++ return response;+ }++ public static PageParameters paramsOf(Project project) {+ PageParameters params = new PageParameters();+ params.set(PARAM_PROJECT, project.getId());+ return params;+ }++}diff --git a/core/src/main/java/io/onedev/server/web/page/project/stats/TopContributorsResourceReference.java b/core/src/main/java/io/onedev/server/web/page/project/stats/TopContributorsResourceReference.javanew file mode 100644index 0000000000..bd11adbe9a--- /dev/null+++ b/core/src/main/java/io/onedev/server/web/page/project/stats/TopContributorsResourceReference.java@@ -0,0 +1,21 @@+package io.onedev.server.web.page.project.stats;++import org.apache.wicket.request.resource.IResource;+import org.apache.wicket.request.resource.ResourceReference;++class TopContributorsResourceReference extends ResourceReference {++ public static final String NAME = "topContributors";++ public TopContributorsResourceReference() {+ super(NAME);+ }++ private static final long serialVersionUID = 1L;++ @Override+ public IResource getResource() {+ return new TopContributorsResource();+ }++}diff --git a/core/src/main/java/io/onedev/server/web/page/project/stats/project-stats.css b/core/src/main/java/io/onedev/server/web/page/project/stats/project-stats.cssindex 7550eb79c2..dc2e7c8b9a 100644--- a/core/src/main/java/io/onedev/server/web/page/project/stats/project-stats.css+++ b/core/src/main/java/io/onedev/server/web/page/project/stats/project-stats.css@@ -1,62 +1,71 @@-#project-stats {- padding: 20px;+#project-contribs .options {+ margin-bottom: 20px;+ padding-bottom: 8px;+ border-bottom: 1px solid #EEE;}--#project-contribs .form-inline div {- margin-right: 10px;+#project-contribs .note {+ margin-bottom: 20px;+ color: #666;+ font-size: 16px;}--#project-contribs .form-inline div .btn {- margin-left: 20px;+#project-contribs .options>.date-range {+ font-size: 20px;}--#orderBy{- float:left;+#project-contribs .options select {+ width: 120px;}-.timeZoom{- float:right;+#project-contribs .overall {+ height: 360px;+ background: #F9F9F9;+ margin-bottom: 20px;+ border: 1px solid #EEE;}-.hr{- clear:both;+#project-contribs .overall .no-data {+ text-align: center;+ font-size: 36px;+ font-style: italic;}-.top-contributors{- width:100%;+#project-contribs .top-contributors .loading {+ text-align: center;}-.overallLineContainer{- clear:both;+#project-contribs .top-contributors .head .pull-left {+ padding-left: 48px;+ position: relative;}-#overallLine{- width:100%;- height:320px;+#project-contribs .top-contributors .head .pull-left .avatar {+ position: absolute;+ left: 0;+ top: 0;+ width: 40px;+ height: 40px;}-#project-contribs{- width: 100%;- margin:0 auto;- height:310px;+#project-contribs .top-contributors .row>div {+ padding: 0;+}+#project-contribs .top-contributors .row>div>.content {+ border: 1px solid #DDD;+}+#project-contribs .top-contributors .head {+ padding: 12px;}-#additions{- color:green;-}-#deletions{- color:red;-}-.project-userlines{- width: 100%;- height:250px-}-.project-userline{- width: 100%;- height:250px-}-.userLine{- display:flex;- justify-content:space-between;- flex-wrap: wrap;- width:100%;-}-.userInfo{- width:49%;- height:300px;--}\ No newline at end of file+#project-contribs .top-contributors .head .name {+ margin-left: 0 !important;+}+#project-contribs .top-contributors .head .total-contribution span {+ margin-right: 12px;+ font-size: 12px;+}+#project-contribs .top-contributors .head .total-contribution span.additions {+ color: green;+}+#project-contribs .top-contributors .head .total-contribution span.deletions {+ color: red;+}+#project-contribs .top-contributors .head .pull-right {+ font-size: 20px;+}+#project-contribs .top-contributors .body {+ background: #F9F9F9;+ height: 300px;+}diff --git a/core/src/main/java/io/onedev/server/web/page/project/stats/project-stats.js b/core/src/main/java/io/onedev/server/web/page/project/stats/project-stats.jsindex dfc86a49f5..411d28febc 100644--- a/core/src/main/java/io/onedev/server/web/page/project/stats/project-stats.js+++ b/core/src/main/java/io/onedev/server/web/page/project/stats/project-stats.js@@ -1,1712 +1,302 @@onedev.server.stats = {- contribs : {- onDomReady : function(jsonList, orderBy, fromDay, toDay, gapday) {-- //console.log(">>>>>>>>>>gapday:",gapday,"fromDay:",fromDay,"toDay",toDay);- var flag = false;- function getDailyData(list) {- //var dailyData=[];- var date = [];- var data = [];- var base = +new Date(list[0].day.dateTime);- var oneDay = 24 * 3600 * 1000;- var firstday = new Date(list[0].day.dateTime);-- date.push([ firstday.getFullYear(), firstday.getMonth() + 1, firstday.getDate() ].join('/'));-- if (orderBy == "COMMITS") {- data.push(list[0].contribution.commits);- for (var i = 1; i < list.length; i++) {- var day = new Date(list[i].day.dateTime);- var now = new Date(base += oneDay);- while (day.getTime() != now.getTime()) {- date.push([ now.getFullYear(), now.getMonth() + 1, now.getDate() ].join('/'));- data.push(0);- now = new Date(base += oneDay);-- }- date.push([ now.getFullYear(), now.getMonth() + 1, now.getDate() ].join('/'));- data.push(list[i].contribution.commits);- }- } else if (orderBy == "ADDITIONS") {- data.push(list[0].contribution.additions / 1000);- for (var i = 1; i < list.length; i++) {- var day = new Date(list[i].day.dateTime);- var now = new Date(base += oneDay);- while (day.getTime() != now.getTime()) {- date.push([ now.getFullYear(), now.getMonth() + 1, now.getDate() ].join('/'));- data.push(0);- now = new Date(base += oneDay);-- }- date.push([ now.getFullYear(), now.getMonth() + 1, now.getDate() ].join('/'));- data.push(list[i].contribution.additions / 1000);- }-- } else {- data.push(list[0].contribution.deletions / 1000);- for (var i = 1; i < list.length; i++) {- var day = new Date(list[i].day.dateTime);- var now = new Date(base += oneDay);- while (day.getTime() != now.getTime()) {- date.push([ now.getFullYear(), now.getMonth() + 1, now.getDate() ].join('/'));- data.push(0);- now = new Date(base += oneDay);-- }- date.push([ now.getFullYear(), now.getMonth() + 1, now.getDate() ].join('/'));- data.push(list[i].contribution.deletions / 1000);- }- }- data = data.concat(date);- return data;+ contribs: {+ onDomReady : function(overallContributions, topContributorsDataUrl) {+ var $contribs = $("#project-contribs");+ var $overall = $contribs.find(".overall");+ if (overallContributions.length == 0) {+ $overall.html("<div class='no-data'>No data</div>");+ return;}-- /*get Whole Monthly Data from jsonList*/- function getMonthData(list) {- var monthdate = [];- var monthdata = [];- var MONTH = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");- var lastDay = new Date(list[0].day.dateTime);- if (orderBy == "COMMITS") {- var monthCommits = list[0].contribution.commits;- if (list.length == 1) {- monthdate.push([ lastDay.getFullYear(), MONTH[lastDay.getMonth()] ].join('/'));- monthdata.push(monthCommits);- }- for (var i = 1; i < list.length; i++) {- var monthNo = lastDay.getMonth();- var currentDay = new Date(list[i].day.dateTime);- var current_monthNo = currentDay.getMonth();- if (lastDay.getFullYear() == currentDay.getFullYear() && monthNo == current_monthNo) {- monthCommits += list[i].contribution.commits;- if (i == list.length - 1) {- monthdate.push([ lastDay.getFullYear(), MONTH[lastDay.getMonth()] ].join('/'));- monthdata.push(monthCommits);- break;- }- } else {- monthdate.push([ lastDay.getFullYear(), MONTH[lastDay.getMonth()] ].join('/'));- monthdata.push(monthCommits);-- var monthgap = (currentDay.getFullYear() * 12 + currentDay.getMonth()) - (lastDay.getFullYear() * 12 + lastDay.getMonth());- if (monthgap >= 2) {- var curr = lastDay;- curr.setMonth(curr.getMonth() + 1);- while (curr <= currentDay) {- if (curr.getFullYear() == currentDay.getFullYear() && curr.getMonth() == currentDay.getMonth()) break;- var month = curr.getMonth();- monthdate.push([ curr.getFullYear(), MONTH[month] ].join('/'));- monthdata.push(0);- curr.setMonth(month + 1);- }- }-- monthCommits = list[i].contribution.commits;- lastDay = new Date(list[i].day.dateTime);- if (i == list.length - 1) {- monthdate.push([ currentDay.getFullYear(), MONTH[currentDay.getMonth()] ].join('/'));- monthdata.push(monthCommits);- break;- }- }-- }- } else if (orderBy == "ADDITIONS") {- var monthAdditions = list[0].contribution.additions;- if (list.length == 1) {- monthdate.push([ lastDay.getFullYear(), MONTH[lastDay.getMonth()] ].join('/'));- monthdata.push(monthAdditions / 1000);- }- for (var i = 1; i < list.length; i++) {- var monthNo = lastDay.getMonth();- var currentDay = new Date(list[i].day.dateTime);- var current_monthNo = currentDay.getMonth();- if (lastDay.getFullYear() == currentDay.getFullYear() && monthNo == current_monthNo) {- monthAdditions += list[i].contribution.additions;- if (i == list.length - 1) {- monthdate.push([ lastDay.getFullYear(), MONTH[lastDay.getMonth()] ].join('/'));- monthdata.push(monthAdditions / 1000);- break;- }- } else {- monthdate.push([ lastDay.getFullYear(), MONTH[lastDay.getMonth()] ].join('/'));- monthdata.push(monthAdditions / 1000);- var monthgap = (currentDay.getFullYear() * 12 + currentDay.getMonth()) - (lastDay.getFullYear() * 12 + lastDay.getMonth());- if (monthgap >= 2) {- var curr = lastDay;- curr.setMonth(curr.getMonth() + 1);- while (curr <= currentDay) {- if (curr.getFullYear() == currentDay.getFullYear() && curr.getMonth() == currentDay.getMonth()) break;- var month = curr.getMonth();- monthdate.push([ curr.getFullYear(), MONTH[month] ].join('/'));- monthdata.push(0);- curr.setMonth(month + 1);- }- }-- monthAdditions = list[i].contribution.additions;- lastDay = new Date(list[i].day.dateTime);- if (i == list.length - 1) {- monthdate.push([ currentDay.getFullYear(), MONTH[currentDay.getMonth()] ].join('/'));- monthdata.push(monthAdditions / 1000);- break;- }- }-- }- } else {- var monthDeletions = list[0].contribution.deletions;- if (list.length == 1) {- monthdate.push([ lastDay.getFullYear(), MONTH[lastDay.getMonth()] ].join('/'));- monthdata.push(monthDeletions / 1000);- }- for (var i = 1; i < list.length; i++) {- var monthNo = lastDay.getMonth();- var currentDay = new Date(list[i].day.dateTime);- var current_monthNo = currentDay.getMonth();- if (lastDay.getFullYear() == currentDay.getFullYear() && monthNo == current_monthNo) {- monthDeletions += list[i].contribution.deletions;- if (i == list.length - 1) {- monthdate.push([ lastDay.getFullYear(), MONTH[lastDay.getMonth()] ].join('/'));- monthdata.push(monthDeletions / 1000);- break;- }- } else {- monthdate.push([ lastDay.getFullYear(), MONTH[lastDay.getMonth()] ].join('/'));- monthdata.push(monthDeletions / 1000);-- var monthgap = (currentDay.getFullYear() * 12 + currentDay.getMonth()) - (lastDay.getFullYear() * 12 + lastDay.getMonth());- if (monthgap >= 2) {- var curr = lastDay;- curr.setMonth(curr.getMonth() + 1);- while (curr <= currentDay) {- if (curr.getFullYear() == currentDay.getFullYear() && curr.getMonth() == currentDay.getMonth()) break;- var month = curr.getMonth();- monthdate.push([ curr.getFullYear(), MONTH[month] ].join('/'));- monthdata.push(0);- curr.setMonth(month + 1);- }- }-- monthDeletions = list[i].contribution.deletions;- lastDay = new Date(list[i].day.dateTime);- if (i == list.length - 1) {- monthdate.push([ currentDay.getFullYear(), MONTH[currentDay.getMonth()] ].join('/'));- monthdata.push(monthDeletions / 1000);- break;- }- }-- }- }- monthdata = monthdata.concat(monthdate);- return monthdata;++ var contribDays = [];+ for (var dayMillis in overallContributions) {+ contribDays.push(new Date(parseInt(dayMillis)));}- /*get Sliced DailyData from the Whole DailyData*/- function getSlicedDailyData(list, fromday, today) {- var slicedDate = [];- var slicedData = [];- for (var i = 0; i < list.length / 2; i++) {- slicedData.push(list[i]);- }- for (var j = list.length / 2; j < list.length; j++) {- slicedDate.push(list[j]);- }-- var firstday,- lastday;- if (fromday == 'null' && today == 'null') {- firstday = 0;- lastday = slicedDate.length - 1;- } else {- fromday = fromday.replace(/-/g, "/");- today = today.replace(/-/g, "/");- for (var j = 0; j < slicedDate.length; j++) {- if (slicedDate[j] == fromday)- firstday = j;- if (slicedDate[j] == today) {- lastday = j;- break;- }- }-- }- slicedDate = slicedDate.slice(firstday, lastday + 1);- slicedData = slicedData.slice(firstday, lastday + 1);- slicedData = slicedData.concat(slicedDate);- return slicedData;- }- /*get Sliced MonthData from the Whole MonthData*/- function getSlicedMonthData(list, fromday, today) {- //console.log("FUNCTION GETSLICED MONTHDATA",fromday,today)- var slicedDate = [];- var slicedData = [];- var MONTH = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");- for (var i = 0; i < list.length / 2; i++) {- slicedData.push(list[i]);- }- for (var j = list.length / 2; j < list.length; j++) {- slicedDate.push(list[j]);- }-- var firstday,- lastday;- if (fromday == 'null' && today == 'null') {- firstday = 0;- lastday = slicedDate.length - 1;- } else {- fromday = fromday.replace(/-/g, "/");- today = today.replace(/-/g, "/");- var year_fromday = fromday.split("/")[0];- var month_fromday = fromday.split("/")[1];- var year_today = today.split("/")[0];- var month_today = today.split("/")[1];- //console.log("##########year:",year_fromday," month",month_fromday);- for (var j = 0; j < slicedDate.length; j++) {- var year = slicedDate[j].split("/")[0];- var month = slicedDate[j].split("/")[1];- if (year == year_fromday && month == MONTH[month_fromday - 1]) {- firstday = j;- break;- }-- }- for (var j = firstday; j < slicedDate.length; j++) {- var year = slicedDate[j].split("/")[0];- var month = slicedDate[j].split("/")[1];- if (year == year_today && month == MONTH[month_today - 1]) {- lastday = j;- break;- }- }-- }- slicedDate = slicedDate.slice(firstday, lastday + 1);- slicedData = slicedData.slice(firstday, lastday + 1);- slicedData = slicedData.concat(slicedDate);- return slicedData;+ contribDays.sort(function(a, b) {+ return a - b;+ });++ var days = [];++ var lastDay = contribDays[contribDays.length-1];+ var currentDay = contribDays[0];+ while (currentDay <= lastDay) {+ days.push(currentDay);+ currentDay = new Date(currentDay.getTime());+ currentDay.setDate(currentDay.getDate()+1);}- // console.log("fromDay and toDay",fromDay,"###",toDay);-- var showdata = [];- var showdate = [];-- /*get showdata for monthContribution*/- if (gapday > 365) {- var wholeMonthData = getMonthData(jsonList);- var monthData = getSlicedMonthData(wholeMonthData, fromDay, toDay);- //console.log("month",monthData);- for (var i = 0; i < monthData.length / 2; i++) {- showdata.push(monthData[i]);- }- for (var j = monthData.length / 2; j < monthData.length; j++) {- showdate.push(monthData[j]);- }++ function formatDate(date) {+ return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();}-- /*get showdata for dailyContribution*/- else {- var wholeDailyData = getDailyData(jsonList);- var dailyData = getSlicedDailyData(wholeDailyData, fromDay, toDay);- for (var i = 0; i < dailyData.length / 2; i++) {- showdata.push(dailyData[i]);- }- for (var j = dailyData.length / 2; j < dailyData.length; j++) {- showdate.push(dailyData[j]);- }++ var fromDay = days[0];+ var toDay = days[days.length-1];++ function updateDateRange() {+ $contribs.find(".date-range").text(formatDate(fromDay) + " ~ " + formatDate(toDay));}- //console.log("showdata",showdata);- var myChart = echarts.init(document.getElementById('project-contribs'));-- var optionCommits = {- tooltip : {- trigger : 'axis',- // formatter: '{b} <br/>{a}:{c}s',- position : function(pt) {- return [ pt[0], '10%' ];- }- },- title : {- left : 'center',- text : 'OverallContribution',- },- grid : {- left : "2%",- right : "2%",- top : 50,- buttom : "1%"- },- toolbox : {- feature : {- dataZoom : {- yAxisIndex : 'none',- iconStyle : {- opacity : 0- }- },- /*restore: {- //icon:'path://M30.9,53.2C16.8,53.2,5.3,41.7,5.3,27.6S16.8,2,30.9,2C45,2,56.4,13.5,56.4,27.6S45,53.2,30.9,53.2z M30.9,3.5C17.6,3.5,6.8,14.4,6.8,27.6c0,13.3,10.8,24.1,24.101,24.1C44.2,51.7,55,40.9,55,27.6C54.9,14.4,44.1,3.5,30.9,3.5z M36.9,35.8c0,0.601-0.4,1-0.9,1h-1.3c-0.5,0-0.9-0.399-0.9-1V19.5c0-0.6,0.4-1,0.9-1H36c0.5,0,0.9,0.4,0.9,1V35.8z M27.8,35.8 c0,0.601-0.4,1-0.9,1h-1.3c-0.5,0-0.9-0.399-0.9-1V19.5c0-0.6,0.4-1,0.9-1H27c0.5,0,0.9,0.4,0.9,1L27.8,35.8L27.8,35.8z',- iconStyle:{- textPosition:'left',- opacity:1- }- },*/- //saveAsImage: {}- }- //show:false- },- xAxis : {- type : 'category',- boundaryGap : false,- data : showdate,- triggerEvent : true- },- yAxis : {- axisLine : {- show : false- },- minInterval : 1,- /*max: function(value) {- return value.max ;- },*/- type : 'value',- boundaryGap : [ 0, '100%' ],- triggerEvent : true- },-- series : [- {- name : 'commits',- type : 'line',- smooth : true,- symbol : 'none',- sampling : 'average',- itemStyle : {- normal : {- label : {- formatter : function(params) {- if (params.value > 0) {- return params.value;- } else {- return '';- }- }- },- color : 'rgba(0,0,0,0)'- }- },- areaStyle : {- normal : {- color : new echarts.graphic.LinearGradient(0, 0, 0, 1, [ {- offset : 0,- color : 'rgb(143,207,159)'- }, {- offset : 1,- color : 'rgb(143,207,159)'- } ])- }- },- data : showdata- }- ]- };-- var optionAdditions = {- tooltip : {- trigger : 'axis',- formatter : '{b} <br/>{a}:{c}k',- position : function(pt) {- return [ pt[0], '10%' ];- }- },- title : {- left : 'center',- text : 'OverallContribution',- },- grid : {- left : "4%",- right : "2%",- top : 60,- buttom : 60- },- toolbox : {- feature : {- dataZoom : {- yAxisIndex : 'none',- iconStyle : {- opacity : 0- }- },- /*restore: {- iconStyle:{- opacity:1- }- },*/- //saveAsImage: {}- }- },- xAxis : {- type : 'category',- boundaryGap : false,- data : showdate,- triggerEvent : true- },- yAxis : {- axisLabel : {- formatter : function(value) {- return value + 'k'- }- },- axisLine : {- show : false- },- type : 'value',- max : function(value) {- return value.max * 1;- },- boundaryGap : [ 0, '100%' ],- triggerEvent : true- },+ var $contribType = $contribs.find(".contrib-type");+ var $topContributors = $contribs.find(".top-contributors");- series : [- {- name : 'additions',- type : 'line',- smooth : true,- symbol : 'none',- sampling : 'average',- itemStyle : {- normal : {- label : {- formatter : function(params) {- if (params.value > 0) {- return params.value;- } else {- return '';- }- }- },- color : 'rgba(0,0,0,0)'- }- },- areaStyle : {- normal : {- color : new echarts.graphic.LinearGradient(0, 0, 0, 1, [ {- offset : 0,- color : 'rgb(143,207,159)'- }, {- offset : 1,- color : 'rgb(143,207,159)'- } ])- }- },- data : showdata- }- ]- };- var optionDeletions = {- tooltip : {- trigger : 'axis',- formatter : '{b} <br/>{a}:{c}k',- position : function(pt) {- return [ pt[0], '10%' ];- }- },- title : {- left : 'center',- text : 'OverallContribution',- },- grid : {- left : "4%",- right : "2%",- top : 60,- buttom : 60- },- toolbox : {- feature : {- dataZoom : {- yAxisIndex : 'none',- iconStyle : {- opacity : 0- }- },- /*restore: {- iconStyle:{- opacity:1- }- },*/- //saveAsImage: {}- }- },- xAxis : {- type : 'category',-- boundaryGap : false,- data : showdate,- triggerEvent : true- },- yAxis : {- axisLine : {- show : false- },- axisLabel : {- formatter : function(value) {- return value + 'k'- }- },- type : 'value',- max : function(value) {- return value.max * 1;- },- boundaryGap : [ 0, '100%' ],- triggerEvent : true- },-- series : [- {- name : 'deletions',- type : 'line',- smooth : true,- symbol : 'none',- sampling : 'average',- itemStyle : {- normal : {- label : {- formatter : function(params) {- if (params.value > 0) {- return params.value;- } else {- return '';- }- }- },- color : 'rgba(0,0,0,0)'- }- },- areaStyle : {- normal : {- color : new echarts.graphic.LinearGradient(0, 0, 0, 1, [ {- offset : 0,- color : 'rgb(143,207,159)'- }, {- offset : 1,- color : 'rgb(143,207,159)'- } ])- }- },- data : showdata- }- ]- };-- if (orderBy == "COMMITS") {- myChart.setOption(optionCommits, true);- } else if (orderBy == "ADDITIONS") {- myChart.setOption(optionAdditions, true);- } else {- myChart.setOption(optionDeletions, true);+ var overallChart = echarts.init($overall[0]);+ $overall.data("chart", overallChart);++ var overallXAxisData = [];+ for (var i=0; i<days.length; i++) {+ overallXAxisData.push(formatDate(days[i]));}- var firstday = new Date(jsonList[0].day.dateTime);- var firstDay = [ firstday.getFullYear(), firstday.getMonth() + 1, firstday.getDate() ].join('-');- var lastday = new Date(jsonList[jsonList.length - 1].day.dateTime);- var lastDay = [ lastday.getFullYear(), lastday.getMonth() + 1, lastday.getDate() ].join('-');-- // console.log("firstday and lastday",firstDay,"##",lastDay);- if ((fromDay == 'null' && toDay == 'null') || (fromDay == firstDay && toDay == lastDay)) {- myChart.setOption({- toolbox : {- feature : {- restore : {- title : 'Restore date range',- iconStyle : {- opacity : 0- }- }- },- right: '40px'- },- });- } else {- myChart.setOption({- toolbox : {- feature : {- restore : {- title: 'Restore date range',- iconStyle : {- opacity : 1- }- }- },- right: '40px'- },- });- }-- myChart.dispatchAction({- type : 'takeGlobalCursor',- key : 'dataZoomSelect',- dataZoomSelectActive : true // 允许缩放- });-- myChart.on('restore', function(params) {- var firstday = new Date(jsonList[0].day.dateTime);- var lastday = new Date(jsonList[jsonList.length - 1].day.dateTime)- myFunction([ firstday.getFullYear(), firstday.getMonth() + 1, firstday.getDate() ].join('/'), [ lastday.getFullYear(), lastday.getMonth() + 1, lastday.getDate() ].join('/'));- myChart.setOption({- toolbox : {- feature : {- restore : {- title: 'Restore date range',- iconStyle : {- opacity : 0- }- }- },- right: '40px'- },- });- redraw([ firstday.getFullYear(), firstday.getMonth() + 1, firstday.getDate() ].join('/'), [ lastday.getFullYear(), lastday.getMonth() + 1, lastday.getDate() ].join('/'));- });- $(window).resize(function() {myChart.resize()});-- myChart.on('datazoom', function(params) {- myChart.setOption({- toolbox : {- feature : {- restore : {- title: 'Restore date range',- iconStyle : {- opacity : 1- }- }- },- right: '40px'- },- });- var startIndex = myChart.getModel().option.dataZoom[0].startValue;- var endIndex = myChart.getModel().option.dataZoom[0].endValue;- var startdate = Date.parse(showdate[startIndex]);- var enddate = Date.parse(showdate[endIndex]);- var startday = new Date(startdate);- var endday = new Date(enddate);- var currGap = (enddate - startdate) / (24 * 3600 * 1000);- //console.log("<<<<<<currGap+from+tp:",currGap,[startday.getFullYear(),startday.getMonth() + 1, startday.getDate()].join('/'),[endday.getFullYear(),endday.getMonth() + 1, endday.getDate()].join('/'))- if (gapday > 365) {- if (currGap < 365) {- redraw([ startday.getFullYear(), startday.getMonth() + 1, startday.getDate() ].join('/'), [ endday.getFullYear(), endday.getMonth() + 1, endday.getDate() ].join('/'));- myFunction([ startday.getFullYear(), startday.getMonth() + 1, startday.getDate() ].join('/'), [ endday.getFullYear(), endday.getMonth() + 1, endday.getDate() ].join('/'));- } else {- myFunction([ startday.getFullYear(), startday.getMonth() + 1, startday.getDate() ].join('/'), [ endday.getFullYear(), endday.getMonth() + 1, endday.getDate() ].join('/'));- }- } else {- myFunction([ startday.getFullYear(), startday.getMonth() + 1, startday.getDate() ].join('/'), [ endday.getFullYear(), endday.getMonth() + 1, endday.getDate() ].join('/'));- }- });- },--- ondrawLinesReady : function(flag, jsonUserDailyContribution, orderBy, gap) {- //console.log("flag:"+flag+" "+gap);- function getMonthData(list) {- var monthdate = [];- var monthdata = [];- var MONTH = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");- var lastDay = new Date(list[0].day.dateTime);- if (orderBy == "COMMITS") {- var monthCommits = list[0].contribution.commits;- if (list.length == 1) {- monthdate.push([ lastDay.getFullYear(), MONTH[lastDay.getMonth()] ].join('/'));- monthdata.push(monthCommits);- }- for (var i = 1; i < list.length; i++) {- var monthNo = lastDay.getMonth();- var currentDay = new Date(list[i].day.dateTime);- var current_monthNo = currentDay.getMonth();- if (lastDay.getFullYear() == currentDay.getFullYear() && monthNo == current_monthNo) {- monthCommits += list[i].contribution.commits;- if (i == list.length - 1) {- monthdate.push([ lastDay.getFullYear(), MONTH[lastDay.getMonth()] ].join('/'));- monthdata.push(monthCommits);- break;- }- } else {- monthdate.push([ lastDay.getFullYear(), MONTH[lastDay.getMonth()] ].join('/'));- monthdata.push(monthCommits);-- var monthgap = (currentDay.getFullYear() * 12 + currentDay.getMonth()) - (lastDay.getFullYear() * 12 + lastDay.getMonth());- if (monthgap >= 2) {- var curr = lastDay;- curr.setMonth(curr.getMonth() + 1);- while (curr <= currentDay) {- if (curr.getFullYear() == currentDay.getFullYear() && curr.getMonth() == currentDay.getMonth()) break;- var month = curr.getMonth();- monthdate.push([ curr.getFullYear(), MONTH[month] ].join('/'));- monthdata.push(0);- curr.setMonth(month + 1);- }- }-- monthCommits = list[i].contribution.commits;- lastDay = new Date(list[i].day.dateTime);- if (i == list.length - 1) {- monthdate.push([ currentDay.getFullYear(), MONTH[currentDay.getMonth()] ].join('/'));- monthdata.push(monthCommits);- break;- }- }-- }- } else if (orderBy == "ADDITIONS") {- var monthAdditions = list[0].contribution.additions;- if (list.length == 1) {- monthdate.push([ lastDay.getFullYear(), MONTH[lastDay.getMonth()] ].join('/'));- monthdata.push(monthAdditions / 1000);- }- for (var i = 1; i < list.length; i++) {- var monthNo = lastDay.getMonth();- var currentDay = new Date(list[i].day.dateTime);- var current_monthNo = currentDay.getMonth();- if (lastDay.getFullYear() == currentDay.getFullYear() && monthNo == current_monthNo) {- monthAdditions += list[i].contribution.additions;- if (i == list.length - 1) {- monthdate.push([ lastDay.getFullYear(), MONTH[lastDay.getMonth()] ].join('/'));- monthdata.push(monthAdditions / 1000);- break;- }- } else {- monthdate.push([ lastDay.getFullYear(), MONTH[lastDay.getMonth()] ].join('/'));- monthdata.push(monthAdditions / 1000);- var monthgap = (currentDay.getFullYear() * 12 + currentDay.getMonth()) - (lastDay.getFullYear() * 12 + lastDay.getMonth());- if (monthgap >= 2) {- var curr = lastDay;- curr.setMonth(curr.getMonth() + 1);- while (curr <= currentDay) {- if (curr.getFullYear() == currentDay.getFullYear() && curr.getMonth() == currentDay.getMonth()) break;- var month = curr.getMonth();- monthdate.push([ curr.getFullYear(), MONTH[month] ].join('/'));- monthdata.push(0);- curr.setMonth(month + 1);- }- }-- monthAdditions = list[i].contribution.additions;- lastDay = new Date(list[i].day.dateTime);- if (i == list.length - 1) {- monthdate.push([ currentDay.getFullYear(), MONTH[currentDay.getMonth()] ].join('/'));- monthdata.push(monthAdditions / 1000);- break;- }- }-- }- } else {- var monthDeletions = list[0].contribution.deletions;- if (list.length == 1) {- monthdate.push([ lastDay.getFullYear(), MONTH[lastDay.getMonth()] ].join('/'));- monthdata.push(monthDeletions / 1000);- }- for (var i = 1; i < list.length; i++) {- var monthNo = lastDay.getMonth();- var currentDay = new Date(list[i].day.dateTime);- var current_monthNo = currentDay.getMonth();- if (lastDay.getFullYear() == currentDay.getFullYear() && monthNo == current_monthNo) {- monthDeletions += list[i].contribution.deletions;- if (i == list.length - 1) {- monthdate.push([ lastDay.getFullYear(), MONTH[lastDay.getMonth()] ].join('/'));- monthdata.push(monthDeletions / 1000);- break;- }- } else {- monthdate.push([ lastDay.getFullYear(), MONTH[lastDay.getMonth()] ].join('/'));- monthdata.push(monthDeletions / 1000);-- var monthgap = (currentDay.getFullYear() * 12 + currentDay.getMonth()) - (lastDay.getFullYear() * 12 + lastDay.getMonth());- if (monthgap >= 2) {- var curr = lastDay;- curr.setMonth(curr.getMonth() + 1);- while (curr <= currentDay) {- if (curr.getFullYear() == currentDay.getFullYear() && curr.getMonth() == currentDay.getMonth()) break;- var month = curr.getMonth();- monthdate.push([ curr.getFullYear(), MONTH[month] ].join('/'));- monthdata.push(0);- curr.setMonth(month + 1);- }- }-- monthDeletions = list[i].contribution.deletions;- lastDay = new Date(list[i].day.dateTime);- if (i == list.length - 1) {- monthdate.push([ currentDay.getFullYear(), MONTH[currentDay.getMonth()] ].join('/'));- monthdata.push(monthDeletions / 1000);- break;- }- }-- }- }-- monthdata = monthdata.concat(monthdate);- return monthdata;- }-- function getDailyData(list) {- var date = [];++ function getOverallSeriesData() {var data = [];- var base = +new Date(list[0].day.dateTime);- var oneDay = 24 * 3600 * 1000;- var firstday = new Date(list[0].day.dateTime);-- date.push([ firstday.getFullYear(), firstday.getMonth() + 1, firstday.getDate() ].join('/'));- if (orderBy == "COMMITS") {- data.push(list[0].contribution.commits);- for (var i = 1; i < list.length; i++) {- var day = new Date(list[i].day.dateTime);- var now = new Date(base += oneDay);- while (day.getTime() != now.getTime()) {- date.push([ now.getFullYear(), now.getMonth() + 1, now.getDate() ].join('/'));- data.push(0);- now = new Date(base += oneDay);-- }- date.push([ now.getFullYear(), now.getMonth() + 1, now.getDate() ].join('/'));- data.push(list[i].contribution.commits);-- }- } else if (orderBy == "ADDITIONS") {- data.push(list[0].contribution.additions / 1000);- for (var i = 1; i < list.length; i++) {- var day = new Date(list[i].day.dateTime);- var now = new Date(base += oneDay);- while (day.getTime() != now.getTime()) {- date.push([ now.getFullYear(), now.getMonth() + 1, now.getDate() ].join('/'));- data.push(0);- now = new Date(base += oneDay);- }- date.push([ now.getFullYear(), now.getMonth() + 1, now.getDate() ].join('/'));- data.push(list[i].contribution.additions / 1000);- }- } else {- data.push(list[0].contribution.deletions / 1000);- for (var i = 1; i < list.length; i++) {- var day = new Date(list[i].day.dateTime);- var now = new Date(base += oneDay);- while (day.getTime() != now.getTime()) {- date.push([ now.getFullYear(), now.getMonth() + 1, now.getDate() ].join('/'));- data.push(0);- now = new Date(base += oneDay);- }- date.push([ now.getFullYear(), now.getMonth() + 1, now.getDate() ].join('/'));- data.push(list[i].contribution.deletions / 1000);+ for (var i=0; i<days.length; i++) {+ var contribution = overallContributions[days[i].getTime()];+ if (contribution) {+ data.push(contribution[1][$contribType[0].selectedIndex]);+ } else {+ data.push(0);}}- data = data.concat(date);return data;}- //Get Monthly Data- var byMonth = getMonthData(jsonUserDailyContribution);- var monthdate = [];- var monthdata = [];- for (var i = 0; i < byMonth.length / 2; i++) {- monthdata.push(byMonth[i]);- }- for (var j = byMonth.length / 2; j < byMonth.length; j++) {- monthdate.push(byMonth[j]);- }- //Get Daily Data- var byDay = getDailyData(jsonUserDailyContribution);- var data = [];- var date = [];- for (var i = 0; i < byDay.length / 2; i++) {- data.push(byDay[i]);++ var useKiloForOverallChart;++ function formatYAxisLabel(value, index, useKilo) {+ if (index == 0)+ useKilo = false;+ else if (index == 1 && value >= 1000)+ useKilo = true;+ return {+ useKilo: useKilo,+ value: useKilo? (value/1000).toFixed(1) + " k": value+ }}- for (var j = byDay.length / 2; j < byDay.length; j++) {- date.push(byDay[j]);- }- var elem = document.getElementsByClassName("project-userline");- var myChart = echarts.init(elem[flag]);- var optionCommits = {- tooltip : {- trigger : 'axis',- position : function(pt) {- return [ pt[0], '10%' ];- }- },- title : {- left : 'center',- text : '',- },- grid : {- left : "5%",- right : "1%",- top : 30,- buttom : 0- },- toolbox : {- feature : {- dataZoom : {- yAxisIndex : 'none',- iconStyle : {- opacity : 0- }- },- restore : {- title: 'Restore date range',- iconStyle : {- opacity : 0- }- },- //saveAsImage: {show:false},- /*mytool:{//自定义按钮 danielinbiti,这里增加,selfbuttons可以随便取名字- show:true,//是否显示- title:'自定义', //鼠标移动上去显示的文字- icon: 'image://images/timg.jpg',- option:{},- onclick:function() {//点击事件,这里的option1是chart的option信息- alert('1');//这里可以加入自己的处理代码,切换不同的图形- }- },*/-- },- right: '40px'- },- xAxis : {- type : 'category',- boundaryGap : false,- data : monthdate,- axisLabel : {- clickable : true- }- },- yAxis : {- axisLine : {- show : false- },- type : 'value',- minInterval : 1,- max : function(value) {- return value.max * 1;- },- boundaryGap : [ 0, '100%' ]- },-- series : [- {- name : 'commits',- type : 'line',- smooth : true,- symbol : 'none',- sampling : 'average',- itemStyle : {- normal : {- color : 'rgba(0, 0, 0,0)'- }- },- areaStyle : {- normal : {- color : new echarts.graphic.LinearGradient(0, 0, 0, 1, [ {- offset : 0,- color : 'rgb(251, 133, 50)'- }, {- offset : 1,- color : 'rgb(251, 133, 50)'- } ])- }- },- data : monthdata- }- ]++ var grid = {+ left: '80px',+ right: '40px',+ top: '40px',+ bottom: '40px'};- var optionCommitsDaily = {- tooltip : {- trigger : 'axis',- position : function(pt) {- return [ pt[0], '10%' ];- }- },- title : {- left : 'center',- text : '',- },- grid : {- left : "5%",- right : "1%",- top : 30,- buttom : 0- },- toolbox : {- feature : {- dataZoom : {- yAxisIndex : 'none',- iconStyle : {- opacity : 0- }- },- restore : {- title: 'Restore date range',- iconStyle : {- opacity : 0- }- },- //saveAsImage: {}- },- right: '40px'- },- xAxis : {- type : 'category',- boundaryGap : false,- data : date,- axisLabel : {- clickable : true- }- },- yAxis : {- axisLine : {- show : false- },- type : 'value',- minInterval : 1,- max : function(value) {- return value.max * 1;- },- boundaryGap : [ 0, '100%' ]- },- series : [- {- name : 'commits',- type : 'line',- smooth : true,- symbol : 'none',- sampling : 'average',- itemStyle : {- normal : {- color : 'rgba(0, 0, 0,0)'- }- },- areaStyle : {- normal : {- color : new echarts.graphic.LinearGradient(0, 0, 0, 1, [ {- offset : 0,- color : 'rgb(251, 133, 50)'- }, {- offset : 1,- color : 'rgb(251, 133, 50)'- } ])- }- },- data : data- }- ]- };- var optionAdditions = {- tooltip : {- trigger : 'axis',- formatter : '{b} <br/>{a}:{c}k',- position : function(pt) {- return [ pt[0], '10%' ];- }- },- title : {- left : 'center',- text : '',- },- grid : {- left : "5%",- right : "1%",- top : 30,- buttom : 0- },- toolbox : {- feature : {- dataZoom : {- yAxisIndex : 'none',- iconStyle : {- opacity : 0- }- },- restore : {- title: 'Restore date range',- iconStyle : {- opacity : 0- }- },- //saveAsImage: {}- },- right: '40px'- },- xAxis : {- type : 'category',- boundaryGap : false,- data : monthdate,- axisLabel : {- clickable : true- }- },- yAxis : {- axisLabel : {- formatter : function(value) {- return value + 'k'- }- },- axisLine : {- show : false- },- type : 'value',- /*max: function(value) {- return value.max *1;- },*/- boundaryGap : [ 0, '100%' ]- },-- series : [- {- name : 'additions',- type : 'line',- smooth : true,- symbol : 'none',- sampling : 'average',- itemStyle : {- normal : {- color : 'rgba(0, 0, 0,0)'- }- },- areaStyle : {- normal : {- color : new echarts.graphic.LinearGradient(0, 0, 0, 1, [ {- offset : 0,- color : 'rgb(251, 133, 50)'- }, {- offset : 1,- color : 'rgb(251, 133, 50)'- } ])- }- },- data : monthdata- }- ]+ var overallChartOption = {+ grid: grid,+ xAxis: {+ type: 'category',+ data: overallXAxisData,+ boundaryGap: false,+ },+ yAxis: {+ minInterval: 1,+ axisLine: {+ show:false+ },+ axisLabel: {+ formatter: function(value, index) {+ var result = formatYAxisLabel(value, index, useKiloForOverallChart);+ useKiloForOverallChart = result.useKilo;+ return result.value;+ }+ },+ },+ toolbox: {+ show: false+ },+ brush: {+ xAxisIndex: 'all',+ brushLink: 'all',+ outOfBrush: {+ colorAlpha: 0.1+ }+ },+ series: [ {+ type: 'line',+ symbol: 'none',+ smooth: true,+ color: "#19A519",+ animation: false,+ data: getOverallSeriesData(),+ areaStyle: {+ color: "#19A519"+ }+ } ]};- var optionAdditionsDaily = {- tooltip : {- trigger : 'axis',- formatter : '{b} <br/>{a}:{c}k',- position : function(pt) {- return [ pt[0], '10%' ];- }- },- title : {- left : 'center',- text : '',- },- grid : {- left : "7%",- right : "1%",- top : 30,- buttom : 0- },- toolbox : {- feature : {- dataZoom : {- yAxisIndex : 'none',- iconStyle : {- opacity : 0- }- },- restore : {- title: 'Restore date range',- iconStyle : {- opacity : 0- }- },- //saveAsImage: {}- },- right: '40px'- },- xAxis : {- type : 'category',- boundaryGap : false,- data : date,- axisLabel : {- clickable : true- }- },- yAxis : {- axisLabel : {- formatter : function(value) {- return value + 'k'- }- },- axisLine : {- show : false- },- type : 'value',- max : function(value) {- return value.max * 1;- },- boundaryGap : [ 0, '100%' ]- },-- series : [- {- name : 'additions',- type : 'line',- smooth : true,- symbol : 'none',- sampling : 'average',- itemStyle : {- normal : {- color : 'rgba(0, 0, 0,0)'- }- },- areaStyle : {- normal : {- color : new echarts.graphic.LinearGradient(0, 0, 0, 1, [ {- offset : 0,- color : 'rgb(251, 133, 50)'- }, {- offset : 1,- color : 'rgb(251, 133, 50)'- } ])- }- },- data : data- }- ]- };--- var optionDeletions = {- tooltip : {- trigger : 'axis',- formatter : '{b} <br/>{a}:{c}k',- position : function(pt) {- return [ pt[0], '10%' ];- }- },- title : {- left : 'center',- text : '',- },- grid : {- left : "5%",- right : "1%",- top : 30,- buttom : 0- },- toolbox : {- feature : {- dataZoom : {- yAxisIndex : 'none',- iconStyle : {- opacity : 0- }- },- restore : {- title: 'Restore date range',- iconStyle : {- opacity : 0- }- },- //saveAsImage: {}- },- right: '40px'- },- xAxis : {- type : 'category',- boundaryGap : false,- data : monthdate,- axisLabel : {- clickable : true- }- },- yAxis : {- axisLabel : {- formatter : function(value) {- return value + 'k'- }- },- axisLine : {- show : false- },- type : 'value',- max : function(value) {- return value.max * 1;- },- boundaryGap : [ 0, '100%' ]- },-- series : [- {- name : 'deletions',- type : 'line',- smooth : true,- symbol : 'none',- sampling : 'average',- itemStyle : {- normal : {- color : 'rgba(0, 0, 0,0)'- }- },- areaStyle : {- normal : {- color : new echarts.graphic.LinearGradient(0, 0, 0, 1, [ {- offset : 0,- color : 'rgb(251, 133, 50)'- }, {- offset : 1,- color : 'rgb(251, 133, 50)'- } ])- }- },- data : monthdata- }- ]- };- var optionDeletionsDaily = {- tooltip : {- trigger : 'axis',- formatter : '{b} <br/>{a}:{c}k',- position : function(pt) {- return [ pt[0], '10%' ];- }- },- title : {- left : 'center',- text : '',- },- grid : {- left : "5%",- right : "1%",- top : 30,- buttom : 0- },- toolbox : {- feature : {- dataZoom : {- yAxisIndex : 'none',- iconStyle : {- opacity : 0- }- },- restore : {- title: 'Restore date range',- iconStyle : {- opacity : 0- }- },- //saveAsImage: {}- },- right: '40px'- },- xAxis : {- type : 'category',- boundaryGap : false,- data : date,- axisLabel : {- clickable : true- }- },- yAxis : {- axisLabel : {- formatter : function(value) {- return value + 'k'- }- },- axisLine : {- show : false- },- type : 'value',- max : function(value) {- return value.max * 1;- },- boundaryGap : [ 0, '100%' ]- },-- series : [- {- name : 'deletions',- type : 'line',- smooth : true,- symbol : 'none',- sampling : 'average',- itemStyle : {- normal : {- color : 'rgba(0, 0, 0,0)'- }- },- areaStyle : {- normal : {- color : new echarts.graphic.LinearGradient(0, 0, 0, 1, [ {- offset : 0,- color : 'rgb(251, 133, 50)'- }, {- offset : 1,- color : 'rgb(251, 133, 50)'- } ])- }- },- data : data- }- ]- };-- if (orderBy == "COMMITS") {- if (gap > 365) myChart.setOption(optionCommits);- else myChart.setOption(optionCommitsDaily);- } else if (orderBy == "ADDITIONS") {- if (gap > 365) myChart.setOption(optionAdditions);- else myChart.setOption(optionAdditionsDaily);- } else {- if (gap > 365) myChart.setOption(optionDeletions);- else myChart.setOption(optionDeletionsDaily);- }- //myChart.showLoading();- $(window).resize(function() {myChart.resize();});- myChart.dispatchAction({- type : 'takeGlobalCursor',- key : 'dataZoomSelect',- dataZoomSelectActive : true // 允许缩放- });-- myChart.on('restore', function(params) {- myChart.clear();- if (gap > 365) {- if (orderBy == "COMMITS") {- myChart.setOption(optionCommits);- } else if (orderBy == "ADDITIONS") {- myChart.setOption(optionAdditions);- } else {- myChart.setOption(optionDeletions);- }- myChart.dispatchAction({- type : 'takeGlobalCursor',- key : 'dataZoomSelect',- dataZoomSelectActive : true- });+ overallChart.setOption(overallChartOption);+ overallChart.dispatchAction({+ type: 'takeGlobalCursor',+ key: 'brush',+ brushOption: {+ brushType: 'lineX',+ brushMode: 'single'+ }+ });+ overallChart.on("brush", function(params) {+ if (params.areas[0]) {+ var selection = params.areas[0].coordRange;+ function normalizeIndex(index) {+ if (index < 0)+ return 0;+ else if (index > days.length -1)+ return days.length-1;+ else+ return index;+ }+ fromDay = days[normalizeIndex(selection[0])];+ toDay = days[normalizeIndex(selection[1])];} else {- if (orderBy == "COMMITS") {- myChart.setOption(optionCommitsDaily);- } else if (orderBy == "ADDITIONS") {- myChart.setOption(optionAdditionsDaily);- } else {- myChart.setOption(optionDeletionsDaily);- }- myChart.dispatchAction({- type : 'takeGlobalCursor',- key : 'dataZoomSelect',- dataZoomSelectActive : true- });+ fromDay = days[0];+ toDay = days[days.length-1];}+ updateDateRange();+ $topContributors.trigger("update");});-- myChart.on('datazoom', function(params) {- myChart.setOption({- toolbox : {- feature : {- restore : {- title: 'Restore date range',- iconStyle : {- opacity : 1++ function updateTopContributors() {+ $topContributors.empty().append("<div class='loading'><img src='/img/ajax-indicator-big.gif'></img></div>");+ setTimeout(function() {+ $.ajax({+ url: topContributorsDataUrl + "&type=" + $contribType.val().toUpperCase() + "&from=" + fromDay.getTime() + "&to=" + toDay.getTime(),+ cache: false,+ beforeSend: function(xhr) {+ xhr.setRequestHeader('Wicket-Ajax', 'true');+ xhr.setRequestHeader('Wicket-Ajax-BaseURL', Wicket.Ajax.baseUrl || '.');+ },+ success: function(topContributors) {+ var xAxisData = [];+ for (var i=0; i<days.length; i++) {+ if (days[i] >= fromDay && days[i] <= toDay)+ xAxisData.push(formatDate(days[i]));+ }++ var maxValue = 0;+ for (var i=0; i<topContributors.length; i++) {+ for (var dayMillis in topContributors[i].dailyContributions) {+ var value = topContributors[i].dailyContributions[dayMillis];+ if (maxValue < value)+ maxValue = value;}}- },- right: '40px'- },- });- var startValue = myChart.getModel().option.dataZoom[0].startValue;- var endValue = myChart.getModel().option.dataZoom[0].endValue;-- //console.log("start"+monthdate[startValue]+"/1");- //console.log("end"+monthdate[endValue]+"/1");-- //console.log(monthdata[startValue]+" + "+monthdata[endValue]);- if (monthdata[startValue] == 0) {- for (var i = startValue + 1; i < endValue; i++) {- if (monthdata[i] != 0) {- startValue = i;- break;- }- }- }- if (monthdata[endValue] == 0) {- for (var i = endValue - 1; i >= startValue; i--) {- if (monthdata[i] != 0) {- endValue = i;- break;- }- }- }-- var startdate = Date.parse(monthdate[startValue]);- var enddate = Date.parse(monthdate[endValue]);-- var startday = new Date(startdate);- var endday = new Date(enddate);- var gapday = (enddate - startdate) / (24 * 3600 * 1000);- //console.log("start----------",[startday.getFullYear(),startday.getMonth() + 1, startday.getDate()].join('/'),[endday.getFullYear(),endday.getMonth() + 1, endday.getDate()].join('/'));- //console.log("gapday in user:"+gapday);- if (gapday < 365 && monthdata[startValue] != 0 && monthdata[endValue] != 0) {- //console.log("here gapday",gapday);- var start = 0;- var end = jsonUserDailyContribution.length - 1;- for (var i = 0; i < jsonUserDailyContribution.length; i++) {- var day = new Date(jsonUserDailyContribution[i].day.dateTime);- if (start == 0) {- if (day.getFullYear() == startday.getFullYear() && day.getMonth() == startday.getMonth()) {- start = i;- }- }- if (day.getFullYear() == endday.getFullYear() && day.getMonth() == endday.getMonth()) {- end = i;- break;- }- }- //console.log("start:"+start+" end:"+end);-- var userDailyContribution = jsonUserDailyContribution.slice(start, end + 1);- var newdata = [];- var newdate = [];- var byDay = getDailyData(userDailyContribution);- for (var i = 0; i < byDay.length / 2; i++) {- newdata.push(byDay[i]);- }- for (var j = byDay.length / 2; j < byDay.length; j++) {- newdate.push(byDay[j]);- }- //console.log("date:"+newdate);- //console.log("data:"+newdata);-- myChart.clear();- myChart.setOption({- tooltip : {- trigger : 'axis',- position : function(pt) {- return [ pt[0], '10%' ];- }- },- title : {- left : 'center',- text : '',- },- grid : {- left : "5%",- right : "1%",- top : 30,- buttom : 0- },- toolbox : {- feature : {- dataZoom : {- yAxisIndex : 'none',- iconStyle : {- opacity : 0- }- },- restore : {- title: 'Restore date range',- },- //saveAsImage: {}- },- right: '40px'- },- xAxis : {- type : 'category',- boundaryGap : false,- data : newdate,- axisLabel : {- clickable : true- }- },- yAxis : {- axisLine : {- show : false- },- type : 'value',- minInterval : 1,- max : function(value) {- return value.max * 1;- },- boundaryGap : [ 0, '100%' ]- },-- series : [- {- //name:'commits',- type : 'line',- smooth : true,- symbol : 'none',- sampling : 'average',- itemStyle : {- normal : {- color : 'rgba(0, 0, 0,0)'- }- },- areaStyle : {- normal : {- color : new echarts.graphic.LinearGradient(0, 0, 0, 1, [ {- offset : 0,- color : 'rgb(251, 133, 50)'- }, {- offset : 1,- color : 'rgb(251, 133, 50)'- } ])- }- },- data : newdata- }- ]- }, true);- if (orderBy == "COMMITS") {- myChart.setOption({- series : [- {- name : 'commits',- }- ]- });- } else if (orderBy == "ADDITIONS") {- myChart.setOption({- yAxis : {- axisLabel : {- formatter : function(value) {- return value + 'k'- }- },- },- series : [- {- name : 'additions',++ function renderContributor($container, contributor, index) {+ var $content = $("<div class='content'></div>");+ $container.append($content);+ var $head = $("<div class='head clearfix'></div>");+ $content.append($head);+ var $left = $("<div class='pull-left'></div>");+ $head.append($left);+ $left.append("<img class='avatar' src='" + contributor.authorAvatarUrl + "'></img>");+ var nameSpan = "<span class='name'>" + contributor.authorName + "</span>";+ if (contributor.authorUrl) {+ $left.append("<a href='" + contributor.authorUrl + "'>" + nameSpan + "</a>");+ } else {+ $left.append(nameSpan);}- ]- });- } else {- myChart.setOption({- yAxis : {- axisLabel : {- formatter : function(value) {- return value + 'k'+ var $totalContribution = $("<div class='total-contribution'></div>");+ $left.append($totalContribution);+ $totalContribution.append("<span class='commits'>" + contributor.totalCommits + " commits</span>");+ $totalContribution.append("<span class='additions'>" + contributor.totalAdditions + " ++</span>");+ $totalContribution.append("<span class='deletions'>" + contributor.totalDeletions + " --</span>");+ $head.append("<div class='pull-right'>#" + (index + 1) + "</div>");++ var $body = $("<div class='body chart'></div>");+ $content.append($body);++ var chart = echarts.init($body[0]);+ $body.data("chart", chart);++ var seriesData = [];+ var maxValueOfContributor = 0;+ for (var i=0; i<days.length; i++) {+ if (days[i] >= fromDay && days[i] <= toDay) {+ var contribution = contributor.dailyContributions[days[i].getTime()];+ if (contribution) {+ seriesData.push(contribution);+ if (maxValueOfContributor < contribution)+ maxValueOfContributor = contribution;+ } else {+ seriesData.push(0);+ }}- },- },- series : [- {- name : 'deletions',}- ]- });- }- myChart.dispatchAction({- type : 'takeGlobalCursor',- key : 'dataZoomSelect',- dataZoomSelectActive : true++ var useKilo;+ var option = {+ grid: grid,+ xAxis: {+ type: 'category',+ data: xAxisData,+ boundaryGap: false+ },+ yAxis: {+ minInterval: 1,+ axisLine: {+ show:false+ },+ boundaryGap: [0, (maxValue-maxValueOfContributor)/maxValueOfContributor],+ axisLabel: {+ formatter: function(value, index) {+ var result = formatYAxisLabel(value, index, useKilo);+ useKilo = result.useKilo;+ return result.value;+ }+ },+ },+ series: [ {+ type: 'line',+ color: "#EEAD08",+ symbol: 'none',+ smooth: true,+ animation: false,+ areaStyle: {+ color: "#EEAD08"+ },+ data: seriesData,+ } ]+ };+ chart.setOption(option);+ }++ $topContributors.empty();+ var rows = Math.trunc(topContributors.length/2);+ for (var i=0; i<rows; i++) {+ var $row = $("<div class='row'><div class='col-md-6 left'></div><div class='col-md-6 right'></div>");+ $topContributors.append($row);+ renderContributor($row.children(".left"), topContributors[i*2], i*2);+ renderContributor($row.children(".right"), topContributors[i*2+1], i*2+1);+ }+ if (rows*2 < topContributors.length) {+ var $row = $("<div class='row'><div class='col-md-6 left'></div></div");+ $topContributors.append($row);+ renderContributor($row.children(".left"), topContributors[rows*2], rows*2);+ }+ },});- }+ }, 10);+ }++ $contribType.change(function() {+ overallChartOption.series[0].data = getOverallSeriesData();+ overallChart.setOption(overallChartOption);+ updateTopContributors();+ });++ $topContributors.doneEvents("update", function() {+ updateTopContributors();+ });++ updateDateRange();+ updateTopContributors();++ $(window).resize(function() {+ $contribs.find(".chart").each(function() {+ $(this).data("chart").resize();+ });});}},-- sourceLines : {- onDomReady : function() {}+ sourceLines: {+ onDomReady: function() {}}}\ No newline at end of filediff --git a/product/src/test/java/io/onedev/server/product/Test.java b/product/src/test/java/io/onedev/server/product/Test.javaindex 457a49af9a..80b25e09ab 100644--- a/product/src/test/java/io/onedev/server/product/Test.java+++ b/product/src/test/java/io/onedev/server/product/Test.java@@ -1,9 +1,11 @@package io.onedev.server.product;+import com.fasterxml.jackson.core.JsonProcessingException;+public class Test {@org.junit.Test- public void test() {+ public void test() throws JsonProcessingException {}}\ No newline at end of file