You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RepoContributors.vue 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. <script>
  2. import {SvgIcon} from '../svg.js';
  3. import {
  4. Chart,
  5. Title,
  6. BarElement,
  7. LinearScale,
  8. TimeScale,
  9. PointElement,
  10. LineElement,
  11. Filler,
  12. } from 'chart.js';
  13. import {GET} from '../modules/fetch.js';
  14. import zoomPlugin from 'chartjs-plugin-zoom';
  15. import {Line as ChartLine} from 'vue-chartjs';
  16. import {
  17. startDaysBetween,
  18. firstStartDateAfterDate,
  19. fillEmptyStartDaysWithZeroes,
  20. } from '../utils/time.js';
  21. import {chartJsColors} from '../utils/color.js';
  22. import {sleep} from '../utils.js';
  23. import 'chartjs-adapter-dayjs-4/dist/chartjs-adapter-dayjs-4.esm';
  24. import $ from 'jquery';
  25. const {pageData} = window.config;
  26. const customEventListener = {
  27. id: 'customEventListener',
  28. afterEvent: (chart, args, opts) => {
  29. // event will be replayed from chart.update when reset zoom,
  30. // so we need to check whether args.replay is true to avoid call loops
  31. if (args.event.type === 'dblclick' && opts.chartType === 'main' && !args.replay) {
  32. chart.resetZoom();
  33. opts.instance.updateOtherCharts(args.event, true);
  34. }
  35. },
  36. };
  37. Chart.defaults.color = chartJsColors.text;
  38. Chart.defaults.borderColor = chartJsColors.border;
  39. Chart.register(
  40. TimeScale,
  41. LinearScale,
  42. BarElement,
  43. Title,
  44. PointElement,
  45. LineElement,
  46. Filler,
  47. zoomPlugin,
  48. customEventListener,
  49. );
  50. export default {
  51. components: {ChartLine, SvgIcon},
  52. props: {
  53. locale: {
  54. type: Object,
  55. required: true,
  56. },
  57. },
  58. data: () => ({
  59. isLoading: false,
  60. errorText: '',
  61. totalStats: {},
  62. sortedContributors: {},
  63. repoLink: pageData.repoLink || [],
  64. type: pageData.contributionType,
  65. contributorsStats: [],
  66. xAxisStart: null,
  67. xAxisEnd: null,
  68. xAxisMin: null,
  69. xAxisMax: null,
  70. }),
  71. mounted() {
  72. this.fetchGraphData();
  73. $('#repo-contributors').dropdown({
  74. onChange: (val) => {
  75. this.xAxisMin = this.xAxisStart;
  76. this.xAxisMax = this.xAxisEnd;
  77. this.type = val;
  78. this.sortContributors();
  79. },
  80. });
  81. },
  82. methods: {
  83. sortContributors() {
  84. const contributors = this.filterContributorWeeksByDateRange();
  85. const criteria = `total_${this.type}`;
  86. this.sortedContributors = Object.values(contributors)
  87. .filter((contributor) => contributor[criteria] !== 0)
  88. .sort((a, b) => a[criteria] > b[criteria] ? -1 : a[criteria] === b[criteria] ? 0 : 1)
  89. .slice(0, 100);
  90. },
  91. async fetchGraphData() {
  92. this.isLoading = true;
  93. try {
  94. let response;
  95. do {
  96. response = await GET(`${this.repoLink}/activity/contributors/data`);
  97. if (response.status === 202) {
  98. await sleep(1000); // wait for 1 second before retrying
  99. }
  100. } while (response.status === 202);
  101. if (response.ok) {
  102. const data = await response.json();
  103. const {total, ...rest} = data;
  104. // below line might be deleted if we are sure go produces map always sorted by keys
  105. total.weeks = Object.fromEntries(Object.entries(total.weeks).sort());
  106. const weekValues = Object.values(total.weeks);
  107. this.xAxisStart = weekValues[0].week;
  108. this.xAxisEnd = firstStartDateAfterDate(new Date());
  109. const startDays = startDaysBetween(new Date(this.xAxisStart), new Date(this.xAxisEnd));
  110. total.weeks = fillEmptyStartDaysWithZeroes(startDays, total.weeks);
  111. this.xAxisMin = this.xAxisStart;
  112. this.xAxisMax = this.xAxisEnd;
  113. this.contributorsStats = {};
  114. for (const [email, user] of Object.entries(rest)) {
  115. user.weeks = fillEmptyStartDaysWithZeroes(startDays, user.weeks);
  116. this.contributorsStats[email] = user;
  117. }
  118. this.sortContributors();
  119. this.totalStats = total;
  120. this.errorText = '';
  121. } else {
  122. this.errorText = response.statusText;
  123. }
  124. } catch (err) {
  125. this.errorText = err.message;
  126. } finally {
  127. this.isLoading = false;
  128. }
  129. },
  130. filterContributorWeeksByDateRange() {
  131. const filteredData = {};
  132. const data = this.contributorsStats;
  133. for (const key of Object.keys(data)) {
  134. const user = data[key];
  135. user.total_commits = 0;
  136. user.total_additions = 0;
  137. user.total_deletions = 0;
  138. user.max_contribution_type = 0;
  139. const filteredWeeks = user.weeks.filter((week) => {
  140. const oneWeek = 7 * 24 * 60 * 60 * 1000;
  141. if (week.week >= this.xAxisMin - oneWeek && week.week <= this.xAxisMax + oneWeek) {
  142. user.total_commits += week.commits;
  143. user.total_additions += week.additions;
  144. user.total_deletions += week.deletions;
  145. if (week[this.type] > user.max_contribution_type) {
  146. user.max_contribution_type = week[this.type];
  147. }
  148. return true;
  149. }
  150. return false;
  151. });
  152. // this line is required. See https://github.com/sahinakkaya/gitea/pull/3#discussion_r1396495722
  153. // for details.
  154. user.max_contribution_type += 1;
  155. filteredData[key] = {...user, weeks: filteredWeeks};
  156. }
  157. return filteredData;
  158. },
  159. maxMainGraph() {
  160. // This method calculates maximum value for Y value of the main graph. If the number
  161. // of maximum contributions for selected contribution type is 15.955 it is probably
  162. // better to round it up to 20.000.This method is responsible for doing that.
  163. // Normally, chartjs handles this automatically, but it will resize the graph when you
  164. // zoom, pan etc. I think resizing the graph makes it harder to compare things visually.
  165. const maxValue = Math.max(
  166. ...this.totalStats.weeks.map((o) => o[this.type]),
  167. );
  168. const [coefficient, exp] = maxValue.toExponential().split('e').map(Number);
  169. if (coefficient % 1 === 0) return maxValue;
  170. return (1 - (coefficient % 1)) * 10 ** exp + maxValue;
  171. },
  172. maxContributorGraph() {
  173. // Similar to maxMainGraph method this method calculates maximum value for Y value
  174. // for contributors' graph. If I let chartjs do this for me, it will choose different
  175. // maxY value for each contributors' graph which again makes it harder to compare.
  176. const maxValue = Math.max(
  177. ...this.sortedContributors.map((c) => c.max_contribution_type),
  178. );
  179. const [coefficient, exp] = maxValue.toExponential().split('e').map(Number);
  180. if (coefficient % 1 === 0) return maxValue;
  181. return (1 - (coefficient % 1)) * 10 ** exp + maxValue;
  182. },
  183. toGraphData(data) {
  184. return {
  185. datasets: [
  186. {
  187. data: data.map((i) => ({x: i.week, y: i[this.type]})),
  188. pointRadius: 0,
  189. pointHitRadius: 0,
  190. fill: 'start',
  191. backgroundColor: chartJsColors[this.type],
  192. borderWidth: 0,
  193. tension: 0.3,
  194. },
  195. ],
  196. };
  197. },
  198. updateOtherCharts(event, reset) {
  199. const minVal = event.chart.options.scales.x.min;
  200. const maxVal = event.chart.options.scales.x.max;
  201. if (reset) {
  202. this.xAxisMin = this.xAxisStart;
  203. this.xAxisMax = this.xAxisEnd;
  204. this.sortContributors();
  205. } else if (minVal) {
  206. this.xAxisMin = minVal;
  207. this.xAxisMax = maxVal;
  208. this.sortContributors();
  209. }
  210. },
  211. getOptions(type) {
  212. return {
  213. responsive: true,
  214. maintainAspectRatio: false,
  215. animation: false,
  216. events: ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove', 'dblclick'],
  217. plugins: {
  218. title: {
  219. display: type === 'main',
  220. text: 'drag: zoom, shift+drag: pan, double click: reset zoom',
  221. position: 'top',
  222. align: 'center',
  223. },
  224. customEventListener: {
  225. chartType: type,
  226. instance: this,
  227. },
  228. zoom: {
  229. pan: {
  230. enabled: true,
  231. modifierKey: 'shift',
  232. mode: 'x',
  233. threshold: 20,
  234. onPanComplete: this.updateOtherCharts,
  235. },
  236. limits: {
  237. x: {
  238. // Check https://www.chartjs.org/chartjs-plugin-zoom/latest/guide/options.html#scale-limits
  239. // to know what each option means
  240. min: 'original',
  241. max: 'original',
  242. // number of milliseconds in 2 weeks. Minimum x range will be 2 weeks when you zoom on the graph
  243. minRange: 2 * 7 * 24 * 60 * 60 * 1000,
  244. },
  245. },
  246. zoom: {
  247. drag: {
  248. enabled: type === 'main',
  249. },
  250. pinch: {
  251. enabled: type === 'main',
  252. },
  253. mode: 'x',
  254. onZoomComplete: this.updateOtherCharts,
  255. },
  256. },
  257. },
  258. scales: {
  259. x: {
  260. min: this.xAxisMin,
  261. max: this.xAxisMax,
  262. type: 'time',
  263. grid: {
  264. display: false,
  265. },
  266. time: {
  267. minUnit: 'month',
  268. },
  269. ticks: {
  270. maxRotation: 0,
  271. maxTicksLimit: type === 'main' ? 12 : 6,
  272. },
  273. },
  274. y: {
  275. min: 0,
  276. max: type === 'main' ? this.maxMainGraph() : this.maxContributorGraph(),
  277. ticks: {
  278. maxTicksLimit: type === 'main' ? 6 : 4,
  279. },
  280. },
  281. },
  282. };
  283. },
  284. },
  285. };
  286. </script>
  287. <template>
  288. <div>
  289. <div class="ui header tw-flex tw-content-center tw-justify-between">
  290. <div>
  291. <relative-time
  292. v-if="xAxisMin > 0"
  293. format="datetime"
  294. year="numeric"
  295. month="short"
  296. day="numeric"
  297. weekday=""
  298. :datetime="new Date(xAxisMin)"
  299. >
  300. {{ new Date(xAxisMin) }}
  301. </relative-time>
  302. {{ isLoading ? locale.loadingTitle : errorText ? locale.loadingTitleFailed: "-" }}
  303. <relative-time
  304. v-if="xAxisMax > 0"
  305. format="datetime"
  306. year="numeric"
  307. month="short"
  308. day="numeric"
  309. weekday=""
  310. :datetime="new Date(xAxisMax)"
  311. >
  312. {{ new Date(xAxisMax) }}
  313. </relative-time>
  314. </div>
  315. <div>
  316. <!-- Contribution type -->
  317. <div class="ui dropdown jump" id="repo-contributors">
  318. <div class="ui basic compact button">
  319. <span class="text">
  320. <span class="not-mobile">{{ locale.filterLabel }}&nbsp;</span><strong>{{ locale.contributionType[type] }}</strong>
  321. <svg-icon name="octicon-triangle-down" :size="14"/>
  322. </span>
  323. </div>
  324. <div class="menu">
  325. <div :class="['item', {'active': type === 'commits'}]">
  326. {{ locale.contributionType.commits }}
  327. </div>
  328. <div :class="['item', {'active': type === 'additions'}]">
  329. {{ locale.contributionType.additions }}
  330. </div>
  331. <div :class="['item', {'active': type === 'deletions'}]">
  332. {{ locale.contributionType.deletions }}
  333. </div>
  334. </div>
  335. </div>
  336. </div>
  337. </div>
  338. <div class="tw-flex ui segment main-graph">
  339. <div v-if="isLoading || errorText !== ''" class="gt-tc tw-m-auto">
  340. <div v-if="isLoading">
  341. <SvgIcon name="octicon-sync" class="gt-mr-3 job-status-rotate"/>
  342. {{ locale.loadingInfo }}
  343. </div>
  344. <div v-else class="text red">
  345. <SvgIcon name="octicon-x-circle-fill"/>
  346. {{ errorText }}
  347. </div>
  348. </div>
  349. <ChartLine
  350. v-memo="[totalStats.weeks, type]" v-if="Object.keys(totalStats).length !== 0"
  351. :data="toGraphData(totalStats.weeks)" :options="getOptions('main')"
  352. />
  353. </div>
  354. <div class="contributor-grid">
  355. <div
  356. v-for="(contributor, index) in sortedContributors"
  357. :key="index"
  358. v-memo="[sortedContributors, type]"
  359. >
  360. <div class="ui top attached header tw-flex tw-flex-1">
  361. <b class="ui right">#{{ index + 1 }}</b>
  362. <a :href="contributor.home_link">
  363. <img class="ui avatar tw-align-middle" height="40" width="40" :src="contributor.avatar_link">
  364. </a>
  365. <div class="gt-ml-3">
  366. <a v-if="contributor.home_link !== ''" :href="contributor.home_link"><h4>{{ contributor.name }}</h4></a>
  367. <h4 v-else class="contributor-name">
  368. {{ contributor.name }}
  369. </h4>
  370. <p class="gt-font-12 tw-flex gt-gap-2">
  371. <strong v-if="contributor.total_commits">{{ contributor.total_commits.toLocaleString() }} {{ locale.contributionType.commits }}</strong>
  372. <strong v-if="contributor.total_additions" class="text green">{{ contributor.total_additions.toLocaleString() }}++ </strong>
  373. <strong v-if="contributor.total_deletions" class="text red">
  374. {{ contributor.total_deletions.toLocaleString() }}--</strong>
  375. </p>
  376. </div>
  377. </div>
  378. <div class="ui attached segment">
  379. <div>
  380. <ChartLine
  381. :data="toGraphData(contributor.weeks)"
  382. :options="getOptions('contributor')"
  383. />
  384. </div>
  385. </div>
  386. </div>
  387. </div>
  388. </div>
  389. </template>
  390. <style scoped>
  391. .main-graph {
  392. height: 260px;
  393. padding-top: 2px;
  394. }
  395. .contributor-grid {
  396. display: grid;
  397. grid-template-columns: repeat(2, 1fr);
  398. gap: 1rem;
  399. }
  400. .contributor-grid > * {
  401. min-width: 0;
  402. }
  403. @media (max-width: 991.98px) {
  404. .contributor-grid {
  405. grid-template-columns: repeat(1, 1fr);
  406. }
  407. }
  408. .contributor-name {
  409. margin-bottom: 0;
  410. }
  411. </style>