// ==UserScript== // @name AzDO Pull Request Improvements // @version 2.26.2 // @author Alejandro Barreto (National Instruments) // @description Adds sorting and categorization to the PR dashboard. Also adds minor improvements to the PR diff experience, such as a base update selector and per-file checkboxes. // @license MIT // @namespace https://github.com/alejandro5042 // @homepageURL https://alejandro5042.github.io/azdo-userscripts/ // @supportURL https://alejandro5042.github.io/azdo-userscripts/SUPPORT.html // @contributionURL https://github.com/alejandro5042/azdo-userscripts // @include https://dev.azure.com/* // @include https://*.visualstudio.com/* // @run-at document-end // @require https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js#sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8= // @require https://cdnjs.cloudflare.com/ajax/libs/jquery-once/2.2.3/jquery.once.min.js#sha256-HaeXVMzafCQfVtWoLtN3wzhLWNs8cY2cH9OIQ8R9jfM= // @require https://cdnjs.cloudflare.com/ajax/libs/lscache/1.3.0/lscache.js#sha256-QVvX22TtfzD4pclw/4yxR0G1/db2GZMYG9+gxRM9v30= // @require https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js#sha256-wCBClaCr6pJ7sGU5kfb3gQMOOcIZNzaWpWcj/lD9Vfk= // @require https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js#sha256-7/yoZS3548fXSRXqc/xYzjsmuW3sFKzuvOCHd06Pmps= // @downloadURL none // ==/UserScript== (function () { 'use strict'; // All REST API calls should fail after a timeout, instead of going on forever. $.ajaxSetup({ timeout: 5000 }); // Find out who is our current user. In general, we should avoid using pageData because it doesn't always get updated when moving between page-to-page in AzDO's single-page application flow. Instead, rely on the AzDO REST APIs to get information from stuff you find on the page or the URL. Some things are OK to get from pageData; e.g. stuff like the user which is available on all pages. const pageData = JSON.parse(document.getElementById('dataProviders').innerHTML).data; const currentUser = pageData['ms.vss-web.page-data'].user; // Because of CORS, we need to make sure we're querying the same hostname for our AzDO APIs. const azdoApiBaseUrl = `${window.location.origin}${pageData['ms.vss-tfs-web.header-action-data'].suiteHomeUrl}`; // Set a namespace for our local storage items. lscache.setBucket('acb-azdo/'); // Call our event handler if we notice new elements being inserted into the DOM. This happens as the page is loading or updating dynamically based on user activity. We throttle new element events to avoid using up CPU when AzDO is adding a lot of elements during a short time (like on page load). document.addEventListener('DOMNodeInserted', _.throttle(onPageDOMNodeInserted, 400)); // This is "main()" for this script. Runs periodically when the page updates. function onPageDOMNodeInserted(event) { // The page may not have refreshed when moving between URLs--sometimes AzDO acts as a single-page application. So we must always check where we are and act accordingly. if (/\/(pullrequest)\//i.test(window.location.pathname)) { addCheckboxesToFiles(); addBaseUpdateSelector(); makePullRequestDiffEasierToScroll(); applyStickyPullRequestComments(); addAccessKeysToPullRequestTabs(); if (/\/DevCentral\/_git\/ASW\//i.test(window.location.pathname)) { addNICodeOfDayToggle(); } } else if (/\/(_pulls|pullrequests)/i.test(window.location.pathname)) { sortPullRequestDashboard(); } applyNicerScrollbars(); } function applyStickyPullRequestComments() { // Comments that start with this string become sticky. Only the first comment of the thread counts. const lowerCasePrefix = 'note:'; addStyleOnce('sticky-comments', /* css */ ` .vc-discussion-thread-box .vc-discussion-thread-comment:first-of-type .vc-discussion-thread-renderparent[content^="${lowerCasePrefix}" i] { border: 2px solid var(--palette-black-alpha-20); border-radius: 5px; margin: 7px 0px; padding: 10px 15px; }`); // Expand threads that have the sticky prefix. const lowerCasePrefixCssSelector = CSS.escape(`: "${lowerCasePrefix}`); $('.discussion-thread-host').once('expand-sticky-threads-on-load').each(async function () { await sleep(100); const button = this.querySelector(`button.ms-Button.expand-button[aria-label*="${lowerCasePrefixCssSelector}" i]`); if (button) { button.click(); } }); } function addAccessKeysToPullRequestTabs() { // Give all the tabs an access key equal to their numeric position on screen. $('ul.vc-pullrequest-tabs a').once('add-accesskeys').each(function () { $(this).attr('accesskey', $(this).attr('aria-posinset')); }); } function applyNicerScrollbars() { addStyleOnce('nicer-scrollbars', /* css */ ` ::-webkit-scrollbar { width: 15px; height: 15px; } ::-webkit-scrollbar-track, ::-webkit-scrollbar-corner { background: rgb(var(--palette-neutral-4)); } ::-webkit-scrollbar-thumb { background: rgb(var(--palette-neutral-20)); }`); } function makePullRequestDiffEasierToScroll() { addStyleOnce('pr-diff-improvements', /* css */ ` .vc-change-summary-files .file-container { /* Make the divs float but clear them so they get stacked on top of each other. We float so that the divs expand to take up the width of the text in it. Finally, we remove the overflow property so that they don't have scrollbars and also such that we can have sticky elements (apparently, sticky elements don't work if the div has overflow). */ float: left; clear: both; min-width: 95%; overflow: initial; } .vc-change-summary-files .file-row { /* Let the file name section of each diff stick to the top of the page if we're scrolling. */ position: sticky; top: 0; z-index: 100000; padding-bottom: 10px; background: var(--background-color,rgba(255, 255, 255, 1)); } .vc-change-summary-files .vc-diff-viewer { /* We borrowed padding from the diff to give to the bottom of the file row. So adjust accordingly (this value was originally 20px). */ padding-top: 10px; }`); } // The func we'll call to continuously add checkboxes to the PR file listing, once initialization is over. let addCheckboxesToNewFilesFunc = () => { }; // If we're on specific PR, add checkboxes to the file listing. function addCheckboxesToFiles() { $('.vc-sparse-files-tree').once('add-checkbox-support').each(async function () { addCheckboxesToNewFilesFunc = () => { }; const filesTree = $(this); addStyleOnce('pr-file-checbox-support-css', /* css */ ` :root { /* Set some constants for our CSS. */ --file-to-review-color: var(--communication-foreground); } button.file-complete-checkbox { /* Make a checkbox out of a button. */ cursor: pointer; width: 15px; height: 15px; line-height: 15px; margin: -3px 8px 0px 0px; padding: 0px; background: var(--palette-black-alpha-6); border-radius: 3px; border: 1px solid var(--palette-black-alpha-10); vertical-align: middle; display: inline-block; font-size: 0.75em; text-align: center; color: var(--text-primary-color); } button.file-complete-checkbox:hover { /* Make a checkbox out of a button. */ background: var(--palette-black-alpha-10); } button.file-complete-checkbox.checked:after { /* Make a checkbox out of a button. */ content: "✔"; } .vc-sparse-files-tree .tree-row.file-to-review-row, .vc-sparse-files-tree .tree-row.file-to-review-row .file-name { /* Highlight files I need to review. */ color: var(--file-to-review-color); } .vc-sparse-files-tree .tree-row.file-to-review-row .file-owners-role { /* Style the role of the user in the files table. */ font-weight: bold; padding: 7px 10px; position: absolute; z-index: 100; float: right; } .file-to-review-diff { /* Highlight files I need to review. */ border-left: 3px solid var(--file-to-review-color) !important; padding-left: 7px; } .files-container.hide-files-not-to-review .file-container:not(.file-to-review-diff) { /* Fade the header for files I don't have to review. */ opacity: 0.2; } .files-container.hide-files-not-to-review .file-container:not(.file-to-review-diff) .item-details-body { /* Hide the diff for files I don't have to review. */ display: none; }`); // Get the current iteration of the PR. const prUrl = await getCurrentPullRequestUrlAsync(); const currentPullRequestIteration = (await $.get(`${prUrl}/iterations?api-version=5.0`)).count; // Get the current checkbox state for the PR at this URL. const checkboxStateId = `pr-file-iteration6/${window.location.pathname}`; // Stores the checkbox state for the current page. A map of files => iteration it was checked. const filesToIterationReviewed = lscache.get(checkboxStateId) || {}; // Handle clicking on file checkboxes. filesTree.on('click', 'button.file-complete-checkbox', function (event) { const checkbox = $(this); // Toggle the look of the checkbox. checkbox.toggleClass('checked'); // Save the iteration number the file was checked in our map. To save space, if it is unchecked, simply remove the entry. if (checkbox.hasClass('checked')) { filesToIterationReviewed[checkbox.attr('name')] = currentPullRequestIteration; } else { delete filesToIterationReviewed[checkbox.attr('name')]; } // Save the current checkbox state to local storage. lscache.set(checkboxStateId, filesToIterationReviewed, 60 * 24 * 21); // Stop the click event here to avoid the checkbox click from selecting the PR row underneath, which changes the active diff in the right panel. event.stopPropagation(); }); // Get owners info for this PR. const ownersInfo = await getNationalInstrumentsPullRequestOwnersInfo(prUrl); // If we have owners info, add a button to filter out diffs that we don't need to review. if (ownersInfo && ownersInfo.currentUserFileCount > 0) { $('.changed-files-summary-toolbar').once('add-other-files-button').each(function () { $(this) .find('ul') .prepend('') .click(event => { $('.files-container').toggleClass('hide-files-not-to-review'); }); }); } addCheckboxesToNewFilesFunc = function () { // If we have owners info, tag the diffs that we don't need to review. if (ownersInfo && ownersInfo.currentUserFileCount > 0) { $('.file-container .file-path').once('filter-files-to-review').each(function () { const filePathElement = $(this); const path = filePathElement.text().replace(/\//, ''); filePathElement.closest('.file-container').toggleClass('file-to-review-diff', ownersInfo.isCurrentUserResponsibleForFile(path)); }); } $('.vc-sparse-files-tree .vc-tree-cell').once('add-complete-checkbox').each(function () { const fileCell = $(this); const fileRow = fileCell.closest('.tree-row'); const typeIcon = fileRow.find('.type-icon'); // Don't put checkboxes on rows that don't represent files. if (!/bowtie-file\b/i.test(typeIcon.attr('class'))) { return; } const name = fileCell.attr('content'); // The 'content' attribute contains the file operation; e.g. "/src/file.cs [edit]". const iteration = filesToIterationReviewed[name] || 0; // Create the checkbox before the type icon. $(''); updateButtonForCurrentState(button, isFlagged); button.prependTo(this); button.click(async function (event) { const isNowFlagged = await toggleThreadFlaggedForNICodeOfTheDay(await getCurrentPullRequestUrlAsync(), { flaggedDate: new Date().toISOString(), flaggedBy: currentUser.uniqueName, pullRequestId: getCurrentPullRequestId(), threadId: thread.id, file: thread.itemPath, threadAuthor: thread.comments[0].author.displayName, threadContentShort: truncate(thread.comments[0].content || thread.comments[0].newContent, 100), }); // Update the button visuals in this thread updateButtonForCurrentState($(this).parents('.vc-discussion-comments').find('.cod-toggle'), isNowFlagged); }); }); } // The func we'll call to continuously sort new PRs into categories, once initialization is over. let sortEachPullRequestFunc = () => { }; // If we're on a pull request page, attempt to sort it. function sortPullRequestDashboard() { // Find the reviews section for this user. Note the two selectors: 1) a repo dashboard; 2) the overall dashboard (e.g. https://dev.azure.com/*/_pulls). $("[aria-label='Assigned to me'][role='region'], .ms-GroupedList-group:has([aria-label*='Assigned to me'])").once('reviews-sorted').each(function () { sortEachPullRequestFunc = () => { }; const personalReviewSection = $(this); addStyleOnce('reviews-list-css', /* css */ ` details.reviews-list { margin: 10px 30px; display: none; } details.reviews-list summary { padding: 10px; cursor: pointer; color: var(--text-secondary-color); } details.reviews-list > div.flex-container { display: flex; flex-direction: column-reverse; }`); // Disable the expanding button if we are on the overall PR dashboard. If enabled and the user hides/shows this section, it causes the AzDO page to re-add all the PRs, leading to duplicates in the sorted list. personalReviewSection.find('button.ms-GroupHeader-expand').prop('disabled', true).attr('title', 'AzDO Pull Request Improvements userscript disabled this button.'); // Define what it means to be a notable PR after you have approved it. const peopleToNotApproveToCountAsNotableThread = 2; const commentsToCountAsNotableThread = 4; const wordsToCountAsNotableThread = 300; const notableUpdateDescription = `These are pull requests you've already approved, but since then, any of following events have happened: 1) At least ${peopleToNotApproveToCountAsNotableThread} people voted Rejected or Waiting on Author 2) A thread was posted with at least ${commentsToCountAsNotableThread} comments 3) A thread was posted with at least ${wordsToCountAsNotableThread} words Optional: To remove PRs from this list, simply vote again on the PR (even if it's the same vote).`; // Create review sections with counters. const sections = { blocking: $("
Blocking
"), pending: $("
Incomplete
"), blocked: $("
Incomplete but blocked
"), approvedButNotable: $(`
Completed as Approved / Approved with Suggestions (with notable activity)
`), drafts: $("
Drafts
"), waiting: $("
Completed as Waiting on Author
"), rejected: $("
Completed as Rejected
"), approved: $("
Completed as Approved / Approved with Suggestions
"), }; // Load the subsection open/closed setting if it exists and setup a change handler to save the setting. We also add common elements to each sections. for (const section of Object.values(sections)) { const id = `pr-section-open/${section.attr('class')}`; section.children('summary').append(" (0)"); section.append("
"); section.prop('open', lscache.get(id)); section.on('toggle', function () { lscache.set(id, $(this).prop('open')); }); section.appendTo(personalReviewSection); } // Loop through the PRs that we've voted on. sortEachPullRequestFunc = () => $(personalReviewSection).find('[role="list"] [role="listitem"]').once('pr-sorted').each(async function () { const row = $(this); // Loop until AzDO has added the link to the PR into the row. let pullRequestHref; while (!pullRequestHref) { // Important! Do not remove this sleep, even on the first iteration. We need to give AzDO some time to finish making the row before moving it. If we don't sleep for some time, and we begin moving rows, AzDO may get confused and not create all the PR rows. That would cause some PRs to not be rendered in the list. The best solution is to wait until the list finishes to render via an event handler; except that I don't know how to hook into that without understanding AzDO JS infrastructure. The sleep time was chosen to balance first load time (don't wait too long before sorting) and what appears to be long enough to avoid the missing PR problem when sorting a 50+ PR dashboard, as determined by experimentation (refreshing the page a dozen or so times). // eslint-disable-next-line no-await-in-loop await sleep(300); pullRequestHref = row.find("a[href*='/pullrequest/']").attr('href'); } try { // Hide the row while we are updating it. row.hide(150); // Get the PR id. const pullRequestUrl = new URL(pullRequestHref, window.location.origin); const pullRequestId = parseInt(pullRequestUrl.pathname.substring(pullRequestUrl.pathname.lastIndexOf('/') + 1), 10); // Get complete information about the PR. const pr = await getPullRequestAsync(pullRequestId); // Get non-deleted pr threads, ordered from newest to oldest. const prThreads = (await $.get(`${pr.url}/threads?api-version=5.0`)).value.filter(x => !x.isDeleted).reverse(); let userAddedTimestamp = getReviewerAddedOrResetTimestamp(prThreads, currentUser.uniqueName); if (!userAddedTimestamp) { userAddedTimestamp = pr.creationDate; } // Order the reviews by when the current user was added (reviews that the user was added to most recently are listed last). We do this by ordering the rows inside a reversed-order flex container. // The order property is a 32-bit integer. If treat it as number of seconds, that allows a range of 68 years (2147483647 / (60 * 60 * 24 * 365)) in the positive values alone. // Dates values are number of milliseconds since 1970, so we wouldn't overflow until 2038. Still, we might as well subtract a more recent reference date, i.e. 2019. const secondsSince2019 = Math.trunc((Date.parse(userAddedTimestamp) - Date.parse('2019-01-01')) / 1000); row.css('order', secondsSince2019); let missingVotes = 0; let waitingOrRejectedVotes = 0; let userVote = 0; // Count the number of votes. for (const reviewer of pr.reviewers) { if (reviewer.uniqueName === currentUser.uniqueName) { userVote = reviewer.vote; } if (reviewer.vote === 0) { missingVotes += 1; } else if (reviewer.vote < 0) { waitingOrRejectedVotes += 1; } } // See what section this PR should be filed under and style the row, if necessary. let section; let computeSize = false; if (pr.isDraft) { section = sections.drafts; computeSize = true; } else if (userVote === -5) { section = sections.waiting; } else if (userVote < 0) { section = sections.rejected; } else if (userVote > 0) { section = prHadNotableActivitySinceCurrentUserVoted(prThreads, peopleToNotApproveToCountAsNotableThread, commentsToCountAsNotableThread, wordsToCountAsNotableThread) ? sections.approvedButNotable : sections.approved; } else { computeSize = true; if (waitingOrRejectedVotes > 0) { section = sections.blocked; } else if (missingVotes === 1) { section = sections.blocking; } else { section = sections.pending; } } // Compute the size of certain PRs; e.g. those we haven't reviewed yet. But first, sure we've created a merge commit that we can compute its size. if (computeSize && pr.lastMergeCommit) { let fileCount = 0; // See if this PR has owners info and count the files listed for the current user. const ownersInfo = await getNationalInstrumentsPullRequestOwnersInfo(pr.url); if (ownersInfo) { fileCount = ownersInfo.currentUserFileCount; } // If there is no owner info or if it returns zero files to review (since we may not be on the review explicitly), then count the number of files in the merge commit. if (fileCount === 0) { const mergeCommitInfo = await $.get(`${pr.lastMergeCommit.url}/changes?api-version=5.0`); fileCount = _(mergeCommitInfo.changes).filter(item => !item.item.isFolder).size(); } const fileCountContent = ` ${fileCount}`; // Add the file count on the overall PR dashboard. row.find('div.vss-DetailsList--titleCellTwoLine').parent() .append(`
${fileCountContent}
`); // Add the file count on a repo's PR dashboard. row.find('div.vc-pullrequest-entry-col-secondary') .after(`
${fileCountContent}
`); } // If we identified a section, move the row. if (section) { section.find('.review-subsection-counter').text((i, value) => +value + 1); section.children('div.flex-container').append(row); section.show(); } } finally { // No matter what--e.g. even on error--show the row again. row.show(150); } }); }); sortEachPullRequestFunc(); } function getReviewerAddedOrResetTimestamp(prThreadsNewestFirst, reviewerUniqueName) { for (const thread of prThreadsNewestFirst) { if (thread.properties) { if (Object.prototype.hasOwnProperty.call(thread.properties, 'CodeReviewReviewersUpdatedAddedIdentity')) { const addedReviewer = thread.identities[thread.properties.CodeReviewReviewersUpdatedAddedIdentity.$value]; if (addedReviewer.uniqueName === reviewerUniqueName) { return thread.publishedDate; } } else if (Object.prototype.hasOwnProperty.call(thread.properties, 'CodeReviewResetMultipleVotesExampleVoterIdentities')) { if (Object.keys(thread.identities).filter(x => thread.identities[x].uniqueName === reviewerUniqueName)) { return thread.publishedDate; } } } } return null; } function prHadNotableActivitySinceCurrentUserVoted(prThreadsNewestFirst, newNonApprovingVoteLimit, newThreadCommentCountLimit, newThreadWordCountLimit) { let newNonApprovedVotes = 0; for (const thread of prThreadsNewestFirst) { // See if this thread represents a non-approved vote. if (thread.properties && Object.prototype.hasOwnProperty.call(thread.properties, 'CodeReviewThreadType')) { if (thread.properties.CodeReviewThreadType.$value === 'VoteUpdate') { // Stop looking at threads once we find the thread that represents our vote. const votingUser = thread.identities[thread.properties.CodeReviewVotedByIdentity.$value]; if (votingUser.uniqueName === currentUser.uniqueName) { break; } if (thread.properties.CodeReviewVoteResult.$value < 0) { newNonApprovedVotes += 1; if (newNonApprovedVotes >= newNonApprovingVoteLimit) { return true; } } } } // Count the number of comments and words in the thread. let wordCount = 0; let commentCount = 0; for (const comment of thread.comments) { if (comment.commentType !== 'system' && !comment.isDeleted && comment.content) { commentCount += 1; wordCount += comment.content.trim().split(/\s+/).length; } } if (commentCount >= newThreadCommentCountLimit || wordCount >= newThreadWordCountLimit) { return true; } } return false; } // Helper function to avoid adding CSS twice into a document. function addStyleOnce(id, style) { $(document.head).once(id).each(function () { $('