gitea源码

DiffCommitSelector.vue 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. <script lang="ts">
  2. import {defineComponent} from 'vue';
  3. import {SvgIcon} from '../svg.ts';
  4. import {GET} from '../modules/fetch.ts';
  5. import {generateElemId} from '../utils/dom.ts';
  6. type Commit = {
  7. id: string,
  8. hovered: boolean,
  9. selected: boolean,
  10. summary: string,
  11. committer_or_author_name: string,
  12. time: string,
  13. short_sha: string,
  14. }
  15. type CommitListResult = {
  16. commits: Array<Commit>,
  17. last_review_commit_sha: string,
  18. locale: Record<string, string>,
  19. }
  20. export default defineComponent({
  21. components: {SvgIcon},
  22. data: () => {
  23. const el = document.querySelector('#diff-commit-select');
  24. return {
  25. menuVisible: false,
  26. isLoading: false,
  27. queryParams: el.getAttribute('data-queryparams'),
  28. issueLink: el.getAttribute('data-issuelink'),
  29. locale: {
  30. filter_changes_by_commit: el.getAttribute('data-filter_changes_by_commit'),
  31. } as Record<string, string>,
  32. mergeBase: el.getAttribute('data-merge-base'),
  33. commits: [] as Array<Commit>,
  34. hoverActivated: false,
  35. lastReviewCommitSha: '',
  36. uniqueIdMenu: generateElemId('diff-commit-selector-menu-'),
  37. uniqueIdShowAll: generateElemId('diff-commit-selector-show-all-'),
  38. };
  39. },
  40. computed: {
  41. commitsSinceLastReview() {
  42. if (this.lastReviewCommitSha) {
  43. return this.commits.length - this.commits.findIndex((x) => x.id === this.lastReviewCommitSha) - 1;
  44. }
  45. return 0;
  46. },
  47. },
  48. mounted() {
  49. document.body.addEventListener('click', this.onBodyClick);
  50. this.$el.addEventListener('keydown', this.onKeyDown);
  51. this.$el.addEventListener('keyup', this.onKeyUp);
  52. },
  53. unmounted() {
  54. document.body.removeEventListener('click', this.onBodyClick);
  55. this.$el.removeEventListener('keydown', this.onKeyDown);
  56. this.$el.removeEventListener('keyup', this.onKeyUp);
  57. },
  58. methods: {
  59. onBodyClick(event: MouseEvent) {
  60. // close this menu on click outside of this element when the dropdown is currently visible opened
  61. if (this.$el.contains(event.target)) return;
  62. if (this.menuVisible) {
  63. this.toggleMenu();
  64. }
  65. },
  66. onKeyDown(event: KeyboardEvent) {
  67. if (!this.menuVisible) return;
  68. const item = document.activeElement as HTMLElement;
  69. if (!this.$el.contains(item)) return;
  70. switch (event.key) {
  71. case 'ArrowDown': // select next element
  72. event.preventDefault();
  73. this.focusElem(item.nextElementSibling as HTMLElement, item);
  74. break;
  75. case 'ArrowUp': // select previous element
  76. event.preventDefault();
  77. this.focusElem(item.previousElementSibling as HTMLElement, item);
  78. break;
  79. case 'Escape': // close menu
  80. event.preventDefault();
  81. item.tabIndex = -1;
  82. this.toggleMenu();
  83. break;
  84. }
  85. if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
  86. const item = document.activeElement; // try to highlight the selected commits
  87. const commitIdx = item?.matches('.item') ? item.getAttribute('data-commit-idx') : null;
  88. if (commitIdx) this.highlight(this.commits[Number(commitIdx)]);
  89. }
  90. },
  91. onKeyUp(event: KeyboardEvent) {
  92. if (!this.menuVisible) return;
  93. const item = document.activeElement;
  94. if (!this.$el.contains(item)) return;
  95. if (event.key === 'Shift' && this.hoverActivated) {
  96. // shift is not pressed anymore -> deactivate hovering and reset hovered and selected
  97. this.hoverActivated = false;
  98. for (const commit of this.commits) {
  99. commit.hovered = false;
  100. commit.selected = false;
  101. }
  102. }
  103. },
  104. highlight(commit: Commit) {
  105. if (!this.hoverActivated) return;
  106. const indexSelected = this.commits.findIndex((x) => x.selected);
  107. const indexCurrentElem = this.commits.findIndex((x) => x.id === commit.id);
  108. for (const [idx, commit] of this.commits.entries()) {
  109. commit.hovered = Math.min(indexSelected, indexCurrentElem) <= idx && idx <= Math.max(indexSelected, indexCurrentElem);
  110. }
  111. },
  112. /** Focus given element */
  113. focusElem(elem: HTMLElement, prevElem: HTMLElement) {
  114. if (elem) {
  115. elem.tabIndex = 0;
  116. if (prevElem) prevElem.tabIndex = -1;
  117. elem.focus();
  118. }
  119. },
  120. /** Opens our menu, loads commits before opening */
  121. async toggleMenu() {
  122. this.menuVisible = !this.menuVisible;
  123. // load our commits when the menu is not yet visible (it'll be toggled after loading)
  124. // and we got no commits
  125. if (!this.commits.length && this.menuVisible && !this.isLoading) {
  126. this.isLoading = true;
  127. try {
  128. await this.fetchCommits();
  129. } finally {
  130. this.isLoading = false;
  131. }
  132. }
  133. // set correct tabindex to allow easier navigation
  134. this.$nextTick(() => {
  135. if (this.menuVisible) {
  136. this.focusElem(this.$refs.showAllChanges as HTMLElement, this.$refs.expandBtn as HTMLElement);
  137. } else {
  138. this.focusElem(this.$refs.expandBtn as HTMLElement, this.$refs.showAllChanges as HTMLElement);
  139. }
  140. });
  141. },
  142. /** Load the commits to show in this dropdown */
  143. async fetchCommits() {
  144. const resp = await GET(`${this.issueLink}/commits/list`);
  145. const results = await resp.json() as CommitListResult;
  146. this.commits.push(...results.commits.map((x) => {
  147. x.hovered = false;
  148. return x;
  149. }));
  150. this.commits.reverse();
  151. this.lastReviewCommitSha = results.last_review_commit_sha || null;
  152. if (this.lastReviewCommitSha && !this.commits.some((x) => x.id === this.lastReviewCommitSha)) {
  153. // the lastReviewCommit is not available (probably due to a force push)
  154. // reset the last review commit sha
  155. this.lastReviewCommitSha = null;
  156. }
  157. Object.assign(this.locale, results.locale);
  158. },
  159. showAllChanges() {
  160. window.location.assign(`${this.issueLink}/files${this.queryParams}`);
  161. },
  162. /** Called when user clicks on since last review */
  163. changesSinceLastReviewClick() {
  164. window.location.assign(`${this.issueLink}/files/${this.lastReviewCommitSha}..${this.commits.at(-1).id}${this.queryParams}`);
  165. },
  166. /** Clicking on a single commit opens this specific commit */
  167. commitClicked(commitId: string, newWindow = false) {
  168. const url = `${this.issueLink}/commits/${commitId}${this.queryParams}`;
  169. if (newWindow) {
  170. window.open(url);
  171. } else {
  172. window.location.assign(url);
  173. }
  174. },
  175. /**
  176. * When a commit is clicked while holding Shift, it enables range selection.
  177. * - The range selection is a half-open, half-closed range, meaning it excludes the start commit but includes the end commit.
  178. * - The start of the commit range is always the previous commit of the first clicked commit.
  179. * - If the first commit in the list is clicked, the mergeBase will be used as the start of the range instead.
  180. * - The second Shift-click defines the end of the range.
  181. * - Once both are selected, the diff view for the selected commit range will open.
  182. */
  183. commitClickedShift(commit: Commit) {
  184. this.hoverActivated = !this.hoverActivated;
  185. commit.selected = true;
  186. // Second click -> determine our range and open links accordingly
  187. if (!this.hoverActivated) {
  188. // since at least one commit is selected, we can determine the range
  189. // find all selected commits and generate a link
  190. const firstSelected = this.commits.findIndex((x) => x.selected);
  191. const lastSelected = this.commits.findLastIndex((x) => x.selected);
  192. let beforeCommitID: string;
  193. if (firstSelected === 0) {
  194. beforeCommitID = this.mergeBase;
  195. } else {
  196. beforeCommitID = this.commits[firstSelected - 1].id;
  197. }
  198. const afterCommitID = this.commits[lastSelected].id;
  199. if (firstSelected === lastSelected) {
  200. // if the start and end are the same, we show this single commit
  201. window.location.assign(`${this.issueLink}/commits/${afterCommitID}${this.queryParams}`);
  202. } else if (beforeCommitID === this.mergeBase && afterCommitID === this.commits.at(-1).id) {
  203. // if the first commit is selected and the last commit is selected, we show all commits
  204. window.location.assign(`${this.issueLink}/files${this.queryParams}`);
  205. } else {
  206. window.location.assign(`${this.issueLink}/files/${beforeCommitID}..${afterCommitID}${this.queryParams}`);
  207. }
  208. }
  209. },
  210. },
  211. });
  212. </script>
  213. <template>
  214. <div class="ui scrolling dropdown custom diff-commit-selector">
  215. <button
  216. ref="expandBtn"
  217. class="ui tiny basic button"
  218. @click.stop="toggleMenu()"
  219. :data-tooltip-content="locale.filter_changes_by_commit"
  220. aria-haspopup="true"
  221. :aria-label="locale.filter_changes_by_commit"
  222. :aria-controls="uniqueIdMenu"
  223. :aria-activedescendant="uniqueIdShowAll"
  224. >
  225. <svg-icon name="octicon-git-commit"/>
  226. </button>
  227. <!-- this dropdown is not managed by Fomantic UI, so it needs some classes like "transition" explicitly -->
  228. <div class="left menu transition" :id="uniqueIdMenu" :class="{visible: menuVisible}" v-show="menuVisible" v-cloak :aria-expanded="menuVisible ? 'true': 'false'">
  229. <div class="loading-indicator is-loading" v-if="isLoading"/>
  230. <div v-if="!isLoading" class="item" :id="uniqueIdShowAll" ref="showAllChanges" role="menuitem" @keydown.enter="showAllChanges()" @click="showAllChanges()">
  231. <div class="gt-ellipsis">
  232. {{ locale.show_all_commits }}
  233. </div>
  234. <div class="gt-ellipsis text light-2 tw-mb-0">
  235. {{ locale.stats_num_commits }}
  236. </div>
  237. </div>
  238. <!-- only show the show changes since last review if there is a review AND we are commits ahead of the last review -->
  239. <div
  240. v-if="lastReviewCommitSha != null"
  241. class="item" role="menuitem"
  242. :class="{disabled: !commitsSinceLastReview}"
  243. @keydown.enter="changesSinceLastReviewClick()"
  244. @click="changesSinceLastReviewClick()"
  245. >
  246. <div class="gt-ellipsis">
  247. {{ locale.show_changes_since_your_last_review }}
  248. </div>
  249. <div class="gt-ellipsis text light-2">
  250. {{ commitsSinceLastReview }} commits
  251. </div>
  252. </div>
  253. <span v-if="!isLoading" class="info text light-2">{{ locale.select_commit_hold_shift_for_range }}</span>
  254. <template v-for="(commit, idx) in commits" :key="commit.id">
  255. <div
  256. class="item" role="menuitem"
  257. :class="{selected: commit.selected, hovered: commit.hovered}"
  258. :data-commit-idx="idx"
  259. @keydown.enter.exact="commitClicked(commit.id)"
  260. @keydown.enter.shift.exact="commitClickedShift(commit)"
  261. @mouseover.shift="highlight(commit)"
  262. @click.exact="commitClicked(commit.id)"
  263. @click.ctrl.exact="commitClicked(commit.id, true)"
  264. @click.meta.exact="commitClicked(commit.id, true)"
  265. @click.shift.exact.stop.prevent="commitClickedShift(commit)"
  266. >
  267. <div class="tw-flex-1 tw-flex tw-flex-col tw-gap-1">
  268. <div class="gt-ellipsis commit-list-summary">
  269. {{ commit.summary }}
  270. </div>
  271. <div class="gt-ellipsis text light-2">
  272. {{ commit.committer_or_author_name }}
  273. <span class="text right">
  274. <!-- TODO: make this respect the PreferredTimestampTense setting -->
  275. <relative-time prefix="" :datetime="commit.time" data-tooltip-content data-tooltip-interactive="true">{{ commit.time }}</relative-time>
  276. </span>
  277. </div>
  278. </div>
  279. <div class="tw-font-mono">
  280. {{ commit.short_sha }}
  281. </div>
  282. </div>
  283. </template>
  284. </div>
  285. </div>
  286. </template>
  287. <style scoped>
  288. .ui.dropdown.diff-commit-selector .menu {
  289. margin-top: 0.25em;
  290. overflow-x: hidden;
  291. max-height: 450px;
  292. }
  293. .ui.dropdown.diff-commit-selector .menu .loading-indicator {
  294. height: 200px;
  295. width: 350px;
  296. }
  297. .ui.dropdown.diff-commit-selector .menu > .item,
  298. .ui.dropdown.diff-commit-selector .menu > .info {
  299. display: flex;
  300. flex-direction: row;
  301. line-height: 1.4;
  302. gap: 0.25em;
  303. padding: 7px 14px !important;
  304. }
  305. .ui.dropdown.diff-commit-selector .menu > .item:not(:first-child),
  306. .ui.dropdown.diff-commit-selector .menu > .info:not(:first-child) {
  307. border-top: 1px solid var(--color-secondary) !important;
  308. }
  309. .ui.dropdown.diff-commit-selector .menu > .item:focus {
  310. background: var(--color-active);
  311. }
  312. .ui.dropdown.diff-commit-selector .menu > .item.hovered {
  313. background-color: var(--color-small-accent);
  314. }
  315. .ui.dropdown.diff-commit-selector .menu > .item.selected {
  316. background-color: var(--color-accent);
  317. }
  318. .ui.dropdown.diff-commit-selector .menu .commit-list-summary {
  319. max-width: min(380px, 96vw);
  320. }
  321. </style>