diff options
Diffstat (limited to 'app')
156 files changed, 2937 insertions, 2602 deletions
diff --git a/app/assets/javascripts/awards_handler.js b/app/assets/javascripts/awards_handler.js index adb45b0606d..ebe722061d7 100644 --- a/app/assets/javascripts/awards_handler.js +++ b/app/assets/javascripts/awards_handler.js @@ -1,3 +1,4 @@ +/* eslint-disable class-methods-use-this */ /* global Flash */ import Cookies from 'js-cookie'; @@ -68,141 +69,140 @@ function renderCategory(name, emojiList, opts = {}) { `; } -function AwardsHandler() { - this.eventListeners = []; - this.aliases = emojiAliases; - // If the user shows intent let's pre-build the menu - this.registerEventListener('one', $(document), 'mouseenter focus', '.js-add-award', 'mouseenter focus', () => { - const $menu = $('.emoji-menu'); - if ($menu.length === 0) { - requestAnimationFrame(() => { - this.createEmojiMenu(); - }); - } - // Prebuild the categoryMap - categoryMap = categoryMap || buildCategoryMap(); - }); - this.registerEventListener('on', $(document), 'click', '.js-add-award', (e) => { - e.stopPropagation(); - e.preventDefault(); - this.showEmojiMenu($(e.currentTarget)); - }); +export default class AwardsHandler { + constructor() { + this.eventListeners = []; + this.aliases = emojiAliases; + // If the user shows intent let's pre-build the menu + this.registerEventListener('one', $(document), 'mouseenter focus', '.js-add-award', 'mouseenter focus', () => { + const $menu = $('.emoji-menu'); + if ($menu.length === 0) { + requestAnimationFrame(() => { + this.createEmojiMenu(); + }); + } + // Prebuild the categoryMap + categoryMap = categoryMap || buildCategoryMap(); + }); + this.registerEventListener('on', $(document), 'click', '.js-add-award', (e) => { + e.stopPropagation(); + e.preventDefault(); + this.showEmojiMenu($(e.currentTarget)); + }); - this.registerEventListener('on', $('html'), 'click', (e) => { - const $target = $(e.target); - if (!$target.closest('.emoji-menu-content').length) { - $('.js-awards-block.current').removeClass('current'); - } - if (!$target.closest('.emoji-menu').length) { - if ($('.emoji-menu').is(':visible')) { - $('.js-add-award.is-active').removeClass('is-active'); - $('.emoji-menu').removeClass('is-visible'); + this.registerEventListener('on', $('html'), 'click', (e) => { + const $target = $(e.target); + if (!$target.closest('.emoji-menu-content').length) { + $('.js-awards-block.current').removeClass('current'); } - } - }); - this.registerEventListener('on', $(document), 'click', '.js-emoji-btn', (e) => { - e.preventDefault(); - const $target = $(e.currentTarget); - const $glEmojiElement = $target.find('gl-emoji'); - const $spriteIconElement = $target.find('.icon'); - const emoji = ($glEmojiElement.length ? $glEmojiElement : $spriteIconElement).data('name'); - - $target.closest('.js-awards-block').addClass('current'); - this.addAward(this.getVotesBlock(), this.getAwardUrl(), emoji); - }); -} + if (!$target.closest('.emoji-menu').length) { + if ($('.emoji-menu').is(':visible')) { + $('.js-add-award.is-active').removeClass('is-active'); + $('.emoji-menu').removeClass('is-visible'); + } + } + }); + this.registerEventListener('on', $(document), 'click', '.js-emoji-btn', (e) => { + e.preventDefault(); + const $target = $(e.currentTarget); + const $glEmojiElement = $target.find('gl-emoji'); + const $spriteIconElement = $target.find('.icon'); + const emoji = ($glEmojiElement.length ? $glEmojiElement : $spriteIconElement).data('name'); + + $target.closest('.js-awards-block').addClass('current'); + this.addAward(this.getVotesBlock(), this.getAwardUrl(), emoji); + }); + } -AwardsHandler.prototype.registerEventListener = function registerEventListener(method = 'on', element, ...args) { - element[method].call(element, ...args); - this.eventListeners.push({ - element, - args, - }); -}; + registerEventListener(method = 'on', element, ...args) { + element[method].call(element, ...args); + this.eventListeners.push({ + element, + args, + }); + } -AwardsHandler.prototype.showEmojiMenu = function showEmojiMenu($addBtn) { - if ($addBtn.hasClass('js-note-emoji')) { - $addBtn.closest('.note').find('.js-awards-block').addClass('current'); - } else { - $addBtn.closest('.js-awards-block').addClass('current'); - } - - const $menu = $('.emoji-menu'); - const $thumbsBtn = $menu.find('[data-name="thumbsup"], [data-name="thumbsdown"]').parent(); - const $userAuthored = this.isUserAuthored($addBtn); - if ($menu.length) { - if ($menu.is('.is-visible')) { - $addBtn.removeClass('is-active'); - $menu.removeClass('is-visible'); - $('.js-emoji-menu-search').blur(); + showEmojiMenu($addBtn) { + if ($addBtn.hasClass('js-note-emoji')) { + $addBtn.closest('.note').find('.js-awards-block').addClass('current'); } else { - $addBtn.addClass('is-active'); - this.positionMenu($menu, $addBtn); - $menu.addClass('is-visible'); - $('.js-emoji-menu-search').focus(); + $addBtn.closest('.js-awards-block').addClass('current'); } - } else { - $addBtn.addClass('is-loading is-active'); - this.createEmojiMenu(() => { - const $createdMenu = $('.emoji-menu'); - $addBtn.removeClass('is-loading'); - this.positionMenu($createdMenu, $addBtn); - return setTimeout(() => { - $createdMenu.addClass('is-visible'); + + const $menu = $('.emoji-menu'); + const $thumbsBtn = $menu.find('[data-name="thumbsup"], [data-name="thumbsdown"]').parent(); + const $userAuthored = this.isUserAuthored($addBtn); + if ($menu.length) { + if ($menu.is('.is-visible')) { + $addBtn.removeClass('is-active'); + $menu.removeClass('is-visible'); + $('.js-emoji-menu-search').blur(); + } else { + $addBtn.addClass('is-active'); + this.positionMenu($menu, $addBtn); + $menu.addClass('is-visible'); $('.js-emoji-menu-search').focus(); - }, 200); - }); + } + } else { + $addBtn.addClass('is-loading is-active'); + this.createEmojiMenu(() => { + const $createdMenu = $('.emoji-menu'); + $addBtn.removeClass('is-loading'); + this.positionMenu($createdMenu, $addBtn); + return setTimeout(() => { + $createdMenu.addClass('is-visible'); + $('.js-emoji-menu-search').focus(); + }, 200); + }); + } + + $thumbsBtn.toggleClass('disabled', $userAuthored); } - $thumbsBtn.toggleClass('disabled', $userAuthored); -}; + // Create the emoji menu with the first category of emojis. + // Then render the remaining categories of emojis one by one to avoid jank. + createEmojiMenu(callback) { + if (this.isCreatingEmojiMenu) { + return; + } + this.isCreatingEmojiMenu = true; -// Create the emoji menu with the first category of emojis. -// Then render the remaining categories of emojis one by one to avoid jank. -AwardsHandler.prototype.createEmojiMenu = function createEmojiMenu(callback) { - if (this.isCreatingEmojiMenu) { - return; - } - this.isCreatingEmojiMenu = true; - - // Render the first category - categoryMap = categoryMap || buildCategoryMap(); - const categoryNameKey = Object.keys(categoryMap)[0]; - const emojisInCategory = categoryMap[categoryNameKey]; - const firstCategory = renderCategory(categoryLabelMap[categoryNameKey], emojisInCategory); - - // Render the frequently used - const frequentlyUsedEmojis = this.getFrequentlyUsedEmojis(); - let frequentlyUsedCatgegory = ''; - if (frequentlyUsedEmojis.length > 0) { - frequentlyUsedCatgegory = renderCategory('Frequently used', frequentlyUsedEmojis, { - menuListClass: 'frequent-emojis', - }); - } + // Render the first category + categoryMap = categoryMap || buildCategoryMap(); + const categoryNameKey = Object.keys(categoryMap)[0]; + const emojisInCategory = categoryMap[categoryNameKey]; + const firstCategory = renderCategory(categoryLabelMap[categoryNameKey], emojisInCategory); + + // Render the frequently used + const frequentlyUsedEmojis = this.getFrequentlyUsedEmojis(); + let frequentlyUsedCatgegory = ''; + if (frequentlyUsedEmojis.length > 0) { + frequentlyUsedCatgegory = renderCategory('Frequently used', frequentlyUsedEmojis, { + menuListClass: 'frequent-emojis', + }); + } - const emojiMenuMarkup = ` - <div class="emoji-menu"> - <input type="text" name="emoji-menu-search" value="" class="js-emoji-menu-search emoji-search search-input form-control" placeholder="Search emoji" /> + const emojiMenuMarkup = ` + <div class="emoji-menu"> + <input type="text" name="emoji-menu-search" value="" class="js-emoji-menu-search emoji-search search-input form-control" placeholder="Search emoji" /> - <div class="emoji-menu-content"> - ${frequentlyUsedCatgegory} - ${firstCategory} + <div class="emoji-menu-content"> + ${frequentlyUsedCatgegory} + ${firstCategory} + </div> </div> - </div> - `; + `; - document.body.insertAdjacentHTML('beforeend', emojiMenuMarkup); + document.body.insertAdjacentHTML('beforeend', emojiMenuMarkup); - this.addRemainingEmojiMenuCategories(); - this.setupSearch(); - if (callback) { - callback(); + this.addRemainingEmojiMenuCategories(); + this.setupSearch(); + if (callback) { + callback(); + } } -}; -AwardsHandler - .prototype - .addRemainingEmojiMenuCategories = function addRemainingEmojiMenuCategories() { + addRemainingEmojiMenuCategories() { if (this.isAddingRemainingEmojiMenuCategories) { return; } @@ -243,176 +243,174 @@ AwardsHandler emojiContentElement.insertAdjacentHTML('beforeend', '<p>We encountered an error while adding the remaining categories</p>'); throw new Error(`Error occurred in addRemainingEmojiMenuCategories: ${err.message}`); }); - }; - -AwardsHandler.prototype.positionMenu = function positionMenu($menu, $addBtn) { - const position = $addBtn.data('position'); - // The menu could potentially be off-screen or in a hidden overflow element - // So we position the element absolute in the body - const css = { - top: `${$addBtn.offset().top + $addBtn.outerHeight()}px`, - }; - if (position === 'right') { - css.left = `${($addBtn.offset().left - $menu.outerWidth()) + 20}px`; - $menu.addClass('is-aligned-right'); - } else { - css.left = `${$addBtn.offset().left}px`; - $menu.removeClass('is-aligned-right'); - } - return $menu.css(css); -}; - -AwardsHandler.prototype.addAward = function addAward( - votesBlock, - awardUrl, - emoji, - checkMutuality, - callback, -) { - const normalizedEmoji = this.normalizeEmojiName(emoji); - const $emojiButton = this.findEmojiIcon(votesBlock, normalizedEmoji).parent(); - this.postEmoji($emojiButton, awardUrl, normalizedEmoji, () => { - this.addAwardToEmojiBar(votesBlock, normalizedEmoji, checkMutuality); - return typeof callback === 'function' ? callback() : undefined; - }); - $('.emoji-menu').removeClass('is-visible'); - $('.js-add-award.is-active').removeClass('is-active'); -}; + } -AwardsHandler.prototype.addAwardToEmojiBar = function addAwardToEmojiBar( - votesBlock, - emoji, - checkForMutuality, -) { - if (checkForMutuality || checkForMutuality === null) { - this.checkMutuality(votesBlock, emoji); - } - this.addEmojiToFrequentlyUsedList(emoji); - const normalizedEmoji = this.normalizeEmojiName(emoji); - const $emojiButton = this.findEmojiIcon(votesBlock, normalizedEmoji).parent(); - if ($emojiButton.length > 0) { - if (this.isActive($emojiButton)) { - this.decrementCounter($emojiButton, normalizedEmoji); + positionMenu($menu, $addBtn) { + const position = $addBtn.data('position'); + // The menu could potentially be off-screen or in a hidden overflow element + // So we position the element absolute in the body + const css = { + top: `${$addBtn.offset().top + $addBtn.outerHeight()}px`, + }; + if (position === 'right') { + css.left = `${($addBtn.offset().left - $menu.outerWidth()) + 20}px`; + $menu.addClass('is-aligned-right'); } else { - const counter = $emojiButton.find('.js-counter'); - counter.text(parseInt(counter.text(), 10) + 1); - $emojiButton.addClass('active'); - this.addYouToUserList(votesBlock, normalizedEmoji); - this.animateEmoji($emojiButton); + css.left = `${$addBtn.offset().left}px`; + $menu.removeClass('is-aligned-right'); } - } else { - votesBlock.removeClass('hidden'); - this.createEmoji(votesBlock, normalizedEmoji); + return $menu.css(css); } -}; -AwardsHandler.prototype.getVotesBlock = function getVotesBlock() { - const currentBlock = $('.js-awards-block.current'); - let resultantVotesBlock = currentBlock; - if (currentBlock.length === 0) { - resultantVotesBlock = $('.js-awards-block').eq(0); + addAward( + votesBlock, + awardUrl, + emoji, + checkMutuality, + callback, + ) { + const normalizedEmoji = this.normalizeEmojiName(emoji); + const $emojiButton = this.findEmojiIcon(votesBlock, normalizedEmoji).parent(); + this.postEmoji($emojiButton, awardUrl, normalizedEmoji, () => { + this.addAwardToEmojiBar(votesBlock, normalizedEmoji, checkMutuality); + return typeof callback === 'function' ? callback() : undefined; + }); + $('.emoji-menu').removeClass('is-visible'); + $('.js-add-award.is-active').removeClass('is-active'); } - return resultantVotesBlock; -}; + addAwardToEmojiBar( + votesBlock, + emoji, + checkForMutuality, + ) { + if (checkForMutuality || checkForMutuality === null) { + this.checkMutuality(votesBlock, emoji); + } + this.addEmojiToFrequentlyUsedList(emoji); + const normalizedEmoji = this.normalizeEmojiName(emoji); + const $emojiButton = this.findEmojiIcon(votesBlock, normalizedEmoji).parent(); + if ($emojiButton.length > 0) { + if (this.isActive($emojiButton)) { + this.decrementCounter($emojiButton, normalizedEmoji); + } else { + const counter = $emojiButton.find('.js-counter'); + counter.text(parseInt(counter.text(), 10) + 1); + $emojiButton.addClass('active'); + this.addYouToUserList(votesBlock, normalizedEmoji); + this.animateEmoji($emojiButton); + } + } else { + votesBlock.removeClass('hidden'); + this.createEmoji(votesBlock, normalizedEmoji); + } + } -AwardsHandler.prototype.getAwardUrl = function getAwardUrl() { - return this.getVotesBlock().data('award-url'); -}; + getVotesBlock() { + const currentBlock = $('.js-awards-block.current'); + let resultantVotesBlock = currentBlock; + if (currentBlock.length === 0) { + resultantVotesBlock = $('.js-awards-block').eq(0); + } + + return resultantVotesBlock; + } -AwardsHandler.prototype.checkMutuality = function checkMutuality(votesBlock, emoji) { - const awardUrl = this.getAwardUrl(); - if (emoji === 'thumbsup' || emoji === 'thumbsdown') { - const mutualVote = emoji === 'thumbsup' ? 'thumbsdown' : 'thumbsup'; - const $emojiButton = votesBlock.find(`[data-name="${mutualVote}"]`).parent(); - const isAlreadyVoted = $emojiButton.hasClass('active'); - if (isAlreadyVoted) { - this.addAward(votesBlock, awardUrl, mutualVote, false); + getAwardUrl() { + return this.getVotesBlock().data('award-url'); + } + + checkMutuality(votesBlock, emoji) { + const awardUrl = this.getAwardUrl(); + if (emoji === 'thumbsup' || emoji === 'thumbsdown') { + const mutualVote = emoji === 'thumbsup' ? 'thumbsdown' : 'thumbsup'; + const $emojiButton = votesBlock.find(`[data-name="${mutualVote}"]`).parent(); + const isAlreadyVoted = $emojiButton.hasClass('active'); + if (isAlreadyVoted) { + this.addAward(votesBlock, awardUrl, mutualVote, false); + } } } -}; -AwardsHandler.prototype.isActive = function isActive($emojiButton) { - return $emojiButton.hasClass('active'); -}; + isActive($emojiButton) { + return $emojiButton.hasClass('active'); + } -AwardsHandler.prototype.isUserAuthored = function isUserAuthored($button) { - return $button.hasClass('js-user-authored'); -}; + isUserAuthored($button) { + return $button.hasClass('js-user-authored'); + } -AwardsHandler.prototype.decrementCounter = function decrementCounter($emojiButton, emoji) { - const counter = $('.js-counter', $emojiButton); - const counterNumber = parseInt(counter.text(), 10); - if (counterNumber > 1) { - counter.text(counterNumber - 1); - this.removeYouFromUserList($emojiButton); - } else if (emoji === 'thumbsup' || emoji === 'thumbsdown') { - $emojiButton.tooltip('destroy'); - counter.text('0'); - this.removeYouFromUserList($emojiButton); - if ($emojiButton.parents('.note').length) { + decrementCounter($emojiButton, emoji) { + const counter = $('.js-counter', $emojiButton); + const counterNumber = parseInt(counter.text(), 10); + if (counterNumber > 1) { + counter.text(counterNumber - 1); + this.removeYouFromUserList($emojiButton); + } else if (emoji === 'thumbsup' || emoji === 'thumbsdown') { + $emojiButton.tooltip('destroy'); + counter.text('0'); + this.removeYouFromUserList($emojiButton); + if ($emojiButton.parents('.note').length) { + this.removeEmoji($emojiButton); + } + } else { this.removeEmoji($emojiButton); } - } else { - this.removeEmoji($emojiButton); + return $emojiButton.removeClass('active'); } - return $emojiButton.removeClass('active'); -}; -AwardsHandler.prototype.removeEmoji = function removeEmoji($emojiButton) { - $emojiButton.tooltip('destroy'); - $emojiButton.remove(); - const $votesBlock = this.getVotesBlock(); - if ($votesBlock.find('.js-emoji-btn').length === 0) { - $votesBlock.addClass('hidden'); + removeEmoji($emojiButton) { + $emojiButton.tooltip('destroy'); + $emojiButton.remove(); + const $votesBlock = this.getVotesBlock(); + if ($votesBlock.find('.js-emoji-btn').length === 0) { + $votesBlock.addClass('hidden'); + } } -}; - -AwardsHandler.prototype.getAwardTooltip = function getAwardTooltip($awardBlock) { - return $awardBlock.attr('data-original-title') || $awardBlock.attr('data-title') || ''; -}; -AwardsHandler.prototype.toSentence = function toSentence(list) { - let sentence; - if (list.length <= 2) { - sentence = list.join(' and '); - } else { - sentence = `${list.slice(0, -1).join(', ')}, and ${list[list.length - 1]}`; + getAwardTooltip($awardBlock) { + return $awardBlock.attr('data-original-title') || $awardBlock.attr('data-title') || ''; } - return sentence; -}; + toSentence(list) { + let sentence; + if (list.length <= 2) { + sentence = list.join(' and '); + } else { + sentence = `${list.slice(0, -1).join(', ')}, and ${list[list.length - 1]}`; + } -AwardsHandler.prototype.removeYouFromUserList = function removeYouFromUserList($emojiButton) { - const awardBlock = $emojiButton; - const originalTitle = this.getAwardTooltip(awardBlock); - const authors = originalTitle.split(FROM_SENTENCE_REGEX); - authors.splice(authors.indexOf('You'), 1); - return awardBlock - .closest('.js-emoji-btn') - .removeData('title') - .removeAttr('data-title') - .removeAttr('data-original-title') - .attr('title', this.toSentence(authors)) - .tooltip('fixTitle'); -}; + return sentence; + } -AwardsHandler.prototype.addYouToUserList = function addYouToUserList(votesBlock, emoji) { - const awardBlock = this.findEmojiIcon(votesBlock, emoji).parent(); - const origTitle = this.getAwardTooltip(awardBlock); - let users = []; - if (origTitle) { - users = origTitle.trim().split(FROM_SENTENCE_REGEX); - } - users.unshift('You'); - return awardBlock - .attr('title', this.toSentence(users)) - .tooltip('fixTitle'); -}; + removeYouFromUserList($emojiButton) { + const awardBlock = $emojiButton; + const originalTitle = this.getAwardTooltip(awardBlock); + const authors = originalTitle.split(FROM_SENTENCE_REGEX); + authors.splice(authors.indexOf('You'), 1); + return awardBlock + .closest('.js-emoji-btn') + .removeData('title') + .removeAttr('data-title') + .removeAttr('data-original-title') + .attr('title', this.toSentence(authors)) + .tooltip('fixTitle'); + } + + addYouToUserList(votesBlock, emoji) { + const awardBlock = this.findEmojiIcon(votesBlock, emoji).parent(); + const origTitle = this.getAwardTooltip(awardBlock); + let users = []; + if (origTitle) { + users = origTitle.trim().split(FROM_SENTENCE_REGEX); + } + users.unshift('You'); + return awardBlock + .attr('title', this.toSentence(users)) + .tooltip('fixTitle'); + } -AwardsHandler - .prototype - .createAwardButtonForVotesBlock = function createAwardButtonForVotesBlock(votesBlock, emojiName) { + createAwardButtonForVotesBlock(votesBlock, emojiName) { const buttonHtml = ` <button class="btn award-control js-emoji-btn has-tooltip active" title="You" data-placement="bottom"> ${glEmojiTag(emojiName)} @@ -424,144 +422,141 @@ AwardsHandler this.animateEmoji($emojiButton); $('.award-control').tooltip(); votesBlock.removeClass('current'); - }; + } -AwardsHandler.prototype.animateEmoji = function animateEmoji($emoji) { - const className = 'pulse animated once short'; - $emoji.addClass(className); + animateEmoji($emoji) { + const className = 'pulse animated once short'; + $emoji.addClass(className); - this.registerEventListener('on', $emoji, animationEndEventString, (e) => { - $(e.currentTarget).removeClass(className); - }); -}; + this.registerEventListener('on', $emoji, animationEndEventString, (e) => { + $(e.currentTarget).removeClass(className); + }); + } -AwardsHandler.prototype.createEmoji = function createEmoji(votesBlock, emoji) { - if ($('.emoji-menu').length) { - this.createAwardButtonForVotesBlock(votesBlock, emoji); + createEmoji(votesBlock, emoji) { + if ($('.emoji-menu').length) { + this.createAwardButtonForVotesBlock(votesBlock, emoji); + } + this.createEmojiMenu(() => { + this.createAwardButtonForVotesBlock(votesBlock, emoji); + }); } - this.createEmojiMenu(() => { - this.createAwardButtonForVotesBlock(votesBlock, emoji); - }); -}; -AwardsHandler.prototype.postEmoji = function postEmoji($emojiButton, awardUrl, emoji, callback) { - if (this.isUserAuthored($emojiButton)) { - this.userAuthored($emojiButton); - } else { - $.post(awardUrl, { - name: emoji, - }, (data) => { - if (data.ok) { - callback(); - } - }).fail(() => new Flash('Something went wrong on our end.')); + postEmoji($emojiButton, awardUrl, emoji, callback) { + if (this.isUserAuthored($emojiButton)) { + this.userAuthored($emojiButton); + } else { + $.post(awardUrl, { + name: emoji, + }, (data) => { + if (data.ok) { + callback(); + } + }).fail(() => new Flash('Something went wrong on our end.')); + } } -}; -AwardsHandler.prototype.findEmojiIcon = function findEmojiIcon(votesBlock, emoji) { - return votesBlock.find(`.js-emoji-btn [data-name="${emoji}"]`); -}; + findEmojiIcon(votesBlock, emoji) { + return votesBlock.find(`.js-emoji-btn [data-name="${emoji}"]`); + } -AwardsHandler.prototype.userAuthored = function userAuthored($emojiButton) { - const oldTitle = this.getAwardTooltip($emojiButton); - const newTitle = 'You cannot vote on your own issue, MR and note'; - gl.utils.updateTooltipTitle($emojiButton, newTitle).tooltip('show'); - // Restore tooltip back to award list - return setTimeout(() => { - $emojiButton.tooltip('hide'); - gl.utils.updateTooltipTitle($emojiButton, oldTitle); - }, 2800); -}; + userAuthored($emojiButton) { + const oldTitle = this.getAwardTooltip($emojiButton); + const newTitle = 'You cannot vote on your own issue, MR and note'; + gl.utils.updateTooltipTitle($emojiButton, newTitle).tooltip('show'); + // Restore tooltip back to award list + return setTimeout(() => { + $emojiButton.tooltip('hide'); + gl.utils.updateTooltipTitle($emojiButton, oldTitle); + }, 2800); + } -AwardsHandler.prototype.scrollToAwards = function scrollToAwards() { - const options = { - scrollTop: $('.awards').offset().top - 110, - }; - return $('body, html').animate(options, 200); -}; + scrollToAwards() { + const options = { + scrollTop: $('.awards').offset().top - 110, + }; + return $('body, html').animate(options, 200); + } -AwardsHandler.prototype.normalizeEmojiName = function normalizeEmojiName(emoji) { - return Object.prototype.hasOwnProperty.call(this.aliases, emoji) ? this.aliases[emoji] : emoji; -}; + normalizeEmojiName(emoji) { + return Object.prototype.hasOwnProperty.call(this.aliases, emoji) ? this.aliases[emoji] : emoji; + } -AwardsHandler - .prototype - .addEmojiToFrequentlyUsedList = function addEmojiToFrequentlyUsedList(emoji) { + addEmojiToFrequentlyUsedList(emoji) { if (isEmojiNameValid(emoji)) { this.frequentlyUsedEmojis = _.uniq(this.getFrequentlyUsedEmojis().concat(emoji)); Cookies.set('frequently_used_emojis', this.frequentlyUsedEmojis.join(','), { expires: 365 }); } - }; - -AwardsHandler.prototype.getFrequentlyUsedEmojis = function getFrequentlyUsedEmojis() { - return this.frequentlyUsedEmojis || (() => { - const frequentlyUsedEmojis = _.uniq((Cookies.get('frequently_used_emojis') || '').split(',')); - this.frequentlyUsedEmojis = frequentlyUsedEmojis.filter( - inputName => isEmojiNameValid(inputName), - ); + } - return this.frequentlyUsedEmojis; - })(); -}; + getFrequentlyUsedEmojis() { + return this.frequentlyUsedEmojis || (() => { + const frequentlyUsedEmojis = _.uniq((Cookies.get('frequently_used_emojis') || '').split(',')); + this.frequentlyUsedEmojis = frequentlyUsedEmojis.filter( + inputName => isEmojiNameValid(inputName), + ); -AwardsHandler.prototype.setupSearch = function setupSearch() { - const $search = $('.js-emoji-menu-search'); + return this.frequentlyUsedEmojis; + })(); + } - this.registerEventListener('on', $search, 'input', (e) => { - const term = $(e.target).val().trim(); - this.searchEmojis(term); - }); + setupSearch() { + const $search = $('.js-emoji-menu-search'); - const $menu = $('.emoji-menu'); - this.registerEventListener('on', $menu, transitionEndEventString, (e) => { - if (e.target === e.currentTarget) { - // Clear the search - this.searchEmojis(''); - } - }); -}; + this.registerEventListener('on', $search, 'input', (e) => { + const term = $(e.target).val().trim(); + this.searchEmojis(term); + }); -AwardsHandler.prototype.searchEmojis = function searchEmojis(term) { - const $search = $('.js-emoji-menu-search'); - $search.val(term); - - // Clean previous search results - $('ul.emoji-menu-search, h5.emoji-search-title').remove(); - if (term.length > 0) { - // Generate a search result block - const h5 = $('<h5 class="emoji-search-title"/>').text('Search results'); - const foundEmojis = this.findMatchingEmojiElements(term).show(); - const ul = $('<ul>').addClass('emoji-menu-list emoji-menu-search').append(foundEmojis); - $('.emoji-menu-content ul, .emoji-menu-content h5').hide(); - $('.emoji-menu-content').append(h5).append(ul); - } else { - $('.emoji-menu-content').children().show(); + const $menu = $('.emoji-menu'); + this.registerEventListener('on', $menu, transitionEndEventString, (e) => { + if (e.target === e.currentTarget) { + // Clear the search + this.searchEmojis(''); + } + }); } -}; - -AwardsHandler.prototype.findMatchingEmojiElements = function findMatchingEmojiElements(term) { - const safeTerm = term.toLowerCase(); - const namesMatchingAlias = []; - Object.keys(emojiAliases).forEach((alias) => { - if (alias.indexOf(safeTerm) >= 0) { - namesMatchingAlias.push(emojiAliases[alias]); + searchEmojis(term) { + const $search = $('.js-emoji-menu-search'); + $search.val(term); + + // Clean previous search results + $('ul.emoji-menu-search, h5.emoji-search-title').remove(); + if (term.length > 0) { + // Generate a search result block + const h5 = $('<h5 class="emoji-search-title"/>').text('Search results'); + const foundEmojis = this.findMatchingEmojiElements(term).show(); + const ul = $('<ul>').addClass('emoji-menu-list emoji-menu-search').append(foundEmojis); + $('.emoji-menu-content ul, .emoji-menu-content h5').hide(); + $('.emoji-menu-content').append(h5).append(ul); + } else { + $('.emoji-menu-content').children().show(); } - }); - const $matchingElements = namesMatchingAlias.concat(safeTerm) - .reduce( - ($result, searchTerm) => - $result.add($(`.emoji-menu-list:not(.frequent-emojis) [data-name*="${searchTerm}"]`)), - $([]), - ); - return $matchingElements.closest('li').clone(); -}; + } -AwardsHandler.prototype.destroy = function destroy() { - this.eventListeners.forEach((entry) => { - entry.element.off.call(entry.element, ...entry.args); - }); - $('.emoji-menu').remove(); -}; + findMatchingEmojiElements(term) { + const safeTerm = term.toLowerCase(); + + const namesMatchingAlias = []; + Object.keys(emojiAliases).forEach((alias) => { + if (alias.indexOf(safeTerm) >= 0) { + namesMatchingAlias.push(emojiAliases[alias]); + } + }); + const $matchingElements = namesMatchingAlias.concat(safeTerm) + .reduce( + ($result, searchTerm) => + $result.add($(`.emoji-menu-list:not(.frequent-emojis) [data-name*="${searchTerm}"]`)), + $([]), + ); + return $matchingElements.closest('li').clone(); + } -export default AwardsHandler; + destroy() { + this.eventListeners.forEach((entry) => { + entry.element.off.call(entry.element, ...entry.args); + }); + $('.emoji-menu').remove(); + } +} diff --git a/app/assets/javascripts/boards/components/board_new_issue.js b/app/assets/javascripts/boards/components/board_new_issue.js index b1c47b09c35..4af8b0c7713 100644 --- a/app/assets/javascripts/boards/components/board_new_issue.js +++ b/app/assets/javascripts/boards/components/board_new_issue.js @@ -17,7 +17,7 @@ export default { methods: { submit(e) { e.preventDefault(); - if (this.title.trim() === '') return; + if (this.title.trim() === '') return Promise.resolve(); this.error = false; @@ -29,7 +29,10 @@ export default { assignees: [], }); - this.list.newIssue(issue) + eventHub.$emit(`scroll-board-list-${this.list.id}`); + this.cancel(); + + return this.list.newIssue(issue) .then(() => { // Need this because our jQuery very kindly disables buttons on ALL form submissions $(this.$refs.submitButton).enable(); @@ -47,9 +50,6 @@ export default { // Show error message this.error = true; }); - - eventHub.$emit(`scroll-board-list-${this.list.id}`); - this.cancel(); }, cancel() { this.title = ''; diff --git a/app/assets/javascripts/boards/models/list.js b/app/assets/javascripts/boards/models/list.js index 548de1a4c52..b4b09b3876e 100644 --- a/app/assets/javascripts/boards/models/list.js +++ b/app/assets/javascripts/boards/models/list.js @@ -112,8 +112,7 @@ class List { .then((resp) => { const data = resp.json(); issue.id = data.iid; - }) - .then(() => { + if (this.issuesSize > 1) { const moveBeforeIid = this.issues[1].id; gl.boardService.moveIssue(issue.id, null, null, null, moveBeforeIid); diff --git a/app/assets/javascripts/environments/components/environment_item.vue b/app/assets/javascripts/environments/components/environment_item.vue index 809c147bf25..b25113e0fc6 100644 --- a/app/assets/javascripts/environments/components/environment_item.vue +++ b/app/assets/javascripts/environments/components/environment_item.vue @@ -403,6 +403,14 @@ export default { return ''; }, + displayEnvironmentActions() { + return this.hasManualActions || + this.externalURL || + this.monitoringUrl || + this.hasStopAction || + this.canRetry; + }, + /** * Constructs folder URL based on the current location and the folder id. * @@ -535,9 +543,12 @@ export default { </span> </div> - <div class="table-section section-30 table-button-footer" role="gridcell"> + <div + v-if="!model.isFolder && displayEnvironmentActions" + class="table-section section-30 table-button-footer" + role="gridcell"> + <div - v-if="!model.isFolder" class="btn-group table-action-buttons" role="group"> diff --git a/app/assets/javascripts/filtered_search/filtered_search_manager.js b/app/assets/javascripts/filtered_search/filtered_search_manager.js index 8f547bd8f1f..1425769d2de 100644 --- a/app/assets/javascripts/filtered_search/filtered_search_manager.js +++ b/app/assets/javascripts/filtered_search/filtered_search_manager.js @@ -40,6 +40,10 @@ class FilteredSearchManager { return []; }) .then((searches) => { + if (!searches) { + return; + } + // Put any searches that may have come in before // we fetched the saved searches ahead of the already saved ones const resultantSearches = this.recentSearchesStore.setRecentSearches( @@ -487,6 +491,7 @@ class FilteredSearchManager { } searchState(e) { + e.preventDefault(); const target = e.currentTarget; // remove focus outline after click target.blur(); diff --git a/app/assets/javascripts/groups/stores/groups_store.js b/app/assets/javascripts/groups/stores/groups_store.js index f6dc4290fd5..6eab6083e8f 100644 --- a/app/assets/javascripts/groups/stores/groups_store.js +++ b/app/assets/javascripts/groups/stores/groups_store.js @@ -47,8 +47,8 @@ export default class GroupsStore { // Map groups to an object groups.map((group) => { - mappedGroups[group.id] = group; - mappedGroups[group.id].subGroups = {}; + mappedGroups[`id${group.id}`] = group; + mappedGroups[`id${group.id}`].subGroups = {}; return group; }); @@ -56,26 +56,27 @@ export default class GroupsStore { const currentGroup = mappedGroups[key]; if (currentGroup.parentId) { // If the group is not at the root level, add it to its parent array of subGroups. - const findParentGroup = mappedGroups[currentGroup.parentId]; + const findParentGroup = mappedGroups[`id${currentGroup.parentId}`]; if (findParentGroup) { - mappedGroups[currentGroup.parentId].subGroups[currentGroup.id] = currentGroup; - mappedGroups[currentGroup.parentId].isOpen = true; // Expand group if it has subgroups + mappedGroups[`id${currentGroup.parentId}`].subGroups[`id${currentGroup.id}`] = currentGroup; + mappedGroups[`id${currentGroup.parentId}`].isOpen = true; // Expand group if it has subgroups } else if (parentGroup && parentGroup.id === currentGroup.parentId) { - tree[currentGroup.id] = currentGroup; + tree[`id${currentGroup.id}`] = currentGroup; } else { - // Means the groups hast no direct parent. - // Save for later processing, we will add them to its corresponding base group + // No parent found. We save it for later processing orphans.push(currentGroup); + + // Add to tree to preserve original order + tree[`id${currentGroup.id}`] = currentGroup; } } else { - // If the group is at the root level, add it to first level elements array. - tree[currentGroup.id] = currentGroup; + // If the group is at the top level, add it to first level elements array. + tree[`id${currentGroup.id}`] = currentGroup; } return key; }); - // Hopefully this array will be empty for most cases if (orphans.length) { orphans.map((orphan) => { let found = false; @@ -83,11 +84,23 @@ export default class GroupsStore { Object.keys(tree).map((key) => { const group = tree[key]; - if (currentOrphan.fullPath.lastIndexOf(group.fullPath) === 0) { + + if ( + group && + currentOrphan.fullPath.lastIndexOf(group.fullPath) === 0 && + // Make sure the currently selected orphan is not the same as the group + // we are checking here otherwise it will end up in an infinite loop + currentOrphan.id !== group.id + ) { group.subGroups[currentOrphan.id] = currentOrphan; group.isOpen = true; currentOrphan.isOrphan = true; found = true; + + // Delete if group was put at the top level. If not the group will be displayed twice. + if (tree[`id${currentOrphan.id}`]) { + delete tree[`id${currentOrphan.id}`]; + } } return key; @@ -95,7 +108,8 @@ export default class GroupsStore { if (!found) { currentOrphan.isOrphan = true; - tree[currentOrphan.id] = currentOrphan; + + tree[`id${currentOrphan.id}`] = currentOrphan; } return orphan; @@ -140,7 +154,7 @@ export default class GroupsStore { // eslint-disable-next-line class-methods-use-this removeGroup(group, collection) { - Vue.delete(collection, group.id); + Vue.delete(collection, `id${group.id}`); } // eslint-disable-next-line class-methods-use-this diff --git a/app/assets/javascripts/issue_show/components/app.vue b/app/assets/javascripts/issue_show/components/app.vue index 8473a81bc88..3d5fb7f441c 100644 --- a/app/assets/javascripts/issue_show/components/app.vue +++ b/app/assets/javascripts/issue_show/components/app.vue @@ -204,13 +204,7 @@ export default { method: 'getData', successCallback: (res) => { const data = res.json(); - const shouldUpdate = this.store.stateShouldUpdate(data); - this.store.updateState(data); - - if (this.showForm && (shouldUpdate.title || shouldUpdate.description)) { - this.store.formState.lockedWarningVisible = true; - } }, errorCallback(err) { throw new Error(err); diff --git a/app/assets/javascripts/issue_show/stores/index.js b/app/assets/javascripts/issue_show/stores/index.js index f2b822f3cbb..0c8bd6f1cc3 100644 --- a/app/assets/javascripts/issue_show/stores/index.js +++ b/app/assets/javascripts/issue_show/stores/index.js @@ -12,6 +12,10 @@ export default class Store { } updateState(data) { + if (this.stateShouldUpdate(data)) { + this.formState.lockedWarningVisible = true; + } + this.state.titleHtml = data.title; this.state.titleText = data.title_text; this.state.descriptionHtml = data.description; @@ -23,10 +27,8 @@ export default class Store { } stateShouldUpdate(data) { - return { - title: this.state.titleText !== data.title_text, - description: this.state.descriptionText !== data.description_text, - }; + return this.state.titleText !== data.title_text || + this.state.descriptionText !== data.description_text; } setFormState(state) { diff --git a/app/assets/javascripts/lib/utils/common_utils.js b/app/assets/javascripts/lib/utils/common_utils.js index 2aca86189fd..122ec138c59 100644 --- a/app/assets/javascripts/lib/utils/common_utils.js +++ b/app/assets/javascripts/lib/utils/common_utils.js @@ -86,18 +86,25 @@ // This is required to handle non-unicode characters in hash hash = decodeURIComponent(hash); + var fixedTabs = document.querySelector('.js-tabs-affix'); + var fixedNav = document.querySelector('.navbar-gitlab'); + + var adjustment = 0; + if (fixedNav) adjustment -= fixedNav.offsetHeight; + // scroll to user-generated markdown anchor if we cannot find a match if (document.getElementById(hash) === null) { var target = document.getElementById('user-content-' + hash); if (target && target.scrollIntoView) { target.scrollIntoView(true); + window.scrollBy(0, adjustment); } } else { // only adjust for fixedTabs when not targeting user-generated content - var fixedTabs = document.querySelector('.js-tabs-affix'); if (fixedTabs) { - window.scrollBy(0, -fixedTabs.offsetHeight); + adjustment -= fixedTabs.offsetHeight; } + window.scrollBy(0, adjustment); } }; diff --git a/app/assets/javascripts/locale/es/app.js b/app/assets/javascripts/locale/es/app.js index eafcd15acf9..8d951928849 100644 --- a/app/assets/javascripts/locale/es/app.js +++ b/app/assets/javascripts/locale/es/app.js @@ -1 +1 @@ -var locales = locales || {}; locales['es'] = {"domain":"app","locale_data":{"app":{"":{"Project-Id-Version":"gitlab 1.0.0","Report-Msgid-Bugs-To":"","PO-Revision-Date":"2017-06-15 21:59-0500","Language-Team":"Spanish","Language":"es","MIME-Version":"1.0","Content-Type":"text/plain; charset=UTF-8","Content-Transfer-Encoding":"8bit","Plural-Forms":"nplurals=2; plural=n != 1;","Last-Translator":"Bob Van Landuyt <bob@gitlab.com>","X-Generator":"Poedit 2.0.2","POT-Creation-Date":"2017-06-15 21:59-0500","lang":"es","domain":"app","plural_forms":"nplurals=2; plural=n != 1;"},"%{commit_author_link} committed %{commit_timeago}":["%{commit_author_link} cambió %{commit_timeago}"],"About auto deploy":["Acerca del auto despliegue"],"Active":["Activo"],"Activity":["Actividad"],"Add Changelog":["Agregar Changelog"],"Add Contribution guide":["Agregar guía de contribución"],"Add License":["Agregar Licencia"],"Add an SSH key to your profile to pull or push via SSH.":["Agregar una clave SSH a tu perfil para actualizar o enviar a través de SSH."],"Add new directory":["Agregar nuevo directorio"],"Archived project! Repository is read-only":["¡Proyecto archivado! El repositorio es de solo lectura"],"Are you sure you want to delete this pipeline schedule?":["¿Estás seguro que deseas eliminar esta programación del pipeline?"],"Attach a file by drag & drop or %{upload_link}":["Adjunte un archivo arrastrando & soltando o %{upload_link}"],"Branch":["Rama","Ramas"],"Branch <strong>%{branch_name}</strong> was created. To set up auto deploy, choose a GitLab CI Yaml template and commit your changes. %{link_to_autodeploy_doc}":["La rama <strong>%{branch_name}</strong> fue creada. Para configurar el auto despliegue, escoge una plantilla Yaml para GitLab CI y envía tus cambios. %{link_to_autodeploy_doc}"],"Branches":["Ramas"],"Browse files":["Examinar los archivos"],"ByAuthor|by":["por"],"CI configuration":["Configuración de CI"],"Cancel":["Cancelar"],"ChangeTypeActionLabel|Pick into branch":["Escoger en la rama"],"ChangeTypeActionLabel|Revert in branch":["Revertir en la rama"],"ChangeTypeAction|Cherry-pick":["Cherry-pick"],"ChangeTypeAction|Revert":["Revertir"],"Changelog":["Changelog"],"Charts":["Gráficos"],"Cherry-pick this commit":["Escoger este cambio"],"Cherry-pick this merge request":["Escoger esta solicitud de fusión"],"CiStatusLabel|canceled":["cancelado"],"CiStatusLabel|created":["creado"],"CiStatusLabel|failed":["fallido"],"CiStatusLabel|manual action":["acción manual"],"CiStatusLabel|passed":["pasó"],"CiStatusLabel|passed with warnings":["pasó con advertencias"],"CiStatusLabel|pending":["pendiente"],"CiStatusLabel|skipped":["omitido"],"CiStatusLabel|waiting for manual action":["esperando acción manual"],"CiStatusText|blocked":["bloqueado"],"CiStatusText|canceled":["cancelado"],"CiStatusText|created":["creado"],"CiStatusText|failed":["fallado"],"CiStatusText|manual":["manual"],"CiStatusText|passed":["pasó"],"CiStatusText|pending":["pendiente"],"CiStatusText|skipped":["omitido"],"CiStatus|running":["en ejecución"],"Commit":["Cambio","Cambios"],"Commit message":["Mensaje del cambio"],"CommitBoxTitle|Commit":["Cambio"],"CommitMessage|Add %{file_name}":["Agregar %{file_name}"],"Commits":["Cambios"],"Commits|History":["Historial"],"Committed by":["Enviado por"],"Compare":["Comparar"],"Contribution guide":["Guía de contribución"],"Contributors":["Contribuidores"],"Copy URL to clipboard":["Copiar URL al portapapeles"],"Copy commit SHA to clipboard":["Copiar SHA del cambio al portapapeles"],"Create New Directory":["Crear Nuevo Directorio"],"Create directory":["Crear directorio"],"Create empty bare repository":["Crear repositorio vacío"],"Create merge request":["Crear solicitud de fusión"],"Create new...":["Crear nuevo..."],"CreateNewFork|Fork":["Bifurcar"],"CreateTag|Tag":["Etiqueta"],"Cron Timezone":["Zona horaria del Cron"],"Cron syntax":["Sintaxis de Cron"],"Custom notification events":["Eventos de notificaciones personalizadas"],"Custom notification levels are the same as participating levels. With custom notification levels you will also receive notifications for select events. To find out more, check out %{notification_link}.":["Los niveles de notificación personalizados son los mismos que los niveles participantes. Con los niveles de notificación personalizados, también recibirá notificaciones para eventos seleccionados. Para obtener más información, consulte %{notification_link}."],"Cycle Analytics":["Cycle Analytics"],"Cycle Analytics gives an overview of how much time it takes to go from idea to production in your project.":["Cycle Analytics ofrece una visión general de cuánto tiempo tarda en pasar de idea a producción en su proyecto."],"CycleAnalyticsStage|Code":["Código"],"CycleAnalyticsStage|Issue":["Incidencia"],"CycleAnalyticsStage|Plan":["Planificación"],"CycleAnalyticsStage|Production":["Producción"],"CycleAnalyticsStage|Review":["Revisión"],"CycleAnalyticsStage|Staging":["Puesta en escena"],"CycleAnalyticsStage|Test":["Pruebas"],"Define a custom pattern with cron syntax":["Definir un patrón personalizado con la sintaxis de cron"],"Delete":["Eliminar"],"Deploy":["Despliegue","Despliegues"],"Description":["Descripción"],"Directory name":["Nombre del directorio"],"Don't show again":["No mostrar de nuevo"],"Download":["Descargar"],"Download tar":["Descargar tar"],"Download tar.bz2":["Descargar tar.bz2"],"Download tar.gz":["Descargar tar.gz"],"Download zip":["Descargar zip"],"DownloadArtifacts|Download":["Descargar"],"DownloadCommit|Email Patches":["Parches por correo electrónico"],"DownloadCommit|Plain Diff":["Diferencias en texto plano"],"DownloadSource|Download":["Descargar"],"Edit":["Editar"],"Edit Pipeline Schedule %{id}":["Editar Programación del Pipeline %{id}"],"Every day (at 4:00am)":["Todos los días (a las 4:00 am)"],"Every month (on the 1st at 4:00am)":["Todos los meses (el día 1 a las 4:00 am)"],"Every week (Sundays at 4:00am)":["Todas las semanas (domingos a las 4:00 am)"],"Failed to change the owner":["Error al cambiar el propietario"],"Failed to remove the pipeline schedule":["Error al eliminar la programación del pipeline"],"Files":["Archivos"],"Find by path":["Buscar por ruta"],"Find file":["Buscar archivo"],"FirstPushedBy|First":["Primer"],"FirstPushedBy|pushed by":["enviado por"],"Fork":["Bifurcación","Bifurcaciones"],"ForkedFromProjectPath|Forked from":["Bifurcado de"],"From issue creation until deploy to production":["Desde la creación de la incidencia hasta el despliegue a producción"],"From merge request merge until deploy to production":["Desde la integración de la solicitud de fusión hasta el despliegue a producción"],"Go to your fork":["Ir a tu bifurcación"],"GoToYourFork|Fork":["Bifurcación"],"Home":["Inicio"],"Housekeeping successfully started":["Servicio de limpieza iniciado con éxito"],"Import repository":["Importar repositorio"],"Interval Pattern":["Patrón de intervalo"],"Introducing Cycle Analytics":["Introducción a Cycle Analytics"],"LFSStatus|Disabled":["Deshabilitado"],"LFSStatus|Enabled":["Habilitado"],"Last %d day":["Último %d día","Últimos %d días"],"Last Pipeline":["Último Pipeline"],"Last Update":["Última actualización"],"Last commit":["Último cambio"],"Learn more in the":["Más información en la"],"Learn more in the|pipeline schedules documentation":["documentación sobre la programación de pipelines"],"Leave group":["Abandonar grupo"],"Leave project":["Abandonar proyecto"],"Limited to showing %d event at most":["Limitado a mostrar máximo %d evento","Limitado a mostrar máximo %d eventos"],"Median":["Mediana"],"MissingSSHKeyWarningLink|add an SSH key":["agregar una clave SSH"],"New Issue":["Nueva incidencia","Nuevas incidencias"],"New Pipeline Schedule":["Nueva Programación del Pipeline"],"New branch":["Nueva rama"],"New directory":["Nuevo directorio"],"New file":["Nuevo archivo"],"New issue":["Nueva incidencia"],"New merge request":["Nueva solicitud de fusión"],"New schedule":["Nueva programación"],"New snippet":["Nuevo fragmento de código"],"New tag":["Nueva etiqueta"],"No repository":["No hay repositorio"],"No schedules":["No hay programaciones"],"Not available":["No disponible"],"Not enough data":["No hay suficientes datos"],"Notification events":["Eventos de notificación"],"NotificationEvent|Close issue":["Cerrar incidencia"],"NotificationEvent|Close merge request":["Cerrar solicitud de fusión"],"NotificationEvent|Failed pipeline":["Pipeline fallido"],"NotificationEvent|Merge merge request":["Integrar solicitud de fusión"],"NotificationEvent|New issue":["Nueva incidencia"],"NotificationEvent|New merge request":["Nueva solicitud de fusión"],"NotificationEvent|New note":["Nueva nota"],"NotificationEvent|Reassign issue":["Reasignar incidencia"],"NotificationEvent|Reassign merge request":["Reasignar solicitud de fusión"],"NotificationEvent|Reopen issue":["Reabrir incidencia"],"NotificationEvent|Successful pipeline":["Pipeline exitoso"],"NotificationLevel|Custom":["Personalizado"],"NotificationLevel|Disabled":["Deshabilitado"],"NotificationLevel|Global":["Global"],"NotificationLevel|On mention":["Cuando me mencionan"],"NotificationLevel|Participate":["Participación"],"NotificationLevel|Watch":["Vigilancia"],"OfSearchInADropdown|Filter":["Filtrar"],"OpenedNDaysAgo|Opened":["Abierto"],"Options":["Opciones"],"Owner":["Propietario"],"Pipeline":["Pipeline"],"Pipeline Health":["Estado del Pipeline"],"Pipeline Schedule":["Programación del Pipeline"],"Pipeline Schedules":["Programaciones de los Pipelines"],"PipelineSchedules|Activated":["Activado"],"PipelineSchedules|Active":["Activos"],"PipelineSchedules|All":["Todos"],"PipelineSchedules|Inactive":["Inactivos"],"PipelineSchedules|Next Run":["Próxima Ejecución"],"PipelineSchedules|None":["Ninguno"],"PipelineSchedules|Provide a short description for this pipeline":["Proporcione una breve descripción para este pipeline"],"PipelineSchedules|Take ownership":["Tomar posesión"],"PipelineSchedules|Target":["Destino"],"PipelineSheduleIntervalPattern|Custom":["Personalizado"],"Pipeline|with stage":["con etapa"],"Pipeline|with stages":["con etapas"],"Project '%{project_name}' queued for deletion.":["Proyecto ‘%{project_name}’ en cola para eliminación."],"Project '%{project_name}' was successfully created.":["Proyecto ‘%{project_name}’ fue creado satisfactoriamente."],"Project '%{project_name}' was successfully updated.":["Proyecto ‘%{project_name}’ fue actualizado satisfactoriamente."],"Project '%{project_name}' will be deleted.":["Proyecto ‘%{project_name}’ será eliminado."],"Project access must be granted explicitly to each user.":["El acceso al proyecto debe concederse explícitamente a cada usuario."],"Project export could not be deleted.":["No se pudo eliminar la exportación del proyecto."],"Project export has been deleted.":["La exportación del proyecto ha sido eliminada."],"Project export link has expired. Please generate a new export from your project settings.":["El enlace de exportación del proyecto ha caducado. Por favor, genera una nueva exportación desde la configuración del proyecto."],"Project export started. A download link will be sent by email.":["Se inició la exportación del proyecto. Se enviará un enlace de descarga por correo electrónico."],"Project home":["Inicio del proyecto"],"ProjectFeature|Disabled":["Deshabilitada"],"ProjectFeature|Everyone with access":["Todos con acceso"],"ProjectFeature|Only team members":["Solo miembros del equipo"],"ProjectFileTree|Name":["Nombre"],"ProjectLastActivity|Never":["Nunca"],"ProjectLifecycle|Stage":["Etapa"],"ProjectNetworkGraph|Graph":["Historial gráfico"],"Read more":["Leer más"],"Readme":["Léeme"],"RefSwitcher|Branches":["Ramas"],"RefSwitcher|Tags":["Etiquetas"],"Related Commits":["Cambios Relacionados"],"Related Deployed Jobs":["Trabajos Desplegados Relacionados"],"Related Issues":["Incidencias Relacionadas"],"Related Jobs":["Trabajos Relacionados"],"Related Merge Requests":["Solicitudes de fusión Relacionadas"],"Related Merged Requests":["Solicitudes de fusión Relacionadas"],"Remind later":["Recordar después"],"Remove project":["Eliminar proyecto"],"Request Access":["Solicitar acceso"],"Revert this commit":["Revertir este cambio"],"Revert this merge request":["Revertir esta solicitud de fusión"],"Save pipeline schedule":["Guardar programación del pipeline"],"Schedule a new pipeline":["Programar un nuevo pipeline"],"Scheduling Pipelines":["Programación de Pipelines"],"Search branches and tags":["Buscar ramas y etiquetas"],"Select Archive Format":["Seleccionar formato de archivo"],"Select a timezone":["Selecciona una zona horaria"],"Select target branch":["Selecciona una rama de destino"],"Set a password on your account to pull or push via %{protocol}":["Establezca una contraseña en su cuenta para actualizar o enviar a través de %{protocol}"],"Set up CI":["Configurar CI"],"Set up Koding":["Configurar Koding"],"Set up auto deploy":["Configurar auto despliegue"],"SetPasswordToCloneLink|set a password":["establecer una contraseña"],"Showing %d event":["Mostrando %d evento","Mostrando %d eventos"],"Source code":["Código fuente"],"StarProject|Star":["Destacar"],"Start a %{new_merge_request} with these changes":["Iniciar una %{new_merge_request} con estos cambios"],"Switch branch/tag":["Cambiar rama/etiqueta"],"Tag":["Etiqueta","Etiquetas"],"Tags":["Etiquetas"],"Target Branch":["Rama de destino"],"The coding stage shows the time from the first commit to creating the merge request. The data will automatically be added here once you create your first merge request.":["La etapa de desarrollo muestra el tiempo desde el primer cambio hasta la creación de la solicitud de fusión. Los datos serán automáticamente incorporados aquí una vez creada tu primera solicitud de fusión."],"The collection of events added to the data gathered for that stage.":["La colección de eventos agregados a los datos recopilados para esa etapa."],"The fork relationship has been removed.":["La relación con la bifurcación se ha eliminado."],"The issue stage shows the time it takes from creating an issue to assigning the issue to a milestone, or add the issue to a list on your Issue Board. Begin creating issues to see data for this stage.":["La etapa de incidencia muestra el tiempo que toma desde la creación de un tema hasta asignar el tema a un hito, o añadir el tema a una lista en el panel de temas. Empieza a crear temas para ver los datos de esta etapa."],"The phase of the development lifecycle.":["La etapa del ciclo de vida de desarrollo."],"The pipelines schedule runs pipelines in the future, repeatedly, for specific branches or tags. Those scheduled pipelines will inherit limited project access based on their associated user.":["La programación de pipelines ejecuta pipelines en el futuro, repetidamente, para ramas o etiquetas específicas. Los pipelines programados heredarán acceso limitado al proyecto basado en su usuario asociado."],"The planning stage shows the time from the previous step to pushing your first commit. This time will be added automatically once you push your first commit.":["La etapa de planificación muestra el tiempo desde el paso anterior hasta el envío de tu primera confirmación. Este tiempo se añadirá automáticamente una vez que usted envíe el primer cambio."],"The production stage shows the total time it takes between creating an issue and deploying the code to production. The data will be automatically added once you have completed the full idea to production cycle.":["La etapa de producción muestra el tiempo total que tarda entre la creación de una incidencia y el despliegue del código a producción. Los datos se añadirán automáticamente una vez haya finalizado por completo el ciclo de idea a producción."],"The project can be accessed by any logged in user.":["El proyecto puede ser accedido por cualquier usuario conectado."],"The project can be accessed without any authentication.":["El proyecto puede accederse sin ninguna autenticación."],"The repository for this project does not exist.":["El repositorio para este proyecto no existe."],"The review stage shows the time from creating the merge request to merging it. The data will automatically be added after you merge your first merge request.":["La etapa de revisión muestra el tiempo desde la creación de la solicitud de fusión hasta que los cambios se fusionaron. Los datos se añadirán automáticamente después de fusionar su primera solicitud de fusión."],"The staging stage shows the time between merging the MR and deploying code to the production environment. The data will be automatically added once you deploy to production for the first time.":["La etapa de puesta en escena muestra el tiempo entre la fusión y el despliegue de código en el entorno de producción. Los datos se añadirán automáticamente una vez que se despliega a producción por primera vez."],"The testing stage shows the time GitLab CI takes to run every pipeline for the related merge request. The data will automatically be added after your first pipeline finishes running.":["La etapa de pruebas muestra el tiempo que GitLab CI toma para ejecutar cada pipeline para la solicitud de fusión relacionada. Los datos se añadirán automáticamente luego de que el primer pipeline termine de ejecutarse."],"The time taken by each data entry gathered by that stage.":["El tiempo utilizado por cada entrada de datos obtenido por esa etapa."],"The value lying at the midpoint of a series of observed values. E.g., between 3, 5, 9, the median is 5. Between 3, 5, 7, 8, the median is (5+7)/2 = 6.":["El valor en el punto medio de una serie de valores observados. Por ejemplo, entre 3, 5, 9, la mediana es 5. Entre 3, 5, 7, 8, la mediana es (5 + 7) / 2 = 6."],"This means you can not push code until you create an empty repository or import existing one.":["Esto significa que no puede enviar código hasta que cree un repositorio vacío o importe uno existente."],"Time before an issue gets scheduled":["Tiempo antes de que una incidencia sea programada"],"Time before an issue starts implementation":["Tiempo antes de que empieze la implementación de una incidencia"],"Time between merge request creation and merge/close":["Tiempo entre la creación de la solicitud de fusión y la integración o cierre de ésta"],"Time until first merge request":["Tiempo hasta la primera solicitud de fusión"],"Timeago|%s days ago":["hace %s días"],"Timeago|%s days remaining":["%s días restantes"],"Timeago|%s hours remaining":["%s horas restantes"],"Timeago|%s minutes ago":["hace %s minutos"],"Timeago|%s minutes remaining":["%s minutos restantes"],"Timeago|%s months ago":["hace %s meses"],"Timeago|%s months remaining":["%s meses restantes"],"Timeago|%s seconds remaining":["%s segundos restantes"],"Timeago|%s weeks ago":["hace %s semanas"],"Timeago|%s weeks remaining":["%s semanas restantes"],"Timeago|%s years ago":["hace %s años"],"Timeago|%s years remaining":["%s años restantes"],"Timeago|1 day remaining":["1 día restante"],"Timeago|1 hour remaining":["1 hora restante"],"Timeago|1 minute remaining":["1 minuto restante"],"Timeago|1 month remaining":["1 mes restante"],"Timeago|1 week remaining":["1 semana restante"],"Timeago|1 year remaining":["1 año restante"],"Timeago|Past due":["Atrasado"],"Timeago|a day ago":["hace un día"],"Timeago|a month ago":["hace un mes"],"Timeago|a week ago":["hace una semana"],"Timeago|a while":["hace un momento"],"Timeago|a year ago":["hace un año"],"Timeago|about %s hours ago":["hace alrededor de %s horas"],"Timeago|about a minute ago":["hace alrededor de 1 minuto"],"Timeago|about an hour ago":["hace alrededor de 1 hora"],"Timeago|in %s days":["en %s días"],"Timeago|in %s hours":["en %s horas"],"Timeago|in %s minutes":["en %s minutos"],"Timeago|in %s months":["en %s meses"],"Timeago|in %s seconds":["en %s segundos"],"Timeago|in %s weeks":["en %s semanas"],"Timeago|in %s years":["en %s años"],"Timeago|in 1 day":["en 1 día"],"Timeago|in 1 hour":["en 1 hora"],"Timeago|in 1 minute":["en 1 minuto"],"Timeago|in 1 month":["en 1 mes"],"Timeago|in 1 week":["en 1 semana"],"Timeago|in 1 year":["en 1 año"],"Timeago|less than a minute ago":["hace menos de 1 minuto"],"Time|hr":["hr","hrs"],"Time|min":["min","mins"],"Time|s":["s"],"Total Time":["Tiempo Total"],"Total test time for all commits/merges":["Tiempo total de pruebas para todos los cambios o integraciones"],"Unstar":["No Destacar"],"Upload New File":["Subir nuevo archivo"],"Upload file":["Subir archivo"],"Use your global notification setting":["Utiliza tu configuración de notificación global"],"VisibilityLevel|Internal":["Interno"],"VisibilityLevel|Private":["Privado"],"VisibilityLevel|Public":["Público"],"Want to see the data? Please ask an administrator for access.":["¿Quieres ver los datos? Por favor pide acceso al administrador."],"We don't have enough data to show this stage.":["No hay suficientes datos para mostrar en esta etapa."],"Withdraw Access Request":["Retirar Solicitud de Acceso"],"You are going to remove %{project_name_with_namespace}.\\nRemoved project CANNOT be restored!\\nAre you ABSOLUTELY sure?":["Va a eliminar %{project_name_with_namespace}.\\n¡El proyecto eliminado NO puede ser restaurado!\\n¿Estás TOTALMENTE seguro?"],"You are going to remove the fork relationship to source project %{forked_from_project}. Are you ABSOLUTELY sure?":["Vas a eliminar el enlace de la bifurcación con el proyecto original %{forked_from_project}. ¿Estás TOTALMENTE seguro?"],"You are going to transfer %{project_name_with_namespace} to another owner. Are you ABSOLUTELY sure?":["Vas a transferir %{project_name_with_namespace} a otro propietario. ¿Estás TOTALMENTE seguro?"],"You can only add files when you are on a branch":["Solo puedes agregar archivos cuando estás en una rama"],"You must sign in to star a project":["Debes iniciar sesión para destacar un proyecto"],"You need permission.":["Necesitas permisos."],"You will not get any notifications via email":["No recibirás ninguna notificación por correo electrónico"],"You will only receive notifications for the events you choose":["Solo recibirás notificaciones de los eventos que elijas"],"You will only receive notifications for threads you have participated in":["Solo recibirás notificaciones de los temas en los que has participado"],"You will receive notifications for any activity":["Recibirás notificaciones por cualquier actividad"],"You will receive notifications only for comments in which you were @mentioned":["Recibirás notificaciones solo para los comentarios en los que se te mencionó"],"You won't be able to pull or push project code via %{protocol} until you %{set_password_link} on your account":["No podrás actualizar o enviar código al proyecto a través de %{protocol} hasta que %{set_password_link} en tu cuenta"],"You won't be able to pull or push project code via SSH until you %{add_ssh_key_link} to your profile":["No podrás actualizar o enviar código al proyecto a través de SSH hasta que %{add_ssh_key_link} en su perfil"],"Your name":["Tu nombre"],"day":["día","días"],"new merge request":["nueva solicitud de fusión"],"notification emails":["correos electrónicos de notificación"],"parent":["padre","padres"]}}};
\ No newline at end of file +var locales = locales || {}; locales['es'] = {"domain":"app","locale_data":{"app":{"":{"Project-Id-Version":"gitlab 1.0.0","Report-Msgid-Bugs-To":"","PO-Revision-Date":"2017-06-21 12:09-0500","Language-Team":"Spanish","Language":"es","MIME-Version":"1.0","Content-Type":"text/plain; charset=UTF-8","Content-Transfer-Encoding":"8bit","Plural-Forms":"nplurals=2; plural=n != 1;","Last-Translator":"Bob Van Landuyt <bob@gitlab.com>","X-Generator":"Poedit 2.0.2","lang":"es","domain":"app","plural_forms":"nplurals=2; plural=n != 1;"},"%d additional commit has been omitted to prevent performance issues.":["%d cambio adicional ha sido omitido para evitar problemas de rendimiento.","%d cambios adicionales han sido omitidos para evitar problemas de rendimiento."],"%d commit":["%d cambio","%d cambios"],"%{commit_author_link} committed %{commit_timeago}":["%{commit_author_link} cambió %{commit_timeago}"],"About auto deploy":["Acerca del auto despliegue"],"Active":["Activo"],"Activity":["Actividad"],"Add Changelog":["Agregar Changelog"],"Add Contribution guide":["Agregar guía de contribución"],"Add License":["Agregar Licencia"],"Add an SSH key to your profile to pull or push via SSH.":["Agregar una clave SSH a tu perfil para actualizar o enviar a través de SSH."],"Add new directory":["Agregar nuevo directorio"],"Archived project! Repository is read-only":["¡Proyecto archivado! El repositorio es de solo lectura"],"Are you sure you want to delete this pipeline schedule?":["¿Estás seguro que deseas eliminar esta programación del pipeline?"],"Attach a file by drag & drop or %{upload_link}":["Adjunte un archivo arrastrando & soltando o %{upload_link}"],"Branch":["Rama","Ramas"],"Branch <strong>%{branch_name}</strong> was created. To set up auto deploy, choose a GitLab CI Yaml template and commit your changes. %{link_to_autodeploy_doc}":["La rama <strong>%{branch_name}</strong> fue creada. Para configurar el auto despliegue, escoge una plantilla Yaml para GitLab CI y envía tus cambios. %{link_to_autodeploy_doc}"],"BranchSwitcherPlaceholder|Search branches":["Buscar ramas"],"BranchSwitcherTitle|Switch branch":["Cambiar rama"],"Branches":["Ramas"],"Browse Directory":["Examinar directorio"],"Browse File":["Examinar archivo"],"Browse Files":["Examinar archivos"],"Browse files":["Examinar archivos"],"ByAuthor|by":["por"],"CI configuration":["Configuración de CI"],"Cancel":["Cancelar"],"ChangeTypeActionLabel|Pick into branch":["Escoger en la rama"],"ChangeTypeActionLabel|Revert in branch":["Revertir en la rama"],"ChangeTypeAction|Cherry-pick":["Cherry-pick"],"ChangeTypeAction|Revert":["Revertir"],"Changelog":["Changelog"],"Charts":["Gráficos"],"Cherry-pick this commit":["Escoger este cambio"],"Cherry-pick this merge request":["Escoger esta solicitud de fusión"],"CiStatusLabel|canceled":["cancelado"],"CiStatusLabel|created":["creado"],"CiStatusLabel|failed":["fallido"],"CiStatusLabel|manual action":["acción manual"],"CiStatusLabel|passed":["pasó"],"CiStatusLabel|passed with warnings":["pasó con advertencias"],"CiStatusLabel|pending":["pendiente"],"CiStatusLabel|skipped":["omitido"],"CiStatusLabel|waiting for manual action":["esperando acción manual"],"CiStatusText|blocked":["bloqueado"],"CiStatusText|canceled":["cancelado"],"CiStatusText|created":["creado"],"CiStatusText|failed":["fallado"],"CiStatusText|manual":["manual"],"CiStatusText|passed":["pasó"],"CiStatusText|pending":["pendiente"],"CiStatusText|skipped":["omitido"],"CiStatus|running":["en ejecución"],"Commit":["Cambio","Cambios"],"Commit message":["Mensaje del cambio"],"CommitBoxTitle|Commit":["Cambio"],"CommitMessage|Add %{file_name}":["Agregar %{file_name}"],"Commits":["Cambios"],"Commits feed":["Feed de cambios"],"Commits|History":["Historial"],"Committed by":["Enviado por"],"Compare":["Comparar"],"Contribution guide":["Guía de contribución"],"Contributors":["Contribuidores"],"Copy URL to clipboard":["Copiar URL al portapapeles"],"Copy commit SHA to clipboard":["Copiar SHA del cambio al portapapeles"],"Create New Directory":["Crear Nuevo Directorio"],"Create directory":["Crear directorio"],"Create empty bare repository":["Crear repositorio vacío"],"Create merge request":["Crear solicitud de fusión"],"Create new...":["Crear nuevo..."],"CreateNewFork|Fork":["Bifurcar"],"CreateTag|Tag":["Etiqueta"],"Cron Timezone":["Zona horaria del Cron"],"Cron syntax":["Sintaxis de Cron"],"Custom notification events":["Eventos de notificaciones personalizadas"],"Custom notification levels are the same as participating levels. With custom notification levels you will also receive notifications for select events. To find out more, check out %{notification_link}.":["Los niveles de notificación personalizados son los mismos que los niveles participantes. Con los niveles de notificación personalizados, también recibirá notificaciones para eventos seleccionados. Para obtener más información, consulte %{notification_link}."],"Cycle Analytics":["Cycle Analytics"],"Cycle Analytics gives an overview of how much time it takes to go from idea to production in your project.":["Cycle Analytics ofrece una visión general de cuánto tiempo tarda en pasar de idea a producción en su proyecto."],"CycleAnalyticsStage|Code":["Código"],"CycleAnalyticsStage|Issue":["Incidencia"],"CycleAnalyticsStage|Plan":["Planificación"],"CycleAnalyticsStage|Production":["Producción"],"CycleAnalyticsStage|Review":["Revisión"],"CycleAnalyticsStage|Staging":["Puesta en escena"],"CycleAnalyticsStage|Test":["Pruebas"],"Define a custom pattern with cron syntax":["Definir un patrón personalizado con la sintaxis de cron"],"Delete":["Eliminar"],"Deploy":["Despliegue","Despliegues"],"Description":["Descripción"],"Directory name":["Nombre del directorio"],"Don't show again":["No mostrar de nuevo"],"Download":["Descargar"],"Download tar":["Descargar tar"],"Download tar.bz2":["Descargar tar.bz2"],"Download tar.gz":["Descargar tar.gz"],"Download zip":["Descargar zip"],"DownloadArtifacts|Download":["Descargar"],"DownloadCommit|Email Patches":["Parches por correo electrónico"],"DownloadCommit|Plain Diff":["Diferencias en texto plano"],"DownloadSource|Download":["Descargar"],"Edit":["Editar"],"Edit Pipeline Schedule %{id}":["Editar Programación del Pipeline %{id}"],"Every day (at 4:00am)":["Todos los días (a las 4:00 am)"],"Every month (on the 1st at 4:00am)":["Todos los meses (el día 1 a las 4:00 am)"],"Every week (Sundays at 4:00am)":["Todas las semanas (domingos a las 4:00 am)"],"Failed to change the owner":["Error al cambiar el propietario"],"Failed to remove the pipeline schedule":["Error al eliminar la programación del pipeline"],"Files":["Archivos"],"Filter by commit message":["Filtrar por mensaje del cambio"],"Find by path":["Buscar por ruta"],"Find file":["Buscar archivo"],"FirstPushedBy|First":["Primer"],"FirstPushedBy|pushed by":["enviado por"],"Fork":["Bifurcación","Bifurcaciones"],"ForkedFromProjectPath|Forked from":["Bifurcado de"],"From issue creation until deploy to production":["Desde la creación de la incidencia hasta el despliegue a producción"],"From merge request merge until deploy to production":["Desde la integración de la solicitud de fusión hasta el despliegue a producción"],"Go to your fork":["Ir a tu bifurcación"],"GoToYourFork|Fork":["Bifurcación"],"Home":["Inicio"],"Housekeeping successfully started":["Servicio de limpieza iniciado con éxito"],"Import repository":["Importar repositorio"],"Interval Pattern":["Patrón de intervalo"],"Introducing Cycle Analytics":["Introducción a Cycle Analytics"],"LFSStatus|Disabled":["Deshabilitado"],"LFSStatus|Enabled":["Habilitado"],"Last %d day":["Último %d día","Últimos %d días"],"Last Pipeline":["Último Pipeline"],"Last Update":["Última actualización"],"Last commit":["Último cambio"],"Learn more in the":["Más información en la"],"Learn more in the|pipeline schedules documentation":["documentación sobre la programación de pipelines"],"Leave group":["Abandonar grupo"],"Leave project":["Abandonar proyecto"],"Limited to showing %d event at most":["Limitado a mostrar máximo %d evento","Limitado a mostrar máximo %d eventos"],"Median":["Mediana"],"MissingSSHKeyWarningLink|add an SSH key":["agregar una clave SSH"],"New Issue":["Nueva incidencia","Nuevas incidencias"],"New Pipeline Schedule":["Nueva Programación del Pipeline"],"New branch":["Nueva rama"],"New directory":["Nuevo directorio"],"New file":["Nuevo archivo"],"New issue":["Nueva incidencia"],"New merge request":["Nueva solicitud de fusión"],"New schedule":["Nueva programación"],"New snippet":["Nuevo fragmento de código"],"New tag":["Nueva etiqueta"],"No repository":["No hay repositorio"],"No schedules":["No hay programaciones"],"Not available":["No disponible"],"Not enough data":["No hay suficientes datos"],"Notification events":["Eventos de notificación"],"NotificationEvent|Close issue":["Cerrar incidencia"],"NotificationEvent|Close merge request":["Cerrar solicitud de fusión"],"NotificationEvent|Failed pipeline":["Pipeline fallido"],"NotificationEvent|Merge merge request":["Integrar solicitud de fusión"],"NotificationEvent|New issue":["Nueva incidencia"],"NotificationEvent|New merge request":["Nueva solicitud de fusión"],"NotificationEvent|New note":["Nueva nota"],"NotificationEvent|Reassign issue":["Reasignar incidencia"],"NotificationEvent|Reassign merge request":["Reasignar solicitud de fusión"],"NotificationEvent|Reopen issue":["Reabrir incidencia"],"NotificationEvent|Successful pipeline":["Pipeline exitoso"],"NotificationLevel|Custom":["Personalizado"],"NotificationLevel|Disabled":["Deshabilitado"],"NotificationLevel|Global":["Global"],"NotificationLevel|On mention":["Cuando me mencionan"],"NotificationLevel|Participate":["Participación"],"NotificationLevel|Watch":["Vigilancia"],"OfSearchInADropdown|Filter":["Filtrar"],"OpenedNDaysAgo|Opened":["Abierto"],"Options":["Opciones"],"Owner":["Propietario"],"Pipeline":["Pipeline"],"Pipeline Health":["Estado del Pipeline"],"Pipeline Schedule":["Programación del Pipeline"],"Pipeline Schedules":["Programaciones de los Pipelines"],"PipelineSchedules|Activated":["Activado"],"PipelineSchedules|Active":["Activos"],"PipelineSchedules|All":["Todos"],"PipelineSchedules|Inactive":["Inactivos"],"PipelineSchedules|Next Run":["Próxima Ejecución"],"PipelineSchedules|None":["Ninguno"],"PipelineSchedules|Provide a short description for this pipeline":["Proporcione una breve descripción para este pipeline"],"PipelineSchedules|Take ownership":["Tomar posesión"],"PipelineSchedules|Target":["Destino"],"PipelineSheduleIntervalPattern|Custom":["Personalizado"],"Pipeline|with stage":["con etapa"],"Pipeline|with stages":["con etapas"],"Project '%{project_name}' queued for deletion.":["Proyecto ‘%{project_name}’ en cola para eliminación."],"Project '%{project_name}' was successfully created.":["Proyecto ‘%{project_name}’ fue creado satisfactoriamente."],"Project '%{project_name}' was successfully updated.":["Proyecto ‘%{project_name}’ fue actualizado satisfactoriamente."],"Project '%{project_name}' will be deleted.":["Proyecto ‘%{project_name}’ será eliminado."],"Project access must be granted explicitly to each user.":["El acceso al proyecto debe concederse explícitamente a cada usuario."],"Project export could not be deleted.":["No se pudo eliminar la exportación del proyecto."],"Project export has been deleted.":["La exportación del proyecto ha sido eliminada."],"Project export link has expired. Please generate a new export from your project settings.":["El enlace de exportación del proyecto ha caducado. Por favor, genera una nueva exportación desde la configuración del proyecto."],"Project export started. A download link will be sent by email.":["Se inició la exportación del proyecto. Se enviará un enlace de descarga por correo electrónico."],"Project home":["Inicio del proyecto"],"ProjectFeature|Disabled":["Deshabilitada"],"ProjectFeature|Everyone with access":["Todos con acceso"],"ProjectFeature|Only team members":["Solo miembros del equipo"],"ProjectFileTree|Name":["Nombre"],"ProjectLastActivity|Never":["Nunca"],"ProjectLifecycle|Stage":["Etapa"],"ProjectNetworkGraph|Graph":["Historial gráfico"],"Read more":["Leer más"],"Readme":["Léeme"],"RefSwitcher|Branches":["Ramas"],"RefSwitcher|Tags":["Etiquetas"],"Related Commits":["Cambios Relacionados"],"Related Deployed Jobs":["Trabajos Desplegados Relacionados"],"Related Issues":["Incidencias Relacionadas"],"Related Jobs":["Trabajos Relacionados"],"Related Merge Requests":["Solicitudes de fusión Relacionadas"],"Related Merged Requests":["Solicitudes de fusión Relacionadas"],"Remind later":["Recordar después"],"Remove project":["Eliminar proyecto"],"Request Access":["Solicitar acceso"],"Revert this commit":["Revertir este cambio"],"Revert this merge request":["Revertir esta solicitud de fusión"],"Save pipeline schedule":["Guardar programación del pipeline"],"Schedule a new pipeline":["Programar un nuevo pipeline"],"Scheduling Pipelines":["Programación de Pipelines"],"Search branches and tags":["Buscar ramas y etiquetas"],"Select Archive Format":["Seleccionar formato de archivo"],"Select a timezone":["Selecciona una zona horaria"],"Select target branch":["Selecciona una rama de destino"],"Set a password on your account to pull or push via %{protocol}":["Establezca una contraseña en su cuenta para actualizar o enviar a través de %{protocol}"],"Set up CI":["Configurar CI"],"Set up Koding":["Configurar Koding"],"Set up auto deploy":["Configurar auto despliegue"],"SetPasswordToCloneLink|set a password":["establecer una contraseña"],"Showing %d event":["Mostrando %d evento","Mostrando %d eventos"],"Source code":["Código fuente"],"StarProject|Star":["Destacar"],"Start a %{new_merge_request} with these changes":["Iniciar una %{new_merge_request} con estos cambios"],"Switch branch/tag":["Cambiar rama/etiqueta"],"Tag":["Etiqueta","Etiquetas"],"Tags":["Etiquetas"],"Target Branch":["Rama de destino"],"The coding stage shows the time from the first commit to creating the merge request. The data will automatically be added here once you create your first merge request.":["La etapa de desarrollo muestra el tiempo desde el primer cambio hasta la creación de la solicitud de fusión. Los datos serán automáticamente incorporados aquí una vez creada tu primera solicitud de fusión."],"The collection of events added to the data gathered for that stage.":["La colección de eventos agregados a los datos recopilados para esa etapa."],"The fork relationship has been removed.":["La relación con la bifurcación se ha eliminado."],"The issue stage shows the time it takes from creating an issue to assigning the issue to a milestone, or add the issue to a list on your Issue Board. Begin creating issues to see data for this stage.":["La etapa de incidencia muestra el tiempo que toma desde la creación de un tema hasta asignar el tema a un hito, o añadir el tema a una lista en el panel de temas. Empieza a crear temas para ver los datos de esta etapa."],"The phase of the development lifecycle.":["La etapa del ciclo de vida de desarrollo."],"The pipelines schedule runs pipelines in the future, repeatedly, for specific branches or tags. Those scheduled pipelines will inherit limited project access based on their associated user.":["La programación de pipelines ejecuta pipelines en el futuro, repetidamente, para ramas o etiquetas específicas. Los pipelines programados heredarán acceso limitado al proyecto basado en su usuario asociado."],"The planning stage shows the time from the previous step to pushing your first commit. This time will be added automatically once you push your first commit.":["La etapa de planificación muestra el tiempo desde el paso anterior hasta el envío de tu primera confirmación. Este tiempo se añadirá automáticamente una vez que usted envíe el primer cambio."],"The production stage shows the total time it takes between creating an issue and deploying the code to production. The data will be automatically added once you have completed the full idea to production cycle.":["La etapa de producción muestra el tiempo total que tarda entre la creación de una incidencia y el despliegue del código a producción. Los datos se añadirán automáticamente una vez haya finalizado por completo el ciclo de idea a producción."],"The project can be accessed by any logged in user.":["El proyecto puede ser accedido por cualquier usuario conectado."],"The project can be accessed without any authentication.":["El proyecto puede accederse sin ninguna autenticación."],"The repository for this project does not exist.":["El repositorio para este proyecto no existe."],"The review stage shows the time from creating the merge request to merging it. The data will automatically be added after you merge your first merge request.":["La etapa de revisión muestra el tiempo desde la creación de la solicitud de fusión hasta que los cambios se fusionaron. Los datos se añadirán automáticamente después de fusionar su primera solicitud de fusión."],"The staging stage shows the time between merging the MR and deploying code to the production environment. The data will be automatically added once you deploy to production for the first time.":["La etapa de puesta en escena muestra el tiempo entre la fusión y el despliegue de código en el entorno de producción. Los datos se añadirán automáticamente una vez que se despliega a producción por primera vez."],"The testing stage shows the time GitLab CI takes to run every pipeline for the related merge request. The data will automatically be added after your first pipeline finishes running.":["La etapa de pruebas muestra el tiempo que GitLab CI toma para ejecutar cada pipeline para la solicitud de fusión relacionada. Los datos se añadirán automáticamente luego de que el primer pipeline termine de ejecutarse."],"The time taken by each data entry gathered by that stage.":["El tiempo utilizado por cada entrada de datos obtenido por esa etapa."],"The value lying at the midpoint of a series of observed values. E.g., between 3, 5, 9, the median is 5. Between 3, 5, 7, 8, the median is (5+7)/2 = 6.":["El valor en el punto medio de una serie de valores observados. Por ejemplo, entre 3, 5, 9, la mediana es 5. Entre 3, 5, 7, 8, la mediana es (5 + 7) / 2 = 6."],"This means you can not push code until you create an empty repository or import existing one.":["Esto significa que no puede enviar código hasta que cree un repositorio vacío o importe uno existente."],"Time before an issue gets scheduled":["Tiempo antes de que una incidencia sea programada"],"Time before an issue starts implementation":["Tiempo antes de que empieze la implementación de una incidencia"],"Time between merge request creation and merge/close":["Tiempo entre la creación de la solicitud de fusión y la integración o cierre de ésta"],"Time until first merge request":["Tiempo hasta la primera solicitud de fusión"],"Timeago|%s days ago":["hace %s días"],"Timeago|%s days remaining":["%s días restantes"],"Timeago|%s hours remaining":["%s horas restantes"],"Timeago|%s minutes ago":["hace %s minutos"],"Timeago|%s minutes remaining":["%s minutos restantes"],"Timeago|%s months ago":["hace %s meses"],"Timeago|%s months remaining":["%s meses restantes"],"Timeago|%s seconds remaining":["%s segundos restantes"],"Timeago|%s weeks ago":["hace %s semanas"],"Timeago|%s weeks remaining":["%s semanas restantes"],"Timeago|%s years ago":["hace %s años"],"Timeago|%s years remaining":["%s años restantes"],"Timeago|1 day remaining":["1 día restante"],"Timeago|1 hour remaining":["1 hora restante"],"Timeago|1 minute remaining":["1 minuto restante"],"Timeago|1 month remaining":["1 mes restante"],"Timeago|1 week remaining":["1 semana restante"],"Timeago|1 year remaining":["1 año restante"],"Timeago|Past due":["Atrasado"],"Timeago|a day ago":["hace un día"],"Timeago|a month ago":["hace un mes"],"Timeago|a week ago":["hace una semana"],"Timeago|a while":["hace un momento"],"Timeago|a year ago":["hace un año"],"Timeago|about %s hours ago":["hace alrededor de %s horas"],"Timeago|about a minute ago":["hace alrededor de 1 minuto"],"Timeago|about an hour ago":["hace alrededor de 1 hora"],"Timeago|in %s days":["en %s días"],"Timeago|in %s hours":["en %s horas"],"Timeago|in %s minutes":["en %s minutos"],"Timeago|in %s months":["en %s meses"],"Timeago|in %s seconds":["en %s segundos"],"Timeago|in %s weeks":["en %s semanas"],"Timeago|in %s years":["en %s años"],"Timeago|in 1 day":["en 1 día"],"Timeago|in 1 hour":["en 1 hora"],"Timeago|in 1 minute":["en 1 minuto"],"Timeago|in 1 month":["en 1 mes"],"Timeago|in 1 week":["en 1 semana"],"Timeago|in 1 year":["en 1 año"],"Timeago|less than a minute ago":["hace menos de 1 minuto"],"Time|hr":["hr","hrs"],"Time|min":["min","mins"],"Time|s":["s"],"Total Time":["Tiempo Total"],"Total test time for all commits/merges":["Tiempo total de pruebas para todos los cambios o integraciones"],"Unstar":["No Destacar"],"Upload New File":["Subir nuevo archivo"],"Upload file":["Subir archivo"],"UploadLink|click to upload":["Hacer clic para subir"],"Use your global notification setting":["Utiliza tu configuración de notificación global"],"View open merge request":["Ver solicitud de fusión abierta"],"VisibilityLevel|Internal":["Interno"],"VisibilityLevel|Private":["Privado"],"VisibilityLevel|Public":["Público"],"Want to see the data? Please ask an administrator for access.":["¿Quieres ver los datos? Por favor pide acceso al administrador."],"We don't have enough data to show this stage.":["No hay suficientes datos para mostrar en esta etapa."],"Withdraw Access Request":["Retirar Solicitud de Acceso"],"You are going to remove %{project_name_with_namespace}.\\nRemoved project CANNOT be restored!\\nAre you ABSOLUTELY sure?":["Va a eliminar %{project_name_with_namespace}.\\n¡El proyecto eliminado NO puede ser restaurado!\\n¿Estás TOTALMENTE seguro?"],"You are going to remove the fork relationship to source project %{forked_from_project}. Are you ABSOLUTELY sure?":["Vas a eliminar el enlace de la bifurcación con el proyecto original %{forked_from_project}. ¿Estás TOTALMENTE seguro?"],"You are going to transfer %{project_name_with_namespace} to another owner. Are you ABSOLUTELY sure?":["Vas a transferir %{project_name_with_namespace} a otro propietario. ¿Estás TOTALMENTE seguro?"],"You can only add files when you are on a branch":["Solo puedes agregar archivos cuando estás en una rama"],"You have reached your project limit":["Has alcanzado el límite de tu proyecto"],"You must sign in to star a project":["Debes iniciar sesión para destacar un proyecto"],"You need permission.":["Necesitas permisos."],"You will not get any notifications via email":["No recibirás ninguna notificación por correo electrónico"],"You will only receive notifications for the events you choose":["Solo recibirás notificaciones de los eventos que elijas"],"You will only receive notifications for threads you have participated in":["Solo recibirás notificaciones de los temas en los que has participado"],"You will receive notifications for any activity":["Recibirás notificaciones por cualquier actividad"],"You will receive notifications only for comments in which you were @mentioned":["Recibirás notificaciones solo para los comentarios en los que se te mencionó"],"You won't be able to pull or push project code via %{protocol} until you %{set_password_link} on your account":["No podrás actualizar o enviar código al proyecto a través de %{protocol} hasta que %{set_password_link} en tu cuenta"],"You won't be able to pull or push project code via SSH until you %{add_ssh_key_link} to your profile":["No podrás actualizar o enviar código al proyecto a través de SSH hasta que %{add_ssh_key_link} en su perfil"],"Your name":["Tu nombre"],"day":["día","días"],"new merge request":["nueva solicitud de fusión"],"notification emails":["correos electrónicos de notificación"],"parent":["padre","padres"]}}};
\ No newline at end of file diff --git a/app/assets/javascripts/locale/zh_CN/app.js b/app/assets/javascripts/locale/zh_CN/app.js index d1335cfbc0f..9c28e4e4627 100644 --- a/app/assets/javascripts/locale/zh_CN/app.js +++ b/app/assets/javascripts/locale/zh_CN/app.js @@ -1 +1 @@ -var locales = locales || {}; locales['zh_CN'] = {"domain":"app","locale_data":{"app":{"":{"Project-Id-Version":"gitlab 1.0.0","Report-Msgid-Bugs-To":"","PO-Revision-Date":"2017-05-04 19:24-0500","Last-Translator":"HuangTao <htve@outlook.com>, 2017","Language-Team":"Chinese (China) (https://www.transifex.com/gitlab-zh/teams/75177/zh_CN/)","MIME-Version":"1.0","Content-Type":"text/plain; charset=UTF-8","Content-Transfer-Encoding":"8bit","Language":"zh_CN","Plural-Forms":"nplurals=1; plural=0;","lang":"zh_CN","domain":"app","plural_forms":"nplurals=1; plural=0;"},"Are you sure you want to delete this pipeline schedule?":[""],"ByAuthor|by":["作者:"],"Cancel":[""],"Commit":["提交"],"Cron Timezone":[""],"Cycle Analytics gives an overview of how much time it takes to go from idea to production in your project.":["周期分析概述了项目从想法到产品实现的各阶段所需的时间。"],"CycleAnalyticsStage|Code":["编码"],"CycleAnalyticsStage|Issue":["议题"],"CycleAnalyticsStage|Plan":["计划"],"CycleAnalyticsStage|Production":["生产"],"CycleAnalyticsStage|Review":["评审"],"CycleAnalyticsStage|Staging":["预发布"],"CycleAnalyticsStage|Test":["测试"],"Delete":[""],"Deploy":["部署"],"Description":[""],"Edit":[""],"Edit Pipeline Schedule %{id}":[""],"Failed to change the owner":[""],"Failed to remove the pipeline schedule":[""],"Filter":[""],"FirstPushedBy|First":["首次推送"],"FirstPushedBy|pushed by":["推送者:"],"From issue creation until deploy to production":["从创建议题到部署至生产环境"],"From merge request merge until deploy to production":["从合并请求被合并后到部署至生产环境"],"Interval Pattern":[""],"Introducing Cycle Analytics":["周期分析简介"],"Last %d day":["最后 %d 天"],"Last Pipeline":[""],"Limited to showing %d event at most":["最多显示 %d 个事件"],"Median":["中位数"],"New Issue":["新议题"],"New Pipeline Schedule":[""],"No schedules":[""],"Not available":["数据不足"],"Not enough data":["数据不足"],"OpenedNDaysAgo|Opened":["开始于"],"Owner":[""],"Pipeline Health":["流水线健康指标"],"Pipeline Schedule":[""],"Pipeline Schedules":[""],"PipelineSchedules|Activated":[""],"PipelineSchedules|Active":[""],"PipelineSchedules|All":[""],"PipelineSchedules|Inactive":[""],"PipelineSchedules|Next Run":[""],"PipelineSchedules|None":[""],"PipelineSchedules|Provide a short description for this pipeline":[""],"PipelineSchedules|Take ownership":[""],"PipelineSchedules|Target":[""],"ProjectLifecycle|Stage":["项目生命周期"],"Read more":["了解更多"],"Related Commits":["相关的提交"],"Related Deployed Jobs":["相关的部署作业"],"Related Issues":["相关的议题"],"Related Jobs":["相关的作业"],"Related Merge Requests":["相关的合并请求"],"Related Merged Requests":["相关已合并的合并请求"],"Save pipeline schedule":[""],"Schedule a new pipeline":[""],"Select a timezone":[""],"Select target branch":[""],"Showing %d event":["显示 %d 个事件"],"Target Branch":[""],"The coding stage shows the time from the first commit to creating the merge request. The data will automatically be added here once you create your first merge request.":["编码阶段概述了从第一次提交到创建合并请求的时间。创建第一个合并请求后,数据将自动添加到此处。"],"The collection of events added to the data gathered for that stage.":["与该阶段相关的事件。"],"The issue stage shows the time it takes from creating an issue to assigning the issue to a milestone, or add the issue to a list on your Issue Board. Begin creating issues to see data for this stage.":["议题阶段概述了从创建议题到将议题设置里程碑或将议题添加到议题看板的时间。开始创建议题以查看此阶段的数据。"],"The phase of the development lifecycle.":["项目生命周期中的各个阶段。"],"The planning stage shows the time from the previous step to pushing your first commit. This time will be added automatically once you push your first commit.":["计划阶段概述了从议题添加到日程后到推送首次提交的时间。当首次推送提交后,数据将自动添加到此处。"],"The production stage shows the total time it takes between creating an issue and deploying the code to production. The data will be automatically added once you have completed the full idea to production cycle.":["生产阶段概述了从创建一个议题到将代码部署到生产环境的总时间。当完成想法到部署生产的循环,数据将自动添加到此处。"],"The review stage shows the time from creating the merge request to merging it. The data will automatically be added after you merge your first merge request.":["评审阶段概述了从创建合并请求到被合并的时间。当创建第一个合并请求后,数据将自动添加到此处。"],"The staging stage shows the time between merging the MR and deploying code to the production environment. The data will be automatically added once you deploy to production for the first time.":["预发布阶段概述了从合并请求被合并到部署至生产环境的总时间。首次部署到生产环境后,数据将自动添加到此处。"],"The testing stage shows the time GitLab CI takes to run every pipeline for the related merge request. The data will automatically be added after your first pipeline finishes running.":["测试阶段概述了GitLab CI为相关合并请求运行每个流水线所需的时间。当第一个流水线运行完成后,数据将自动添加到此处。"],"The time taken by each data entry gathered by that stage.":["该阶段每条数据所花的时间"],"The value lying at the midpoint of a series of observed values. E.g., between 3, 5, 9, the median is 5. Between 3, 5, 7, 8, the median is (5+7)/2 = 6.":["中位数是一个数列中最中间的值。例如在 3、5、9 之间,中位数是 5。在 3、5、7、8 之间,中位数是 (5 + 7)/ 2 = 6。"],"Time before an issue gets scheduled":["议题被列入日程表的时间"],"Time before an issue starts implementation":["开始进行编码前的时间"],"Time between merge request creation and merge/close":["从创建合并请求到被合并或关闭的时间"],"Time until first merge request":["创建第一个合并请求之前的时间"],"Time|hr":["小时"],"Time|min":["分钟"],"Time|s":["秒"],"Total Time":["总时间"],"Total test time for all commits/merges":["所有提交和合并的总测试时间"],"Want to see the data? Please ask an administrator for access.":["权限不足。如需查看相关数据,请向管理员申请权限。"],"We don't have enough data to show this stage.":["该阶段的数据不足,无法显示。"],"You need permission.":["您需要相关的权限。"],"day":["天"]}}};
\ No newline at end of file +var locales = locales || {}; locales['zh_CN'] = {"domain":"app","locale_data":{"app":{"":{"Project-Id-Version":"gitlab 1.0.0","Report-Msgid-Bugs-To":"","POT-Creation-Date":"2017-06-15 21:59-0500","MIME-Version":"1.0","Content-Type":"text/plain; charset=UTF-8","Content-Transfer-Encoding":"8bit","PO-Revision-Date":"2017-06-19 09:57-0400","Last-Translator":"Huang Tao <htve@outlook.com>","Language-Team":"Chinese (China) (https://translate.zanata.org/project/view/GitLab)","Language":"zh-CN","X-Generator":"Zanata 3.9.6","Plural-Forms":"nplurals=1; plural=0","lang":"zh_CN","domain":"app","plural_forms":"nplurals=1; plural=0"},"%{commit_author_link} committed %{commit_timeago}":["由 %{commit_author_link} 提交于 %{commit_timeago}"],"About auto deploy":["关于自动部署"],"Active":["启用"],"Activity":["活动"],"Add Changelog":["添加更新日志"],"Add Contribution guide":["添加贡献指南"],"Add License":["添加许可证"],"Add an SSH key to your profile to pull or push via SSH.":["新建一个用于推送或拉取的 SSH 秘钥到账号中。"],"Add new directory":["添加目录"],"Archived project! Repository is read-only":["项目已归档!存储库为只读状态"],"Are you sure you want to delete this pipeline schedule?":["确定要删除此流水线计划吗?"],"Attach a file by drag & drop or %{upload_link}":["拖放文件到此处或者 %{upload_link}"],"Branch":["分支"],"Branch <strong>%{branch_name}</strong> was created. To set up auto deploy, choose a GitLab CI Yaml template and commit your changes. %{link_to_autodeploy_doc}":["已创建分支 <strong>%{branch_name}</strong> 。如需设置自动部署, 请选择合适的 GitLab CI Yaml 模板并提交更改。%{link_to_autodeploy_doc}"],"Branches":["分支"],"Browse files":["浏览文件"],"ByAuthor|by":["作者:"],"CI configuration":["CI 配置"],"Cancel":["取消"],"ChangeTypeActionLabel|Pick into branch":["选择分支"],"ChangeTypeActionLabel|Revert in branch":["还原分支"],"ChangeTypeAction|Cherry-pick":["优选"],"ChangeTypeAction|Revert":["还原"],"Changelog":["更新日志"],"Charts":["统计图"],"Cherry-pick this commit":["优选此提交"],"Cherry-pick this merge request":["优选此合并请求"],"CiStatusLabel|canceled":["已取消"],"CiStatusLabel|created":["已创建"],"CiStatusLabel|failed":["已失败"],"CiStatusLabel|manual action":["手动操作"],"CiStatusLabel|passed":["已通过"],"CiStatusLabel|passed with warnings":["已通过但有警告"],"CiStatusLabel|pending":["等待中"],"CiStatusLabel|skipped":["已跳过"],"CiStatusLabel|waiting for manual action":["等待手动操作"],"CiStatusText|blocked":["已阻塞"],"CiStatusText|canceled":["已取消"],"CiStatusText|created":["已创建"],"CiStatusText|failed":["已失败"],"CiStatusText|manual":["手动操作"],"CiStatusText|passed":["已通过"],"CiStatusText|pending":["等待中"],"CiStatusText|skipped":["已跳过"],"CiStatus|running":["运行中"],"Commit":["提交"],"Commit message":["提交信息"],"CommitBoxTitle|Commit":["提交"],"CommitMessage|Add %{file_name}":["添加 %{file_name}"],"Commits":["提交"],"Commits|History":["历史"],"Committed by":["提交者:"],"Compare":["比较"],"Contribution guide":["贡献指南"],"Contributors":["贡献者"],"Copy URL to clipboard":["复制 URL 到剪贴板"],"Copy commit SHA to clipboard":["复制提交 SHA 的值到剪贴板"],"Create New Directory":["创建新目录"],"Create directory":["创建目录"],"Create empty bare repository":["创建空的存储库"],"Create merge request":["创建合并请求"],"Create new...":["创建..."],"CreateNewFork|Fork":["派生"],"CreateTag|Tag":["标签"],"Cron Timezone":["Cron 时区"],"Cron syntax":["Cron 语法"],"Custom notification events":["自定义通知事件"],"Custom notification levels are the same as participating levels. With custom notification levels you will also receive notifications for select events. To find out more, check out %{notification_link}.":["自定义通知级别继承自参与级别。使用自定义通知级别,您会收到参与级别及选定事件的通知。想了解更多信息,请查看 %{notification_link}."],"Cycle Analytics":["周期分析"],"Cycle Analytics gives an overview of how much time it takes to go from idea to production in your project.":["周期分析概述了项目从想法到产品实现的各阶段所需的时间。"],"CycleAnalyticsStage|Code":["编码"],"CycleAnalyticsStage|Issue":["议题"],"CycleAnalyticsStage|Plan":["计划"],"CycleAnalyticsStage|Production":["生产"],"CycleAnalyticsStage|Review":["评审"],"CycleAnalyticsStage|Staging":["预发布"],"CycleAnalyticsStage|Test":["测试"],"Define a custom pattern with cron syntax":["使用 Cron 语法定义自定义模式"],"Delete":["删除"],"Deploy":["部署"],"Description":["描述"],"Directory name":["目录名称"],"Don't show again":["不再显示"],"Download":["下载"],"Download tar":["下载 tar"],"Download tar.bz2":["下载 tar.bz2"],"Download tar.gz":["下载 tar.gz"],"Download zip":["下载 zip"],"DownloadArtifacts|Download":["下载"],"DownloadCommit|Email Patches":["电子邮件补丁"],"DownloadCommit|Plain Diff":["差异文件"],"DownloadSource|Download":["下载"],"Edit":["编辑"],"Edit Pipeline Schedule %{id}":["编辑 %{id} 流水线计划"],"Every day (at 4:00am)":["每日执行(凌晨 4 点)"],"Every month (on the 1st at 4:00am)":["每月执行(每月 1 日凌晨 4 点)"],"Every week (Sundays at 4:00am)":["每周执行(周日凌晨 4 点)"],"Failed to change the owner":["无法变更所有者"],"Failed to remove the pipeline schedule":["无法删除流水线计划"],"Files":["文件"],"Find by path":["按路径查找"],"Find file":["查找文件"],"FirstPushedBy|First":["首次推送"],"FirstPushedBy|pushed by":["推送者:"],"Fork":["派生"],"ForkedFromProjectPath|Forked from":["派生自"],"From issue creation until deploy to production":["从创建议题到部署至生产环境"],"From merge request merge until deploy to production":["从合并请求被合并后到部署至生产环境"],"Go to your fork":["跳转到派生项目"],"GoToYourFork|Fork":["跳转到派生项目"],"Home":["首页"],"Housekeeping successfully started":["已开始维护"],"Import repository":["导入存储库"],"Interval Pattern":["循环周期"],"Introducing Cycle Analytics":["周期分析简介"],"LFSStatus|Disabled":["停用"],"LFSStatus|Enabled":["启用"],"Last %d day":["最近 %d 天"],"Last Pipeline":["最新流水线"],"Last Update":["最后更新"],"Last commit":["最后提交"],"Learn more in the":["了解更多"],"Learn more in the|pipeline schedules documentation":["流水线计划文档"],"Leave group":["退出群组"],"Leave project":["退出项目"],"Limited to showing %d event at most":["最多显示 %d 个事件"],"Median":["中位数"],"MissingSSHKeyWarningLink|add an SSH key":["新建 SSH 公钥"],"New Issue":["新建议题"],"New Pipeline Schedule":["创建流水线计划"],"New branch":["新建分支"],"New directory":["新建目录"],"New file":["新建文件"],"New issue":["新建议题"],"New merge request":["新建合并请求"],"New schedule":["新建计划"],"New snippet":["新建代码片段"],"New tag":["新建标签"],"No repository":["没有存储库"],"No schedules":["没有计划"],"Not available":["数据不足"],"Not enough data":["数据不足"],"Notification events":["通知事件"],"NotificationEvent|Close issue":["关闭议题"],"NotificationEvent|Close merge request":["关闭合并请求"],"NotificationEvent|Failed pipeline":["流水线失败"],"NotificationEvent|Merge merge request":["合并请求被合并"],"NotificationEvent|New issue":["新建议题"],"NotificationEvent|New merge request":["新建合并请求"],"NotificationEvent|New note":["新建评论"],"NotificationEvent|Reassign issue":["重新指派议题"],"NotificationEvent|Reassign merge request":["重新指派合并请求"],"NotificationEvent|Reopen issue":["重启议题"],"NotificationEvent|Successful pipeline":["流水线成功完成"],"NotificationLevel|Custom":["自定义"],"NotificationLevel|Disabled":["停用"],"NotificationLevel|Global":["全局"],"NotificationLevel|On mention":["提及"],"NotificationLevel|Participate":["参与"],"NotificationLevel|Watch":["关注"],"OfSearchInADropdown|Filter":["筛选"],"OpenedNDaysAgo|Opened":["开始于"],"Options":["操作"],"Owner":["所有者"],"Pipeline":["流水线"],"Pipeline Health":["流水线健康指标"],"Pipeline Schedule":["流水线计划"],"Pipeline Schedules":["流水线计划"],"PipelineSchedules|Activated":["是否启用"],"PipelineSchedules|Active":["已启用"],"PipelineSchedules|All":["所有"],"PipelineSchedules|Inactive":["未启用"],"PipelineSchedules|Next Run":["下次运行时间"],"PipelineSchedules|None":["无"],"PipelineSchedules|Provide a short description for this pipeline":["为此流水线提供简短描述"],"PipelineSchedules|Take ownership":["取得所有者"],"PipelineSchedules|Target":["目标"],"PipelineSheduleIntervalPattern|Custom":["自定义"],"Pipeline|with stage":["于阶段"],"Pipeline|with stages":["于阶段"],"Project '%{project_name}' queued for deletion.":["项目 '%{project_name}' 已进入删除队列。"],"Project '%{project_name}' was successfully created.":["项目 '%{project_name}' 已创建成功。"],"Project '%{project_name}' was successfully updated.":["项目 '%{project_name}' 已更新完成。"],"Project '%{project_name}' will be deleted.":["项目 '%{project_name}' 将被删除。"],"Project access must be granted explicitly to each user.":["项目访问权限必须明确授权给每个用户。"],"Project export could not be deleted.":["无法删除项目导出。"],"Project export has been deleted.":["项目导出已被删除。"],"Project export link has expired. Please generate a new export from your project settings.":["项目导出链接已过期。请从项目设置中重新生成项目导出。"],"Project export started. A download link will be sent by email.":["项目导出已开始。下载链接将通过电子邮件发送。"],"Project home":["项目首页"],"ProjectFeature|Disabled":["停用"],"ProjectFeature|Everyone with access":["任何对项目有访问权的人"],"ProjectFeature|Only team members":["只限团队成员"],"ProjectFileTree|Name":["名称"],"ProjectLastActivity|Never":["从未"],"ProjectLifecycle|Stage":["阶段"],"ProjectNetworkGraph|Graph":["分支图"],"Read more":["了解更多"],"Readme":["自述文件"],"RefSwitcher|Branches":["分支"],"RefSwitcher|Tags":["标签"],"Related Commits":["相关的提交"],"Related Deployed Jobs":["相关的部署作业"],"Related Issues":["相关的议题"],"Related Jobs":["相关的作业"],"Related Merge Requests":["相关的合并请求"],"Related Merged Requests":["相关已合并的合并请求"],"Remind later":["稍后提醒"],"Remove project":["删除项目"],"Request Access":["申请权限"],"Revert this commit":["还原此提交"],"Revert this merge request":["还原此合并请求"],"Save pipeline schedule":["保存流水线计划"],"Schedule a new pipeline":["新建流水线计划"],"Scheduling Pipelines":["流水线计划"],"Search branches and tags":["搜索分支和标签"],"Select Archive Format":["选择下载格式"],"Select a timezone":["选择时区"],"Select target branch":["选择目标分支"],"Set a password on your account to pull or push via %{protocol}":["为账号创建一个用于推送或拉取的 %{protocol} 密码。"],"Set up CI":["设置 CI"],"Set up Koding":["设置 Koding"],"Set up auto deploy":["设置自动部署"],"SetPasswordToCloneLink|set a password":["设置密码"],"Showing %d event":["显示 %d 个事件"],"Source code":["源代码"],"StarProject|Star":["星标"],"Start a %{new_merge_request} with these changes":["由此更改 %{new_merge_request}"],"Switch branch/tag":["切换分支/标签"],"Tag":["标签"],"Tags":["标签"],"Target Branch":["目标分支"],"The coding stage shows the time from the first commit to creating the merge request. The data will automatically be added here once you create your first merge request.":["编码阶段概述了从第一次提交到创建合并请求的时间。创建第一个合并请求后,数据将自动添加到此处。"],"The collection of events added to the data gathered for that stage.":["与该阶段相关的事件集合。"],"The fork relationship has been removed.":["派生关系已被删除。"],"The issue stage shows the time it takes from creating an issue to assigning the issue to a milestone, or add the issue to a list on your Issue Board. Begin creating issues to see data for this stage.":["议题阶段概述了从创建议题到将议题添加到里程碑或议题看板所花费的时间。创建第一个议题后,数据将自动添加到此处.。"],"The phase of the development lifecycle.":["项目生命周期中的各个阶段。"],"The pipelines schedule runs pipelines in the future, repeatedly, for specific branches or tags. Those scheduled pipelines will inherit limited project access based on their associated user.":["流水线计划会周期性重复运行指定分支或标签的流水线。这些流水线将根据其关联用户继承有限的项目访问权限。"],"The planning stage shows the time from the previous step to pushing your first commit. This time will be added automatically once you push your first commit.":["计划阶段概述了从议题添加到日程到推送首次提交的时间。当首次推送提交后,数据将自动添加到此处。"],"The production stage shows the total time it takes between creating an issue and deploying the code to production. The data will be automatically added once you have completed the full idea to production cycle.":["生产阶段概述了从创建一个议题到将代码部署到生产环境的总时间。当完成想法到部署生产的循环,数据将自动添加到此处。"],"The project can be accessed by any logged in user.":["该项目允许已登录的用户访问。"],"The project can be accessed without any authentication.":["该项目允许任何人访问。"],"The repository for this project does not exist.":["此项目的存储库不存在。"],"The review stage shows the time from creating the merge request to merging it. The data will automatically be added after you merge your first merge request.":["评审阶段概述了从创建合并请求到被合并的时间。当创建第一个合并请求后,数据将自动添加到此处。"],"The staging stage shows the time between merging the MR and deploying code to the production environment. The data will be automatically added once you deploy to production for the first time.":["预发布阶段概述了从合并请求被合并到部署至生产环境的总时间。首次部署到生产环境后,数据将自动添加到此处。"],"The testing stage shows the time GitLab CI takes to run every pipeline for the related merge request. The data will automatically be added after your first pipeline finishes running.":["测试阶段概述了 GitLab CI 为相关合并请求运行每个流水线所需的时间。当第一个流水线运行完成后,数据将自动添加到此处。"],"The time taken by each data entry gathered by that stage.":["该阶段每条数据所花的时间"],"The value lying at the midpoint of a series of observed values. E.g., between 3, 5, 9, the median is 5. Between 3, 5, 7, 8, the median is (5+7)/2 = 6.":["中位数是一个数列中最中间的值。例如在 3、5、9 之间,中位数是 5。在 3、5、7、8 之间,中位数是 (5 + 7)/ 2 = 6。"],"This means you can not push code until you create an empty repository or import existing one.":["在创建一个空的存储库或导入现有存储库之前,将无法推送代码。"],"Time before an issue gets scheduled":["议题被列入日程表的时间"],"Time before an issue starts implementation":["开始进行编码前的时间"],"Time between merge request creation and merge/close":["从创建合并请求到被合并或关闭的时间"],"Time until first merge request":["创建第一个合并请求之前的时间"],"Timeago|%s days ago":[" %s 天前"],"Timeago|%s days remaining":["剩余 %s 天"],"Timeago|%s hours remaining":["剩余 %s 小时"],"Timeago|%s minutes ago":[" %s 分钟前"],"Timeago|%s minutes remaining":["剩余 %s 分钟"],"Timeago|%s months ago":[" %s 个月前"],"Timeago|%s months remaining":["剩余 %s 月"],"Timeago|%s seconds remaining":["剩余 %s 秒"],"Timeago|%s weeks ago":[" %s 星期前"],"Timeago|%s weeks remaining":["剩余 %s 星期"],"Timeago|%s years ago":[" %s 年前"],"Timeago|%s years remaining":["剩余 %s 年"],"Timeago|1 day remaining":["剩余 1 天"],"Timeago|1 hour remaining":["剩余 1 小时"],"Timeago|1 minute remaining":["剩余 1 分钟"],"Timeago|1 month remaining":["剩余 1 个月"],"Timeago|1 week remaining":["剩余 1 星期"],"Timeago|1 year remaining":["剩余 1 年"],"Timeago|Past due":["逾期"],"Timeago|a day ago":[" 1 天前"],"Timeago|a month ago":[" 1 个月前"],"Timeago|a week ago":[" 1 星期前"],"Timeago|a while":["刚刚"],"Timeago|a year ago":[" 1 年前"],"Timeago|about %s hours ago":["约 %s 小时前"],"Timeago|about a minute ago":["约 1 分钟前"],"Timeago|about an hour ago":["约 1 小时前"],"Timeago|in %s days":[" %s 天后"],"Timeago|in %s hours":[" %s 小时后"],"Timeago|in %s minutes":[" %s 分钟后"],"Timeago|in %s months":[" %s 个月后"],"Timeago|in %s seconds":[" %s 秒后"],"Timeago|in %s weeks":[" %s 星期后"],"Timeago|in %s years":[" %s 年后"],"Timeago|in 1 day":[" 1 天后"],"Timeago|in 1 hour":[" 1 小时后"],"Timeago|in 1 minute":[" 1 分钟后"],"Timeago|in 1 month":[" 1 月后"],"Timeago|in 1 week":[" 1 星期后"],"Timeago|in 1 year":[" 1 年后"],"Timeago|less than a minute ago":["不到 1 分钟前"],"Time|hr":["小时"],"Time|min":["分钟"],"Time|s":["秒"],"Total Time":["总时间"],"Total test time for all commits/merges":["所有提交和合并的总测试时间"],"Unstar":["取消星标"],"Upload New File":["上传新文件"],"Upload file":["上传文件"],"Use your global notification setting":["使用全局通知设置"],"VisibilityLevel|Internal":["内部"],"VisibilityLevel|Private":["私有"],"VisibilityLevel|Public":["公开"],"Want to see the data? Please ask an administrator for access.":["权限不足。如需查看相关数据,请向管理员申请权限。"],"We don't have enough data to show this stage.":["该阶段的数据不足,无法显示。"],"Withdraw Access Request":["取消权限申请"],"You are going to remove %{project_name_with_namespace}.\\nRemoved project CANNOT be restored!\\nAre you ABSOLUTELY sure?":["即将要删除 %{project_name_with_namespace}。\\n已删除的项目无法恢复!\\n确定继续吗?"],"You are going to remove the fork relationship to source project %{forked_from_project}. Are you ABSOLUTELY sure?":["即将删除与源项目 %{forked_from_project} 的派生关系。确定继续吗?"],"You are going to transfer %{project_name_with_namespace} to another owner. Are you ABSOLUTELY sure?":["即将 %{project_name_with_namespace} 转移给另一个所有者。确定继续吗?"],"You can only add files when you are on a branch":["只能在分支上添加文件"],"You have reached your project limit":["您已达到项目数量限制"],"You must sign in to star a project":["必须登录才能对项目加星标"],"You need permission.":["需要相关的权限。"],"You will not get any notifications via email":["不会收到任何通知邮件"],"You will only receive notifications for the events you choose":["只接收选择的事件通知"],"You will only receive notifications for threads you have participated in":["只接收参与的主题的通知"],"You will receive notifications for any activity":["接收所有活动的通知"],"You will receive notifications only for comments in which you were @mentioned":["只接收评论中提及(@)您的通知"],"You won't be able to pull or push project code via %{protocol} until you %{set_password_link} on your account":["在账号中 %{set_password_link} 之前将无法通过 %{protocol} 拉取或推送代码。"],"You won't be able to pull or push project code via SSH until you %{add_ssh_key_link} to your profile":["在账号中 %{add_ssh_key_link} 之前将无法通过 SSH 拉取或推送代码。"],"Your name":["您的名字"],"day":["天"],"new merge request":["新建合并请求"],"notification emails":["通知邮件"],"parent":["父级"]}}};
\ No newline at end of file diff --git a/app/assets/javascripts/merge_request_tabs.js b/app/assets/javascripts/merge_request_tabs.js index 7bb2236017e..786b6014dc6 100644 --- a/app/assets/javascripts/merge_request_tabs.js +++ b/app/assets/javascripts/merge_request_tabs.js @@ -155,7 +155,10 @@ import BlobForkSuggestion from './blob/blob_fork_suggestion'; scrollToElement(container) { if (location.hash) { - const offset = -$('.js-tabs-affix').outerHeight(); + const offset = 0 - ( + $('.navbar-gitlab').outerHeight() + + $('.js-tabs-affix').outerHeight() + ); const $el = $(`${container} ${location.hash}:not(.match)`); if ($el.length) { $.scrollTo($el[0], { offset }); @@ -291,7 +294,7 @@ import BlobForkSuggestion from './blob/blob_fork_suggestion'; // Scroll any linked note into view // Similar to `toggler_behavior` in the discussion tab const hash = window.gl.utils.getLocationHash(); - const anchor = hash && $container.find(`[id="${hash}"]`); + const anchor = hash && $container.find(`.note[id="${hash}"]`); if (anchor && anchor.length > 0) { const notesContent = anchor.closest('.notes_content'); const lineType = notesContent.hasClass('new') ? 'new' : 'old'; @@ -301,6 +304,7 @@ import BlobForkSuggestion from './blob/blob_fork_suggestion'; forceShow: true, }); anchor[0].scrollIntoView(); + window.gl.utils.handleLocationHash(); // We have multiple elements on the page with `#note_xxx` // (discussion and diff tabs) and `:target` only applies to the first anchor.addClass('target'); diff --git a/app/assets/javascripts/notes.js b/app/assets/javascripts/notes.js index 624dd336786..b21d7774920 100644 --- a/app/assets/javascripts/notes.js +++ b/app/assets/javascripts/notes.js @@ -4,7 +4,7 @@ no-unused-expressions, quotes, max-len, one-var, one-var-declaration-per-line, default-case, prefer-template, consistent-return, no-alert, no-return-assign, no-param-reassign, prefer-arrow-callback, no-else-return, comma-dangle, no-new, brace-style, no-lonely-if, vars-on-top, no-unused-vars, no-sequences, no-shadow, -newline-per-chained-call, no-useless-escape */ +newline-per-chained-call, no-useless-escape, class-methods-use-this */ /* global Flash */ /* global Autosave */ /* global ResolveService */ @@ -25,1507 +25,1489 @@ import './task_list'; window.autosize = autosize; window.Dropzone = Dropzone; -const normalizeNewlines = function(str) { +function normalizeNewlines(str) { return str.replace(/\r\n/g, '\n'); -}; - -(function() { - this.Notes = (function() { - const MAX_VISIBLE_COMMIT_LIST_COUNT = 3; - const REGEX_QUICK_ACTIONS = /^\/\w+.*$/gm; - - Notes.interval = null; - - function Notes(notes_url, note_ids, last_fetched_at, view, enableGFM = true) { - this.updateTargetButtons = this.updateTargetButtons.bind(this); - this.updateComment = this.updateComment.bind(this); - this.visibilityChange = this.visibilityChange.bind(this); - this.cancelDiscussionForm = this.cancelDiscussionForm.bind(this); - this.onAddDiffNote = this.onAddDiffNote.bind(this); - this.setupDiscussionNoteForm = this.setupDiscussionNoteForm.bind(this); - this.onReplyToDiscussionNote = this.onReplyToDiscussionNote.bind(this); - this.removeNote = this.removeNote.bind(this); - this.cancelEdit = this.cancelEdit.bind(this); - this.updateNote = this.updateNote.bind(this); - this.addDiscussionNote = this.addDiscussionNote.bind(this); - this.addNoteError = this.addNoteError.bind(this); - this.addNote = this.addNote.bind(this); - this.resetMainTargetForm = this.resetMainTargetForm.bind(this); - this.refresh = this.refresh.bind(this); - this.keydownNoteText = this.keydownNoteText.bind(this); - this.toggleCommitList = this.toggleCommitList.bind(this); - this.postComment = this.postComment.bind(this); - this.clearFlashWrapper = this.clearFlash.bind(this); - this.onHashChange = this.onHashChange.bind(this); - - this.notes_url = notes_url; - this.note_ids = note_ids; - this.enableGFM = enableGFM; - // Used to keep track of updated notes while people are editing things - this.updatedNotesTrackingMap = {}; - this.last_fetched_at = last_fetched_at; - this.noteable_url = document.URL; - this.notesCountBadge || (this.notesCountBadge = $('.issuable-details').find('.notes-tab .badge')); - this.basePollingInterval = 15000; - this.maxPollingSteps = 4; - - this.cleanBinding(); - this.addBinding(); - this.setPollingInterval(); - this.setupMainTargetNoteForm(); - this.taskList = new gl.TaskList({ - dataType: 'note', - fieldName: 'note', - selector: '.notes' - }); - this.collapseLongCommitList(); - this.setViewType(view); - - // We are in the Merge Requests page so we need another edit form for Changes tab - if (gl.utils.getPagePath(1) === 'merge_requests') { - $('.note-edit-form').clone() - .addClass('mr-note-edit-form').insertAfter('.note-edit-form'); - } +} + +const MAX_VISIBLE_COMMIT_LIST_COUNT = 3; +const REGEX_QUICK_ACTIONS = /^\/\w+.*$/gm; + +export default class Notes { + constructor(notes_url, note_ids, last_fetched_at, view, enableGFM = true) { + this.updateTargetButtons = this.updateTargetButtons.bind(this); + this.updateComment = this.updateComment.bind(this); + this.visibilityChange = this.visibilityChange.bind(this); + this.cancelDiscussionForm = this.cancelDiscussionForm.bind(this); + this.onAddDiffNote = this.onAddDiffNote.bind(this); + this.setupDiscussionNoteForm = this.setupDiscussionNoteForm.bind(this); + this.onReplyToDiscussionNote = this.onReplyToDiscussionNote.bind(this); + this.removeNote = this.removeNote.bind(this); + this.cancelEdit = this.cancelEdit.bind(this); + this.updateNote = this.updateNote.bind(this); + this.addDiscussionNote = this.addDiscussionNote.bind(this); + this.addNoteError = this.addNoteError.bind(this); + this.addNote = this.addNote.bind(this); + this.resetMainTargetForm = this.resetMainTargetForm.bind(this); + this.refresh = this.refresh.bind(this); + this.keydownNoteText = this.keydownNoteText.bind(this); + this.toggleCommitList = this.toggleCommitList.bind(this); + this.postComment = this.postComment.bind(this); + this.clearFlashWrapper = this.clearFlash.bind(this); + this.onHashChange = this.onHashChange.bind(this); + + this.notes_url = notes_url; + this.note_ids = note_ids; + this.enableGFM = enableGFM; + // Used to keep track of updated notes while people are editing things + this.updatedNotesTrackingMap = {}; + this.last_fetched_at = last_fetched_at; + this.noteable_url = document.URL; + this.notesCountBadge || (this.notesCountBadge = $('.issuable-details').find('.notes-tab .badge')); + this.basePollingInterval = 15000; + this.maxPollingSteps = 4; + + this.cleanBinding(); + this.addBinding(); + this.setPollingInterval(); + this.setupMainTargetNoteForm(); + this.taskList = new gl.TaskList({ + dataType: 'note', + fieldName: 'note', + selector: '.notes' + }); + this.collapseLongCommitList(); + this.setViewType(view); + + // We are in the Merge Requests page so we need another edit form for Changes tab + if (gl.utils.getPagePath(1) === 'merge_requests') { + $('.note-edit-form').clone() + .addClass('mr-note-edit-form').insertAfter('.note-edit-form'); + } + } + + setViewType(view) { + this.view = Cookies.get('diff_view') || view; + } + + addBinding() { + // Edit note link + $(document).on('click', '.js-note-edit', this.showEditForm.bind(this)); + $(document).on('click', '.note-edit-cancel', this.cancelEdit); + // Reopen and close actions for Issue/MR combined with note form submit + $(document).on('click', '.js-comment-submit-button', this.postComment); + $(document).on('click', '.js-comment-save-button', this.updateComment); + $(document).on('keyup input', '.js-note-text', this.updateTargetButtons); + // resolve a discussion + $(document).on('click', '.js-comment-resolve-button', this.postComment); + // remove a note (in general) + $(document).on('click', '.js-note-delete', this.removeNote); + // delete note attachment + $(document).on('click', '.js-note-attachment-delete', this.removeAttachment); + // reset main target form when clicking discard + $(document).on('click', '.js-note-discard', this.resetMainTargetForm); + // update the file name when an attachment is selected + $(document).on('change', '.js-note-attachment-input', this.updateFormAttachment); + // reply to diff/discussion notes + $(document).on('click', '.js-discussion-reply-button', this.onReplyToDiscussionNote); + // add diff note + $(document).on('click', '.js-add-diff-note-button', this.onAddDiffNote); + // hide diff note form + $(document).on('click', '.js-close-discussion-note-form', this.cancelDiscussionForm); + // toggle commit list + $(document).on('click', '.system-note-commit-list-toggler', this.toggleCommitList); + // fetch notes when tab becomes visible + $(document).on('visibilitychange', this.visibilityChange); + // when issue status changes, we need to refresh data + $(document).on('issuable:change', this.refresh); + // ajax:events that happen on Form when actions like Reopen, Close are performed on Issues and MRs. + $(document).on('ajax:success', '.js-main-target-form', this.addNote); + $(document).on('ajax:success', '.js-discussion-note-form', this.addDiscussionNote); + $(document).on('ajax:success', '.js-main-target-form', this.resetMainTargetForm); + $(document).on('ajax:complete', '.js-main-target-form', this.reenableTargetFormSubmitButton); + // when a key is clicked on the notes + $(document).on('keydown', '.js-note-text', this.keydownNoteText); + // When the URL fragment/hash has changed, `#note_xxx` + return $(window).on('hashchange', this.onHashChange); + } + + cleanBinding() { + $(document).off('click', '.js-note-edit'); + $(document).off('click', '.note-edit-cancel'); + $(document).off('click', '.js-note-delete'); + $(document).off('click', '.js-note-attachment-delete'); + $(document).off('click', '.js-discussion-reply-button'); + $(document).off('click', '.js-add-diff-note-button'); + $(document).off('visibilitychange'); + $(document).off('keyup input', '.js-note-text'); + $(document).off('click', '.js-note-target-reopen'); + $(document).off('click', '.js-note-target-close'); + $(document).off('click', '.js-note-discard'); + $(document).off('keydown', '.js-note-text'); + $(document).off('click', '.js-comment-resolve-button'); + $(document).off('click', '.system-note-commit-list-toggler'); + $(document).off('ajax:success', '.js-main-target-form'); + $(document).off('ajax:success', '.js-discussion-note-form'); + $(document).off('ajax:complete', '.js-main-target-form'); + $(window).off('hashchange', this.onHashChange); + } + + static initCommentTypeToggle(form) { + const dropdownTrigger = form.querySelector('.js-comment-type-dropdown .dropdown-toggle'); + const dropdownList = form.querySelector('.js-comment-type-dropdown .dropdown-menu'); + const noteTypeInput = form.querySelector('#note_type'); + const submitButton = form.querySelector('.js-comment-type-dropdown .js-comment-submit-button'); + const closeButton = form.querySelector('.js-note-target-close'); + const reopenButton = form.querySelector('.js-note-target-reopen'); + + const commentTypeToggle = new CommentTypeToggle({ + dropdownTrigger, + dropdownList, + noteTypeInput, + submitButton, + closeButton, + reopenButton, + }); + + commentTypeToggle.initDroplab(); + } + + keydownNoteText(e) { + var $textarea, discussionNoteForm, editNote, myLastNote, myLastNoteEditBtn, newText, originalText; + if (gl.utils.isMetaKey(e)) { + return; } - Notes.prototype.setViewType = function(view) { - this.view = Cookies.get('diff_view') || view; - }; - - Notes.prototype.addBinding = function() { - // Edit note link - $(document).on('click', '.js-note-edit', this.showEditForm.bind(this)); - $(document).on('click', '.note-edit-cancel', this.cancelEdit); - // Reopen and close actions for Issue/MR combined with note form submit - $(document).on('click', '.js-comment-submit-button', this.postComment); - $(document).on('click', '.js-comment-save-button', this.updateComment); - $(document).on('keyup input', '.js-note-text', this.updateTargetButtons); - // resolve a discussion - $(document).on('click', '.js-comment-resolve-button', this.postComment); - // remove a note (in general) - $(document).on('click', '.js-note-delete', this.removeNote); - // delete note attachment - $(document).on('click', '.js-note-attachment-delete', this.removeAttachment); - // reset main target form when clicking discard - $(document).on('click', '.js-note-discard', this.resetMainTargetForm); - // update the file name when an attachment is selected - $(document).on('change', '.js-note-attachment-input', this.updateFormAttachment); - // reply to diff/discussion notes - $(document).on('click', '.js-discussion-reply-button', this.onReplyToDiscussionNote); - // add diff note - $(document).on('click', '.js-add-diff-note-button', this.onAddDiffNote); - // hide diff note form - $(document).on('click', '.js-close-discussion-note-form', this.cancelDiscussionForm); - // toggle commit list - $(document).on('click', '.system-note-commit-list-toggler', this.toggleCommitList); - // fetch notes when tab becomes visible - $(document).on('visibilitychange', this.visibilityChange); - // when issue status changes, we need to refresh data - $(document).on('issuable:change', this.refresh); - // ajax:events that happen on Form when actions like Reopen, Close are performed on Issues and MRs. - $(document).on('ajax:success', '.js-main-target-form', this.addNote); - $(document).on('ajax:success', '.js-discussion-note-form', this.addDiscussionNote); - $(document).on('ajax:success', '.js-main-target-form', this.resetMainTargetForm); - $(document).on('ajax:complete', '.js-main-target-form', this.reenableTargetFormSubmitButton); - // when a key is clicked on the notes - $(document).on('keydown', '.js-note-text', this.keydownNoteText); - // When the URL fragment/hash has changed, `#note_xxx` - return $(window).on('hashchange', this.onHashChange); - }; - - Notes.prototype.cleanBinding = function() { - $(document).off('click', '.js-note-edit'); - $(document).off('click', '.note-edit-cancel'); - $(document).off('click', '.js-note-delete'); - $(document).off('click', '.js-note-attachment-delete'); - $(document).off('click', '.js-discussion-reply-button'); - $(document).off('click', '.js-add-diff-note-button'); - $(document).off('visibilitychange'); - $(document).off('keyup input', '.js-note-text'); - $(document).off('click', '.js-note-target-reopen'); - $(document).off('click', '.js-note-target-close'); - $(document).off('click', '.js-note-discard'); - $(document).off('keydown', '.js-note-text'); - $(document).off('click', '.js-comment-resolve-button'); - $(document).off('click', '.system-note-commit-list-toggler'); - $(document).off('ajax:success', '.js-main-target-form'); - $(document).off('ajax:success', '.js-discussion-note-form'); - $(document).off('ajax:complete', '.js-main-target-form'); - $(window).off('hashchange', this.onHashChange); - }; - - Notes.initCommentTypeToggle = function (form) { - const dropdownTrigger = form.querySelector('.js-comment-type-dropdown .dropdown-toggle'); - const dropdownList = form.querySelector('.js-comment-type-dropdown .dropdown-menu'); - const noteTypeInput = form.querySelector('#note_type'); - const submitButton = form.querySelector('.js-comment-type-dropdown .js-comment-submit-button'); - const closeButton = form.querySelector('.js-note-target-close'); - const reopenButton = form.querySelector('.js-note-target-reopen'); - - const commentTypeToggle = new CommentTypeToggle({ - dropdownTrigger, - dropdownList, - noteTypeInput, - submitButton, - closeButton, - reopenButton, - }); - - commentTypeToggle.initDroplab(); - }; - - Notes.prototype.keydownNoteText = function(e) { - var $textarea, discussionNoteForm, editNote, myLastNote, myLastNoteEditBtn, newText, originalText; - if (gl.utils.isMetaKey(e)) { - return; - } - - $textarea = $(e.target); - // Edit previous note when UP arrow is hit - switch (e.which) { - case 38: + $textarea = $(e.target); + // Edit previous note when UP arrow is hit + switch (e.which) { + case 38: + if ($textarea.val() !== '') { + return; + } + myLastNote = $(`li.note[data-author-id='${gon.current_user_id}'][data-editable]:last`, $textarea.closest('.note, .notes_holder, #notes')); + if (myLastNote.length) { + myLastNoteEditBtn = myLastNote.find('.js-note-edit'); + return myLastNoteEditBtn.trigger('click', [true, myLastNote]); + } + break; + // Cancel creating diff note or editing any note when ESCAPE is hit + case 27: + discussionNoteForm = $textarea.closest('.js-discussion-note-form'); + if (discussionNoteForm.length) { if ($textarea.val() !== '') { - return; - } - myLastNote = $(`li.note[data-author-id='${gon.current_user_id}'][data-editable]:last`, $textarea.closest('.note, .notes_holder, #notes')); - if (myLastNote.length) { - myLastNoteEditBtn = myLastNote.find('.js-note-edit'); - return myLastNoteEditBtn.trigger('click', [true, myLastNote]); - } - break; - // Cancel creating diff note or editing any note when ESCAPE is hit - case 27: - discussionNoteForm = $textarea.closest('.js-discussion-note-form'); - if (discussionNoteForm.length) { - if ($textarea.val() !== '') { - if (!confirm('Are you sure you want to cancel creating this comment?')) { - return; - } + if (!confirm('Are you sure you want to cancel creating this comment?')) { + return; } - this.removeDiscussionNoteForm(discussionNoteForm); - return; } - editNote = $textarea.closest('.note'); - if (editNote.length) { - originalText = $textarea.closest('form').data('original-note'); - newText = $textarea.val(); - if (originalText !== newText) { - if (!confirm('Are you sure you want to cancel editing this comment?')) { - return; - } + this.removeDiscussionNoteForm(discussionNoteForm); + return; + } + editNote = $textarea.closest('.note'); + if (editNote.length) { + originalText = $textarea.closest('form').data('original-note'); + newText = $textarea.val(); + if (originalText !== newText) { + if (!confirm('Are you sure you want to cancel editing this comment?')) { + return; } - return this.removeNoteEditForm(editNote); } - } - }; + return this.removeNoteEditForm(editNote); + } + } + } - Notes.prototype.initRefresh = function() { + initRefresh() { + if (Notes.interval) { clearInterval(Notes.interval); - return Notes.interval = setInterval((function(_this) { - return function() { - return _this.refresh(); - }; - })(this), this.pollingInterval); - }; + } + return Notes.interval = setInterval((function(_this) { + return function() { + return _this.refresh(); + }; + })(this), this.pollingInterval); + } - Notes.prototype.refresh = function() { - if (!document.hidden) { - return this.getContent(); - } - }; + refresh() { + if (!document.hidden) { + return this.getContent(); + } + } - Notes.prototype.getContent = function() { - if (this.refreshing) { - return; - } - this.refreshing = true; - return $.ajax({ - url: this.notes_url, - headers: { 'X-Last-Fetched-At': this.last_fetched_at }, - dataType: 'json', - success: (function(_this) { - return function(data) { - var notes; - notes = data.notes; - _this.last_fetched_at = data.last_fetched_at; - _this.setPollingInterval(data.notes.length); - return $.each(notes, function(i, note) { - _this.renderNote(note); - }); - }; - })(this) - }).always((function(_this) { - return function() { - return _this.refreshing = false; + getContent() { + if (this.refreshing) { + return; + } + this.refreshing = true; + return $.ajax({ + url: this.notes_url, + headers: { 'X-Last-Fetched-At': this.last_fetched_at }, + dataType: 'json', + success: (function(_this) { + return function(data) { + var notes; + notes = data.notes; + _this.last_fetched_at = data.last_fetched_at; + _this.setPollingInterval(data.notes.length); + return $.each(notes, function(i, note) { + _this.renderNote(note); + }); }; - })(this)); - }; - - /* - Increase @pollingInterval up to 120 seconds on every function call, - if `shouldReset` has a truthy value, 'null' or 'undefined' the variable - will reset to @basePollingInterval. - - Note: this function is used to gradually increase the polling interval - if there aren't new notes coming from the server - */ - - Notes.prototype.setPollingInterval = function(shouldReset) { - var nthInterval; - if (shouldReset == null) { - shouldReset = true; - } - nthInterval = this.basePollingInterval * Math.pow(2, this.maxPollingSteps - 1); - if (shouldReset) { - this.pollingInterval = this.basePollingInterval; - } else if (this.pollingInterval < nthInterval) { - this.pollingInterval *= 2; + })(this) + }).always((function(_this) { + return function() { + return _this.refreshing = false; + }; + })(this)); + } + + /** + * Increase @pollingInterval up to 120 seconds on every function call, + * if `shouldReset` has a truthy value, 'null' or 'undefined' the variable + * will reset to @basePollingInterval. + * + * Note: this function is used to gradually increase the polling interval + * if there aren't new notes coming from the server + */ + setPollingInterval(shouldReset) { + var nthInterval; + if (shouldReset == null) { + shouldReset = true; + } + nthInterval = this.basePollingInterval * Math.pow(2, this.maxPollingSteps - 1); + if (shouldReset) { + this.pollingInterval = this.basePollingInterval; + } else if (this.pollingInterval < nthInterval) { + this.pollingInterval *= 2; + } + return this.initRefresh(); + } + + handleQuickActions(noteEntity) { + var votesBlock; + if (noteEntity.commands_changes) { + if ('merge' in noteEntity.commands_changes) { + Notes.checkMergeRequestStatus(); } - return this.initRefresh(); - }; - - Notes.prototype.handleQuickActions = function(noteEntity) { - var votesBlock; - if (noteEntity.commands_changes) { - if ('merge' in noteEntity.commands_changes) { - Notes.checkMergeRequestStatus(); - } - if ('emoji_award' in noteEntity.commands_changes) { - votesBlock = $('.js-awards-block').eq(0); - gl.awardsHandler.addAwardToEmojiBar(votesBlock, noteEntity.commands_changes.emoji_award); - return gl.awardsHandler.scrollToAwards(); - } + if ('emoji_award' in noteEntity.commands_changes) { + votesBlock = $('.js-awards-block').eq(0); + gl.awardsHandler.addAwardToEmojiBar(votesBlock, noteEntity.commands_changes.emoji_award); + return gl.awardsHandler.scrollToAwards(); } - }; - - Notes.prototype.setupNewNote = function($note) { - // Update datetime format on the recent note - gl.utils.localTimeAgo($note.find('.js-timeago'), false); - - this.collapseLongCommitList(); - this.taskList.init(); - - // This stops the note highlight, #note_xxx`, from being removed after real time update - // The `:target` selector does not re-evaluate after we replace element in the DOM - Notes.updateNoteTargetSelector($note); - this.$noteToCleanHighlight = $note; - }; - - Notes.prototype.onHashChange = function() { - if (this.$noteToCleanHighlight) { - Notes.updateNoteTargetSelector(this.$noteToCleanHighlight); - } - - this.$noteToCleanHighlight = null; - }; - - Notes.updateNoteTargetSelector = function($note) { - const hash = gl.utils.getLocationHash(); - // Needs to be an explicit true/false for the jQuery `toggleClass(force)` - const addTargetClass = Boolean(hash && $note.filter(`#${hash}`).length > 0); - $note.toggleClass('target', addTargetClass); - }; - - /* - Render note in main comments area. + } + } - Note: for rendering inline notes use renderDiscussionNote - */ + setupNewNote($note) { + // Update datetime format on the recent note + gl.utils.localTimeAgo($note.find('.js-timeago'), false); - Notes.prototype.renderNote = function(noteEntity, $form, $notesList = $('.main-notes-list')) { - if (noteEntity.discussion_html) { - return this.renderDiscussionNote(noteEntity, $form); - } + this.collapseLongCommitList(); + this.taskList.init(); - if (!noteEntity.valid) { - if (noteEntity.errors.commands_only) { - this.addFlash(noteEntity.errors.commands_only, 'notice', this.parentTimeline); - this.refresh(); - } - return; - } + // This stops the note highlight, #note_xxx`, from being removed after real time update + // The `:target` selector does not re-evaluate after we replace element in the DOM + Notes.updateNoteTargetSelector($note); + this.$noteToCleanHighlight = $note; + } - const $note = $notesList.find(`#note_${noteEntity.id}`); - if (Notes.isNewNote(noteEntity, this.note_ids)) { - this.note_ids.push(noteEntity.id); + onHashChange() { + if (this.$noteToCleanHighlight) { + Notes.updateNoteTargetSelector(this.$noteToCleanHighlight); + } - if ($notesList.length) { - $notesList.find('.system-note.being-posted').remove(); - } - const $newNote = Notes.animateAppendNote(noteEntity.html, $notesList); + this.$noteToCleanHighlight = null; + } + + static updateNoteTargetSelector($note) { + const hash = gl.utils.getLocationHash(); + // Needs to be an explicit true/false for the jQuery `toggleClass(force)` + const addTargetClass = Boolean(hash && $note.filter(`#${hash}`).length > 0); + $note.toggleClass('target', addTargetClass); + } + + /** + * Render note in main comments area. + * + * Note: for rendering inline notes use renderDiscussionNote + */ + renderNote(noteEntity, $form, $notesList = $('.main-notes-list')) { + if (noteEntity.discussion_html) { + return this.renderDiscussionNote(noteEntity, $form); + } - this.setupNewNote($newNote); + if (!noteEntity.valid) { + if (noteEntity.errors.commands_only) { + this.addFlash(noteEntity.errors.commands_only, 'notice', this.parentTimeline); this.refresh(); - return this.updateNotesCount(1); } - // The server can send the same update multiple times so we need to make sure to only update once per actual update. - else if (Notes.isUpdatedNote(noteEntity, $note)) { - const isEditing = $note.hasClass('is-editing'); - const initialContent = normalizeNewlines( - $note.find('.original-note-content').text().trim() - ); - const $textarea = $note.find('.js-note-text'); - const currentContent = $textarea.val(); - // There can be CRLF vs LF mismatches if we don't sanitize and compare the same way - const sanitizedNoteNote = normalizeNewlines(noteEntity.note); - const isTextareaUntouched = currentContent === initialContent || currentContent === sanitizedNoteNote; - - if (isEditing && isTextareaUntouched) { - $textarea.val(noteEntity.note); - this.updatedNotesTrackingMap[noteEntity.id] = noteEntity; - } - else if (isEditing && !isTextareaUntouched) { - this.putConflictEditWarningInPlace(noteEntity, $note); - this.updatedNotesTrackingMap[noteEntity.id] = noteEntity; - } - else { - const $updatedNote = Notes.animateUpdateNote(noteEntity.html, $note); - this.setupNewNote($updatedNote); - } - } - }; - - Notes.prototype.isParallelView = function() { - return Cookies.get('diff_view') === 'parallel'; - }; - - /* - Render note in discussion area. - - Note: for rendering inline notes use renderDiscussionNote - */ + return; + } - Notes.prototype.renderDiscussionNote = function(noteEntity, $form) { - var discussionContainer, form, row, lineType, diffAvatarContainer; - if (!Notes.isNewNote(noteEntity, this.note_ids)) { - return; - } + const $note = $notesList.find(`#note_${noteEntity.id}`); + if (Notes.isNewNote(noteEntity, this.note_ids)) { this.note_ids.push(noteEntity.id); - form = $form || $(`.js-discussion-note-form[data-discussion-id="${noteEntity.discussion_id}"]`); - row = form.closest('tr'); - lineType = this.isParallelView() ? form.find('#line_type').val() : 'old'; - diffAvatarContainer = row.prevAll('.line_holder').first().find('.js-avatar-container.' + lineType + '_line'); - // is this the first note of discussion? - discussionContainer = $(`.notes[data-discussion-id="${noteEntity.discussion_id}"]`); - if (!discussionContainer.length) { - discussionContainer = form.closest('.discussion').find('.notes'); - } - if (discussionContainer.length === 0) { - if (noteEntity.diff_discussion_html) { - var $discussion = $(noteEntity.diff_discussion_html).renderGFM(); - - if (!this.isParallelView() || row.hasClass('js-temp-notes-holder')) { - // insert the note and the reply button after the temp row - row.after($discussion); - } else { - // Merge new discussion HTML in - var $notes = $discussion.find(`.notes[data-discussion-id="${noteEntity.discussion_id}"]`); - var contentContainerClass = '.' + $notes.closest('.notes_content') - .attr('class') - .split(' ') - .join('.'); - - row.find(contentContainerClass + ' .content').append($notes.closest('.content').children()); - } - } - // Init discussion on 'Discussion' page if it is merge request page - const page = $('body').attr('data-page'); - if ((page && page.indexOf('projects:merge_request') !== -1) || !noteEntity.diff_discussion_html) { - Notes.animateAppendNote(noteEntity.discussion_html, $('.main-notes-list')); - } - } else { - // append new note to all matching discussions - Notes.animateAppendNote(noteEntity.html, discussionContainer); - } - if (typeof gl.diffNotesCompileComponents !== 'undefined' && noteEntity.discussion_resolvable) { - gl.diffNotesCompileComponents(); - this.renderDiscussionAvatar(diffAvatarContainer, noteEntity); + if ($notesList.length) { + $notesList.find('.system-note.being-posted').remove(); } + const $newNote = Notes.animateAppendNote(noteEntity.html, $notesList); - gl.utils.localTimeAgo($('.js-timeago'), false); - Notes.checkMergeRequestStatus(); + this.setupNewNote($newNote); + this.refresh(); return this.updateNotesCount(1); - }; - - Notes.prototype.getLineHolder = function(changesDiscussionContainer) { - return $(changesDiscussionContainer).closest('.notes_holder') - .prevAll('.line_holder') - .first() - .get(0); - }; - - Notes.prototype.renderDiscussionAvatar = function(diffAvatarContainer, noteEntity) { - var commentButton = diffAvatarContainer.find('.js-add-diff-note-button'); - var avatarHolder = diffAvatarContainer.find('.diff-comment-avatar-holders'); - - if (!avatarHolder.length) { - avatarHolder = document.createElement('diff-note-avatars'); - avatarHolder.setAttribute('discussion-id', noteEntity.discussion_id); - - diffAvatarContainer.append(avatarHolder); + } + // The server can send the same update multiple times so we need to make sure to only update once per actual update. + else if (Notes.isUpdatedNote(noteEntity, $note)) { + const isEditing = $note.hasClass('is-editing'); + const initialContent = normalizeNewlines( + $note.find('.original-note-content').text().trim() + ); + const $textarea = $note.find('.js-note-text'); + const currentContent = $textarea.val(); + // There can be CRLF vs LF mismatches if we don't sanitize and compare the same way + const sanitizedNoteNote = normalizeNewlines(noteEntity.note); + const isTextareaUntouched = currentContent === initialContent || currentContent === sanitizedNoteNote; - gl.diffNotesCompileComponents(); + if (isEditing && isTextareaUntouched) { + $textarea.val(noteEntity.note); + this.updatedNotesTrackingMap[noteEntity.id] = noteEntity; } - - if (commentButton.length) { - commentButton.remove(); + else if (isEditing && !isTextareaUntouched) { + this.putConflictEditWarningInPlace(noteEntity, $note); + this.updatedNotesTrackingMap[noteEntity.id] = noteEntity; } - }; - - /* - Called in response the main target form has been successfully submitted. - - Removes any errors. - Resets text and preview. - Resets buttons. - */ - - Notes.prototype.resetMainTargetForm = function(e) { - var form; - form = $('.js-main-target-form'); - // remove validation errors - form.find('.js-errors').remove(); - // reset text and preview - form.find('.js-md-write-button').click(); - form.find('.js-note-text').val('').trigger('input'); - form.find('.js-note-text').data('autosave').reset(); - - var event = document.createEvent('Event'); - event.initEvent('autosize:update', true, false); - form.find('.js-autosize')[0].dispatchEvent(event); - - this.updateTargetButtons(e); - }; - - Notes.prototype.reenableTargetFormSubmitButton = function() { - var form; - form = $('.js-main-target-form'); - return form.find('.js-note-text').trigger('input'); - }; - - /* - Shows the main form and does some setup on it. - - Sets some hidden fields in the form. - */ - - Notes.prototype.setupMainTargetNoteForm = function() { - var form; - // find the form - form = $('.js-new-note-form'); - // Set a global clone of the form for later cloning - this.formClone = form.clone(); - // show the form - this.setupNoteForm(form); - // fix classes - form.removeClass('js-new-note-form'); - form.addClass('js-main-target-form'); - form.find('#note_line_code').remove(); - form.find('#note_position').remove(); - form.find('#note_type').val(''); - form.find('#in_reply_to_discussion_id').remove(); - form.find('.js-comment-resolve-button').closest('comment-and-resolve-btn').remove(); - this.parentTimeline = form.parents('.timeline'); - - if (form.length) { - Notes.initCommentTypeToggle(form.get(0)); - } - }; - - /* - General note form setup. - - deactivates the submit button when text is empty - hides the preview button when text is empty - setup GFM auto complete - show the form - */ - - Notes.prototype.setupNoteForm = function(form) { - var textarea, key; - new gl.GLForm(form, this.enableGFM); - textarea = form.find('.js-note-text'); - key = [ - 'Note', - form.find('#note_noteable_type').val(), - form.find('#note_noteable_id').val(), - form.find('#note_commit_id').val(), - form.find('#note_type').val(), - form.find('#in_reply_to_discussion_id').val(), - - // LegacyDiffNote - form.find('#note_line_code').val(), - - // DiffNote - form.find('#note_position').val() - ]; - return new Autosave(textarea, key); - }; - - /* - Called in response to the new note form being submitted - - Adds new note to list. - */ - - Notes.prototype.addNote = function($form, note) { - return this.renderNote(note); - }; - - Notes.prototype.addNoteError = function($form) { - let formParentTimeline; - if ($form.hasClass('js-main-target-form')) { - formParentTimeline = $form.parents('.timeline'); - } else if ($form.hasClass('js-discussion-note-form')) { - formParentTimeline = $form.closest('.discussion-notes').find('.notes'); + else { + const $updatedNote = Notes.animateUpdateNote(noteEntity.html, $note); + this.setupNewNote($updatedNote); } - return this.addFlash('Your comment could not be submitted! Please check your network connection and try again.', 'alert', formParentTimeline); - }; - - Notes.prototype.updateNoteError = $parentTimeline => new Flash('Your comment could not be updated! Please check your network connection and try again.'); - - /* - Called in response to the new note form being submitted - - Adds new note to list. - */ - - Notes.prototype.addDiscussionNote = function($form, note, isNewDiffComment) { - if ($form.attr('data-resolve-all') != null) { - var projectPath = $form.data('project-path'); - var discussionId = $form.data('discussion-id'); - var mergeRequestId = $form.data('noteable-iid'); + } + } + + isParallelView() { + return Cookies.get('diff_view') === 'parallel'; + } + + /** + * Render note in discussion area. + * + * Note: for rendering inline notes use renderDiscussionNote + */ + renderDiscussionNote(noteEntity, $form) { + var discussionContainer, form, row, lineType, diffAvatarContainer; + if (!Notes.isNewNote(noteEntity, this.note_ids)) { + return; + } + this.note_ids.push(noteEntity.id); + form = $form || $(`.js-discussion-note-form[data-discussion-id="${noteEntity.discussion_id}"]`); + row = form.closest('tr'); + lineType = this.isParallelView() ? form.find('#line_type').val() : 'old'; + diffAvatarContainer = row.prevAll('.line_holder').first().find('.js-avatar-container.' + lineType + '_line'); + // is this the first note of discussion? + discussionContainer = $(`.notes[data-discussion-id="${noteEntity.discussion_id}"]`); + if (!discussionContainer.length) { + discussionContainer = form.closest('.discussion').find('.notes'); + } + if (discussionContainer.length === 0) { + if (noteEntity.diff_discussion_html) { + var $discussion = $(noteEntity.diff_discussion_html).renderGFM(); - if (ResolveService != null) { - ResolveService.toggleResolveForDiscussion(mergeRequestId, discussionId); + if (!this.isParallelView() || row.hasClass('js-temp-notes-holder')) { + // insert the note and the reply button after the temp row + row.after($discussion); + } else { + // Merge new discussion HTML in + var $notes = $discussion.find(`.notes[data-discussion-id="${noteEntity.discussion_id}"]`); + var contentContainerClass = '.' + $notes.closest('.notes_content') + .attr('class') + .split(' ') + .join('.'); + + row.find(contentContainerClass + ' .content').append($notes.closest('.content').children()); } } - - this.renderNote(note, $form); - // cleanup after successfully creating a diff/discussion note - if (isNewDiffComment) { - this.removeDiscussionNoteForm($form); + // Init discussion on 'Discussion' page if it is merge request page + const page = $('body').attr('data-page'); + if ((page && page.indexOf('projects:merge_request') !== -1) || !noteEntity.diff_discussion_html) { + Notes.animateAppendNote(noteEntity.discussion_html, $('.main-notes-list')); } - }; + } else { + // append new note to all matching discussions + Notes.animateAppendNote(noteEntity.html, discussionContainer); + } - /* - Called in response to the edit note form being submitted + if (typeof gl.diffNotesCompileComponents !== 'undefined' && noteEntity.discussion_resolvable) { + gl.diffNotesCompileComponents(); + this.renderDiscussionAvatar(diffAvatarContainer, noteEntity); + } - Updates the current note field. - */ + gl.utils.localTimeAgo($('.js-timeago'), false); + Notes.checkMergeRequestStatus(); + return this.updateNotesCount(1); + } - Notes.prototype.updateNote = function(noteEntity, $targetNote) { - var $noteEntityEl, $note_li; - // Convert returned HTML to a jQuery object so we can modify it further - $noteEntityEl = $(noteEntity.html); - $noteEntityEl.addClass('fade-in-full'); - this.revertNoteEditForm($targetNote); - $noteEntityEl.renderGFM(); - // Find the note's `li` element by ID and replace it with the updated HTML - $note_li = $('.note-row-' + noteEntity.id); + getLineHolder(changesDiscussionContainer) { + return $(changesDiscussionContainer).closest('.notes_holder') + .prevAll('.line_holder') + .first() + .get(0); + } - $note_li.replaceWith($noteEntityEl); - this.setupNewNote($noteEntityEl); + renderDiscussionAvatar(diffAvatarContainer, noteEntity) { + var commentButton = diffAvatarContainer.find('.js-add-diff-note-button'); + var avatarHolder = diffAvatarContainer.find('.diff-comment-avatar-holders'); - if (typeof gl.diffNotesCompileComponents !== 'undefined') { - gl.diffNotesCompileComponents(); - } - }; + if (!avatarHolder.length) { + avatarHolder = document.createElement('diff-note-avatars'); + avatarHolder.setAttribute('discussion-id', noteEntity.discussion_id); - Notes.prototype.checkContentToAllowEditing = function($el) { - var initialContent = $el.find('.original-note-content').text().trim(); - var currentContent = $el.find('.js-note-text').val(); - var isAllowed = true; + diffAvatarContainer.append(avatarHolder); - if (currentContent === initialContent) { - this.removeNoteEditForm($el); - } - else { - var $buttons = $el.find('.note-form-actions'); - var isWidgetVisible = gl.utils.isInViewport($el.get(0)); - - if (!isWidgetVisible) { - gl.utils.scrollToElement($el); - } + gl.diffNotesCompileComponents(); + } - $el.find('.js-finish-edit-warning').show(); - isAllowed = false; - } + if (commentButton.length) { + commentButton.remove(); + } + } + + /** + * Called in response the main target form has been successfully submitted. + * + * Removes any errors. + * Resets text and preview. + * Resets buttons. + */ + resetMainTargetForm(e) { + var form; + form = $('.js-main-target-form'); + // remove validation errors + form.find('.js-errors').remove(); + // reset text and preview + form.find('.js-md-write-button').click(); + form.find('.js-note-text').val('').trigger('input'); + form.find('.js-note-text').data('autosave').reset(); + + var event = document.createEvent('Event'); + event.initEvent('autosize:update', true, false); + form.find('.js-autosize')[0].dispatchEvent(event); + + this.updateTargetButtons(e); + } + + reenableTargetFormSubmitButton() { + var form; + form = $('.js-main-target-form'); + return form.find('.js-note-text').trigger('input'); + } + + /** + * Shows the main form and does some setup on it. + * + * Sets some hidden fields in the form. + */ + setupMainTargetNoteForm() { + var form; + // find the form + form = $('.js-new-note-form'); + // Set a global clone of the form for later cloning + this.formClone = form.clone(); + // show the form + this.setupNoteForm(form); + // fix classes + form.removeClass('js-new-note-form'); + form.addClass('js-main-target-form'); + form.find('#note_line_code').remove(); + form.find('#note_position').remove(); + form.find('#note_type').val(''); + form.find('#in_reply_to_discussion_id').remove(); + form.find('.js-comment-resolve-button').closest('comment-and-resolve-btn').remove(); + this.parentTimeline = form.parents('.timeline'); + + if (form.length) { + Notes.initCommentTypeToggle(form.get(0)); + } + } + + /** + * General note form setup. + * + * deactivates the submit button when text is empty + * hides the preview button when text is empty + * setup GFM auto complete + * show the form + */ + setupNoteForm(form) { + var textarea, key; + new gl.GLForm(form, this.enableGFM); + textarea = form.find('.js-note-text'); + key = [ + 'Note', + form.find('#note_noteable_type').val(), + form.find('#note_noteable_id').val(), + form.find('#note_commit_id').val(), + form.find('#note_type').val(), + form.find('#in_reply_to_discussion_id').val(), - return isAllowed; - }; + // LegacyDiffNote + form.find('#note_line_code').val(), - /* - Called in response to clicking the edit note link + // DiffNote + form.find('#note_position').val() + ]; + return new Autosave(textarea, key); + } + + /** + * Called in response to the new note form being submitted + * + * Adds new note to list. + */ + addNote($form, note) { + return this.renderNote(note); + } + + addNoteError($form) { + let formParentTimeline; + if ($form.hasClass('js-main-target-form')) { + formParentTimeline = $form.parents('.timeline'); + } else if ($form.hasClass('js-discussion-note-form')) { + formParentTimeline = $form.closest('.discussion-notes').find('.notes'); + } + return this.addFlash('Your comment could not be submitted! Please check your network connection and try again.', 'alert', formParentTimeline); + } + + updateNoteError($parentTimeline) { + new Flash('Your comment could not be updated! Please check your network connection and try again.'); + } + + /** + * Called in response to the new note form being submitted + * + * Adds new note to list. + */ + addDiscussionNote($form, note, isNewDiffComment) { + if ($form.attr('data-resolve-all') != null) { + var projectPath = $form.data('project-path'); + var discussionId = $form.data('discussion-id'); + var mergeRequestId = $form.data('noteable-iid'); + + if (ResolveService != null) { + ResolveService.toggleResolveForDiscussion(mergeRequestId, discussionId); + } + } - Replaces the note text with the note edit form - Adds a data attribute to the form with the original content of the note for cancellations - */ - Notes.prototype.showEditForm = function(e, scrollTo, myLastNote) { - e.preventDefault(); + this.renderNote(note, $form); + // cleanup after successfully creating a diff/discussion note + if (isNewDiffComment) { + this.removeDiscussionNoteForm($form); + } + } + + /** + * Called in response to the edit note form being submitted + * + * Updates the current note field. + */ + updateNote(noteEntity, $targetNote) { + var $noteEntityEl, $note_li; + // Convert returned HTML to a jQuery object so we can modify it further + $noteEntityEl = $(noteEntity.html); + $noteEntityEl.addClass('fade-in-full'); + this.revertNoteEditForm($targetNote); + $noteEntityEl.renderGFM(); + // Find the note's `li` element by ID and replace it with the updated HTML + $note_li = $('.note-row-' + noteEntity.id); + + $note_li.replaceWith($noteEntityEl); + this.setupNewNote($noteEntityEl); + + if (typeof gl.diffNotesCompileComponents !== 'undefined') { + gl.diffNotesCompileComponents(); + } + } - var $target = $(e.target); - var $editForm = $(this.getEditFormSelector($target)); - var $note = $target.closest('.note'); - var $currentlyEditing = $('.note.is-editing:visible'); + checkContentToAllowEditing($el) { + var initialContent = $el.find('.original-note-content').text().trim(); + var currentContent = $el.find('.js-note-text').val(); + var isAllowed = true; - if ($currentlyEditing.length) { - var isEditAllowed = this.checkContentToAllowEditing($currentlyEditing); + if (currentContent === initialContent) { + this.removeNoteEditForm($el); + } + else { + var $buttons = $el.find('.note-form-actions'); + var isWidgetVisible = gl.utils.isInViewport($el.get(0)); - if (!isEditAllowed) { - return; - } + if (!isWidgetVisible) { + gl.utils.scrollToElement($el); } - $note.find('.js-note-attachment-delete').show(); - $editForm.addClass('current-note-edit-form'); - $note.addClass('is-editing'); - this.putEditFormInPlace($target); - }; + $el.find('.js-finish-edit-warning').show(); + isAllowed = false; + } - /* - Called in response to clicking the edit note link + return isAllowed; + } - Hides edit form and restores the original note text to the editor textarea. - */ + /** + * Called in response to clicking the edit note link + * + * Replaces the note text with the note edit form + * Adds a data attribute to the form with the original content of the note for cancellations + */ + showEditForm(e, scrollTo, myLastNote) { + e.preventDefault(); - Notes.prototype.cancelEdit = function(e) { - e.preventDefault(); - const $target = $(e.target); - const $note = $target.closest('.note'); - const noteId = $note.attr('data-note-id'); + var $target = $(e.target); + var $editForm = $(this.getEditFormSelector($target)); + var $note = $target.closest('.note'); + var $currentlyEditing = $('.note.is-editing:visible'); - this.revertNoteEditForm($target); + if ($currentlyEditing.length) { + var isEditAllowed = this.checkContentToAllowEditing($currentlyEditing); - if (this.updatedNotesTrackingMap[noteId]) { - const $newNote = $(this.updatedNotesTrackingMap[noteId].html); - $note.replaceWith($newNote); - this.setupNewNote($newNote); - // Now that we have taken care of the update, clear it out - delete this.updatedNotesTrackingMap[noteId]; - } - else { - $note.find('.js-finish-edit-warning').hide(); - this.removeNoteEditForm($note); + if (!isEditAllowed) { + return; } - }; - - Notes.prototype.revertNoteEditForm = function($target) { - $target = $target || $('.note.is-editing:visible'); - var selector = this.getEditFormSelector($target); - var $editForm = $(selector); + } - $editForm.insertBefore('.notes-form'); - $editForm.find('.js-comment-save-button').enable(); - $editForm.find('.js-finish-edit-warning').hide(); - }; + $note.find('.js-note-attachment-delete').show(); + $editForm.addClass('current-note-edit-form'); + $note.addClass('is-editing'); + this.putEditFormInPlace($target); + } + + /** + * Called in response to clicking the edit note link + * + * Hides edit form and restores the original note text to the editor textarea. + */ + cancelEdit(e) { + e.preventDefault(); + const $target = $(e.target); + const $note = $target.closest('.note'); + const noteId = $note.attr('data-note-id'); + + this.revertNoteEditForm($target); + + if (this.updatedNotesTrackingMap[noteId]) { + const $newNote = $(this.updatedNotesTrackingMap[noteId].html); + $note.replaceWith($newNote); + this.setupNewNote($newNote); + // Now that we have taken care of the update, clear it out + delete this.updatedNotesTrackingMap[noteId]; + } + else { + $note.find('.js-finish-edit-warning').hide(); + this.removeNoteEditForm($note); + } + } - Notes.prototype.getEditFormSelector = function($el) { - var selector = '.note-edit-form:not(.mr-note-edit-form)'; + revertNoteEditForm($target) { + $target = $target || $('.note.is-editing:visible'); + var selector = this.getEditFormSelector($target); + var $editForm = $(selector); - if ($el.parents('#diffs').length) { - selector = '.note-edit-form.mr-note-edit-form'; - } + $editForm.insertBefore('.notes-form'); + $editForm.find('.js-comment-save-button').enable(); + $editForm.find('.js-finish-edit-warning').hide(); + } - return selector; - }; + getEditFormSelector($el) { + var selector = '.note-edit-form:not(.mr-note-edit-form)'; - Notes.prototype.removeNoteEditForm = function($note) { - var form = $note.find('.current-note-edit-form'); - $note.removeClass('is-editing'); - form.removeClass('current-note-edit-form'); - form.find('.js-finish-edit-warning').hide(); - // Replace markdown textarea text with original note text. - return form.find('.js-note-text').val(form.find('form.edit-note').data('original-note')); - }; + if ($el.parents('#diffs').length) { + selector = '.note-edit-form.mr-note-edit-form'; + } - /* - Called in response to deleting a note of any kind. - - Removes the actual note from view. - Removes the whole discussion if the last note is being removed. - */ - - Notes.prototype.removeNote = function(e) { - var noteElId, noteId, dataNoteId, $note, lineHolder; - $note = $(e.currentTarget).closest('.note'); - noteElId = $note.attr('id'); - noteId = $note.attr('data-note-id'); - lineHolder = $(e.currentTarget).closest('.notes[data-discussion-id]') - .closest('.notes_holder') - .prev('.line_holder'); - $(`.note[id="${noteElId}"]`).each((function(_this) { - // A same note appears in the "Discussion" and in the "Changes" tab, we have - // to remove all. Using $('.note[id='noteId']') ensure we get all the notes, - // where $('#noteId') would return only one. - return function(i, el) { - var $note, $notes; - $note = $(el); - $notes = $note.closest('.discussion-notes'); - - if (typeof gl.diffNotesCompileComponents !== 'undefined') { - if (gl.diffNoteApps[noteElId]) { - gl.diffNoteApps[noteElId].$destroy(); - } + return selector; + } + + removeNoteEditForm($note) { + var form = $note.find('.current-note-edit-form'); + $note.removeClass('is-editing'); + form.removeClass('current-note-edit-form'); + form.find('.js-finish-edit-warning').hide(); + // Replace markdown textarea text with original note text. + return form.find('.js-note-text').val(form.find('form.edit-note').data('original-note')); + } + + /** + * Called in response to deleting a note of any kind. + * + * Removes the actual note from view. + * Removes the whole discussion if the last note is being removed. + */ + removeNote(e) { + var noteElId, noteId, dataNoteId, $note, lineHolder; + $note = $(e.currentTarget).closest('.note'); + noteElId = $note.attr('id'); + noteId = $note.attr('data-note-id'); + lineHolder = $(e.currentTarget).closest('.notes[data-discussion-id]') + .closest('.notes_holder') + .prev('.line_holder'); + $(`.note[id="${noteElId}"]`).each((function(_this) { + // A same note appears in the "Discussion" and in the "Changes" tab, we have + // to remove all. Using $('.note[id='noteId']') ensure we get all the notes, + // where $('#noteId') would return only one. + return function(i, el) { + var $note, $notes; + $note = $(el); + $notes = $note.closest('.discussion-notes'); + + if (typeof gl.diffNotesCompileComponents !== 'undefined') { + if (gl.diffNoteApps[noteElId]) { + gl.diffNoteApps[noteElId].$destroy(); } + } - $note.remove(); + $note.remove(); - // check if this is the last note for this line - if ($notes.find('.note').length === 0) { - var notesTr = $notes.closest('tr'); + // check if this is the last note for this line + if ($notes.find('.note').length === 0) { + var notesTr = $notes.closest('tr'); - // "Discussions" tab - $notes.closest('.timeline-entry').remove(); + // "Discussions" tab + $notes.closest('.timeline-entry').remove(); - // The notes tr can contain multiple lists of notes, like on the parallel diff - if (notesTr.find('.discussion-notes').length > 1) { - $notes.remove(); - } else { - notesTr.remove(); - } + // The notes tr can contain multiple lists of notes, like on the parallel diff + if (notesTr.find('.discussion-notes').length > 1) { + $notes.remove(); + } else { + notesTr.remove(); } - }; - })(this)); - - Notes.checkMergeRequestStatus(); - return this.updateNotesCount(-1); - }; - - /* - Called in response to clicking the delete attachment link - - Removes the attachment wrapper view, including image tag if it exists - Resets the note editing form - */ + } + }; + })(this)); + + Notes.checkMergeRequestStatus(); + return this.updateNotesCount(-1); + } + + /** + * Called in response to clicking the delete attachment link + * + * Removes the attachment wrapper view, including image tag if it exists + * Resets the note editing form + */ + removeAttachment() { + const $note = $(this).closest('.note'); + $note.find('.note-attachment').remove(); + $note.find('.note-body > .note-text').show(); + $note.find('.note-header').show(); + return $note.find('.current-note-edit-form').remove(); + } + + /** + * Called when clicking on the "reply" button for a diff line. + * + * Shows the note form below the notes. + */ + onReplyToDiscussionNote(e) { + this.replyToDiscussionNote(e.target); + } + + replyToDiscussionNote(target) { + var form, replyLink; + form = this.cleanForm(this.formClone.clone()); + replyLink = $(target).closest('.js-discussion-reply-button'); + // insert the form after the button + replyLink + .closest('.discussion-reply-holder') + .hide() + .after(form); + // show the form + return this.setupDiscussionNoteForm(replyLink, form); + } + + /** + * Shows the diff or discussion form and does some setup on it. + * + * Sets some hidden fields in the form. + * + * Note: dataHolder must have the "discussionId" and "lineCode" data attributes set. + */ + setupDiscussionNoteForm(dataHolder, form) { + // setup note target + var discussionID = dataHolder.data('discussionId'); + + if (discussionID) { + form.attr('data-discussion-id', discussionID); + form.find('#in_reply_to_discussion_id').val(discussionID); + } - Notes.prototype.removeAttachment = function() { - const $note = $(this).closest('.note'); - $note.find('.note-attachment').remove(); - $note.find('.note-body > .note-text').show(); - $note.find('.note-header').show(); - return $note.find('.current-note-edit-form').remove(); - }; + form.attr('data-line-code', dataHolder.data('lineCode')); + form.find('#line_type').val(dataHolder.data('lineType')); - /* - Called when clicking on the "reply" button for a diff line. + form.find('#note_noteable_type').val(dataHolder.data('noteableType')); + form.find('#note_noteable_id').val(dataHolder.data('noteableId')); + form.find('#note_commit_id').val(dataHolder.data('commitId')); + form.find('#note_type').val(dataHolder.data('noteType')); - Shows the note form below the notes. - */ + // LegacyDiffNote + form.find('#note_line_code').val(dataHolder.data('lineCode')); - Notes.prototype.onReplyToDiscussionNote = function(e) { - this.replyToDiscussionNote(e.target); - }; + // DiffNote + form.find('#note_position').val(dataHolder.attr('data-position')); - Notes.prototype.replyToDiscussionNote = function(target) { - var form, replyLink; - form = this.cleanForm(this.formClone.clone()); - replyLink = $(target).closest('.js-discussion-reply-button'); - // insert the form after the button - replyLink - .closest('.discussion-reply-holder') - .hide() - .after(form); - // show the form - return this.setupDiscussionNoteForm(replyLink, form); - }; + form.find('.js-note-discard').show().removeClass('js-note-discard').addClass('js-close-discussion-note-form').text(form.find('.js-close-discussion-note-form').data('cancel-text')); + form.find('.js-note-target-close').remove(); + form.find('.js-note-new-discussion').remove(); + this.setupNoteForm(form); - /* - Shows the diff or discussion form and does some setup on it. + form + .removeClass('js-main-target-form') + .addClass('discussion-form js-discussion-note-form'); - Sets some hidden fields in the form. + if (typeof gl.diffNotesCompileComponents !== 'undefined') { + var $commentBtn = form.find('comment-and-resolve-btn'); + $commentBtn.attr(':discussion-id', `'${discussionID}'`); - Note: dataHolder must have the "discussionId" and "lineCode" data attributes set. - */ + gl.diffNotesCompileComponents(); + } - Notes.prototype.setupDiscussionNoteForm = function(dataHolder, form) { - // setup note target - var discussionID = dataHolder.data('discussionId'); + form.find('.js-note-text').focus(); + form + .find('.js-comment-resolve-button') + .attr('data-discussion-id', discussionID); + } + + /** + * Called when clicking on the "add a comment" button on the side of a diff line. + * + * Inserts a temporary row for the form below the line. + * Sets up the form and shows it. + */ + onAddDiffNote(e) { + e.preventDefault(); + const link = e.currentTarget || e.target; + const $link = $(link); + const showReplyInput = !$link.hasClass('js-diff-comment-avatar'); + this.toggleDiffNote({ + target: $link, + lineType: link.dataset.lineType, + showReplyInput + }); + } + + toggleDiffNote({ + target, + lineType, + forceShow, + showReplyInput = false, + }) { + var $link, addForm, hasNotes, newForm, noteForm, replyButton, row, rowCssToAdd, targetContent, isDiffCommentAvatar; + $link = $(target); + row = $link.closest('tr'); + const nextRow = row.next(); + let targetRow = row; + if (nextRow.is('.notes_holder')) { + targetRow = nextRow; + } - if (discussionID) { - form.attr('data-discussion-id', discussionID); - form.find('#in_reply_to_discussion_id').val(discussionID); + hasNotes = nextRow.is('.notes_holder'); + addForm = false; + let lineTypeSelector = ''; + rowCssToAdd = '<tr class="notes_holder js-temp-notes-holder"><td class="notes_line" colspan="2"></td><td class="notes_content"><div class="content"></div></td></tr>'; + // In parallel view, look inside the correct left/right pane + if (this.isParallelView()) { + lineTypeSelector = `.${lineType}`; + rowCssToAdd = '<tr class="notes_holder js-temp-notes-holder"><td class="notes_line old"></td><td class="notes_content parallel old"><div class="content"></div></td><td class="notes_line new"></td><td class="notes_content parallel new"><div class="content"></div></td></tr>'; + } + const notesContentSelector = `.notes_content${lineTypeSelector} .content`; + let notesContent = targetRow.find(notesContentSelector); + + if (hasNotes && showReplyInput) { + targetRow.show(); + notesContent = targetRow.find(notesContentSelector); + if (notesContent.length) { + notesContent.show(); + replyButton = notesContent.find('.js-discussion-reply-button:visible'); + if (replyButton.length) { + this.replyToDiscussionNote(replyButton[0]); + } else { + // In parallel view, the form may not be present in one of the panes + noteForm = notesContent.find('.js-discussion-note-form'); + if (noteForm.length === 0) { + addForm = true; + } + } } + } else if (showReplyInput) { + // add a notes row and insert the form + row.after(rowCssToAdd); + targetRow = row.next(); + notesContent = targetRow.find(notesContentSelector); + addForm = true; + } else { + const isCurrentlyShown = targetRow.find('.content:not(:empty)').is(':visible'); + const isForced = forceShow === true || forceShow === false; + const showNow = forceShow === true || (!isCurrentlyShown && !isForced); + + targetRow.toggle(showNow); + notesContent.toggle(showNow); + } - form.attr('data-line-code', dataHolder.data('lineCode')); - form.find('#line_type').val(dataHolder.data('lineType')); - - form.find('#note_noteable_type').val(dataHolder.data('noteableType')); - form.find('#note_noteable_id').val(dataHolder.data('noteableId')); - form.find('#note_commit_id').val(dataHolder.data('commitId')); - form.find('#note_type').val(dataHolder.data('noteType')); - - // LegacyDiffNote - form.find('#note_line_code').val(dataHolder.data('lineCode')); - - // DiffNote - form.find('#note_position').val(dataHolder.attr('data-position')); - - form.find('.js-note-discard').show().removeClass('js-note-discard').addClass('js-close-discussion-note-form').text(form.find('.js-close-discussion-note-form').data('cancel-text')); - form.find('.js-note-target-close').remove(); - form.find('.js-note-new-discussion').remove(); - this.setupNoteForm(form); - - form - .removeClass('js-main-target-form') - .addClass('discussion-form js-discussion-note-form'); - - if (typeof gl.diffNotesCompileComponents !== 'undefined') { - var $commentBtn = form.find('comment-and-resolve-btn'); - $commentBtn.attr(':discussion-id', `'${discussionID}'`); - - gl.diffNotesCompileComponents(); + if (addForm) { + newForm = this.cleanForm(this.formClone.clone()); + newForm.appendTo(notesContent); + // show the form + return this.setupDiscussionNoteForm($link, newForm); + } + } + + /** + * Called in response to "cancel" on a diff note form. + * + * Shows the reply button again. + * Removes the form and if necessary it's temporary row. + */ + removeDiscussionNoteForm(form) { + var glForm, row; + row = form.closest('tr'); + glForm = form.data('gl-form'); + glForm.destroy(); + form.find('.js-note-text').data('autosave').reset(); + // show the reply button (will only work for replies) + form + .prev('.discussion-reply-holder') + .show(); + if (row.is('.js-temp-notes-holder')) { + // remove temporary row for diff lines + return row.remove(); + } else { + // only remove the form + return form.remove(); + } + } + + cancelDiscussionForm(e) { + var form; + e.preventDefault(); + form = $(e.target).closest('.js-discussion-note-form'); + return this.removeDiscussionNoteForm(form); + } + + /** + * Called after an attachment file has been selected. + * + * Updates the file name for the selected attachment. + */ + updateFormAttachment() { + var filename, form; + form = $(this).closest('form'); + // get only the basename + filename = $(this).val().replace(/^.*[\\\/]/, ''); + return form.find('.js-attachment-filename').text(filename); + } + + /** + * Called when the tab visibility changes + */ + visibilityChange() { + return this.refresh(); + } + + updateTargetButtons(e) { + var closebtn, closetext, discardbtn, form, reopenbtn, reopentext, textarea; + textarea = $(e.target); + form = textarea.parents('form'); + reopenbtn = form.find('.js-note-target-reopen'); + closebtn = form.find('.js-note-target-close'); + discardbtn = form.find('.js-note-discard'); + + if (textarea.val().trim().length > 0) { + reopentext = reopenbtn.attr('data-alternative-text'); + closetext = closebtn.attr('data-alternative-text'); + if (reopenbtn.text() !== reopentext) { + reopenbtn.text(reopentext); } - - form.find('.js-note-text').focus(); - form - .find('.js-comment-resolve-button') - .attr('data-discussion-id', discussionID); - }; - - /* - Called when clicking on the "add a comment" button on the side of a diff line. - - Inserts a temporary row for the form below the line. - Sets up the form and shows it. - */ - - Notes.prototype.onAddDiffNote = function(e) { - e.preventDefault(); - const link = e.currentTarget || e.target; - const $link = $(link); - const showReplyInput = !$link.hasClass('js-diff-comment-avatar'); - this.toggleDiffNote({ - target: $link, - lineType: link.dataset.lineType, - showReplyInput - }); - }; - - Notes.prototype.toggleDiffNote = function({ - target, - lineType, - forceShow, - showReplyInput = false, - }) { - var $link, addForm, hasNotes, newForm, noteForm, replyButton, row, rowCssToAdd, targetContent, isDiffCommentAvatar; - $link = $(target); - row = $link.closest('tr'); - const nextRow = row.next(); - let targetRow = row; - if (nextRow.is('.notes_holder')) { - targetRow = nextRow; + if (closebtn.text() !== closetext) { + closebtn.text(closetext); } - - hasNotes = nextRow.is('.notes_holder'); - addForm = false; - let lineTypeSelector = ''; - rowCssToAdd = '<tr class="notes_holder js-temp-notes-holder"><td class="notes_line" colspan="2"></td><td class="notes_content"><div class="content"></div></td></tr>'; - // In parallel view, look inside the correct left/right pane - if (this.isParallelView()) { - lineTypeSelector = `.${lineType}`; - rowCssToAdd = '<tr class="notes_holder js-temp-notes-holder"><td class="notes_line old"></td><td class="notes_content parallel old"><div class="content"></div></td><td class="notes_line new"></td><td class="notes_content parallel new"><div class="content"></div></td></tr>'; + if (reopenbtn.is(':not(.btn-comment-and-reopen)')) { + reopenbtn.addClass('btn-comment-and-reopen'); } - const notesContentSelector = `.notes_content${lineTypeSelector} .content`; - let notesContent = targetRow.find(notesContentSelector); - - if (hasNotes && showReplyInput) { - targetRow.show(); - notesContent = targetRow.find(notesContentSelector); - if (notesContent.length) { - notesContent.show(); - replyButton = notesContent.find('.js-discussion-reply-button:visible'); - if (replyButton.length) { - this.replyToDiscussionNote(replyButton[0]); - } else { - // In parallel view, the form may not be present in one of the panes - noteForm = notesContent.find('.js-discussion-note-form'); - if (noteForm.length === 0) { - addForm = true; - } - } - } - } else if (showReplyInput) { - // add a notes row and insert the form - row.after(rowCssToAdd); - targetRow = row.next(); - notesContent = targetRow.find(notesContentSelector); - addForm = true; - } else { - const isCurrentlyShown = targetRow.find('.content:not(:empty)').is(':visible'); - const isForced = forceShow === true || forceShow === false; - const showNow = forceShow === true || (!isCurrentlyShown && !isForced); - - targetRow.toggle(showNow); - notesContent.toggle(showNow); + if (closebtn.is(':not(.btn-comment-and-close)')) { + closebtn.addClass('btn-comment-and-close'); } - - if (addForm) { - newForm = this.cleanForm(this.formClone.clone()); - newForm.appendTo(notesContent); - // show the form - return this.setupDiscussionNoteForm($link, newForm); + if (discardbtn.is(':hidden')) { + return discardbtn.show(); } - }; - - /* - Called in response to "cancel" on a diff note form. - - Shows the reply button again. - Removes the form and if necessary it's temporary row. - */ - - Notes.prototype.removeDiscussionNoteForm = function(form) { - var glForm, row; - row = form.closest('tr'); - glForm = form.data('gl-form'); - glForm.destroy(); - form.find('.js-note-text').data('autosave').reset(); - // show the reply button (will only work for replies) - form - .prev('.discussion-reply-holder') - .show(); - if (row.is('.js-temp-notes-holder')) { - // remove temporary row for diff lines - return row.remove(); - } else { - // only remove the form - return form.remove(); + } else { + reopentext = reopenbtn.data('original-text'); + closetext = closebtn.data('original-text'); + if (reopenbtn.text() !== reopentext) { + reopenbtn.text(reopentext); } - }; - - Notes.prototype.cancelDiscussionForm = function(e) { - var form; - e.preventDefault(); - form = $(e.target).closest('.js-discussion-note-form'); - return this.removeDiscussionNoteForm(form); - }; - - /* - Called after an attachment file has been selected. - - Updates the file name for the selected attachment. - */ - - Notes.prototype.updateFormAttachment = function() { - var filename, form; - form = $(this).closest('form'); - // get only the basename - filename = $(this).val().replace(/^.*[\\\/]/, ''); - return form.find('.js-attachment-filename').text(filename); - }; - - /* - Called when the tab visibility changes - */ - - Notes.prototype.visibilityChange = function() { - return this.refresh(); - }; - - Notes.prototype.updateTargetButtons = function(e) { - var closebtn, closetext, discardbtn, form, reopenbtn, reopentext, textarea; - textarea = $(e.target); - form = textarea.parents('form'); - reopenbtn = form.find('.js-note-target-reopen'); - closebtn = form.find('.js-note-target-close'); - discardbtn = form.find('.js-note-discard'); - - if (textarea.val().trim().length > 0) { - reopentext = reopenbtn.attr('data-alternative-text'); - closetext = closebtn.attr('data-alternative-text'); - if (reopenbtn.text() !== reopentext) { - reopenbtn.text(reopentext); - } - if (closebtn.text() !== closetext) { - closebtn.text(closetext); - } - if (reopenbtn.is(':not(.btn-comment-and-reopen)')) { - reopenbtn.addClass('btn-comment-and-reopen'); - } - if (closebtn.is(':not(.btn-comment-and-close)')) { - closebtn.addClass('btn-comment-and-close'); - } - if (discardbtn.is(':hidden')) { - return discardbtn.show(); - } - } else { - reopentext = reopenbtn.data('original-text'); - closetext = closebtn.data('original-text'); - if (reopenbtn.text() !== reopentext) { - reopenbtn.text(reopentext); - } - if (closebtn.text() !== closetext) { - closebtn.text(closetext); - } - if (reopenbtn.is('.btn-comment-and-reopen')) { - reopenbtn.removeClass('btn-comment-and-reopen'); - } - if (closebtn.is('.btn-comment-and-close')) { - closebtn.removeClass('btn-comment-and-close'); - } - if (discardbtn.is(':visible')) { - return discardbtn.hide(); - } + if (closebtn.text() !== closetext) { + closebtn.text(closetext); } - }; - - Notes.prototype.putEditFormInPlace = function($el) { - var $editForm = $(this.getEditFormSelector($el)); - var $note = $el.closest('.note'); - - $editForm.insertAfter($note.find('.note-text')); - - var $originalContentEl = $note.find('.original-note-content'); - var originalContent = $originalContentEl.text().trim(); - var postUrl = $originalContentEl.data('post-url'); - var targetId = $originalContentEl.data('target-id'); - var targetType = $originalContentEl.data('target-type'); - - new gl.GLForm($editForm.find('form'), this.enableGFM); - - $editForm.find('form') - .attr('action', postUrl) - .attr('data-remote', 'true'); - $editForm.find('.js-form-target-id').val(targetId); - $editForm.find('.js-form-target-type').val(targetType); - $editForm.find('.js-note-text').focus().val(originalContent); - $editForm.find('.js-md-write-button').trigger('click'); - $editForm.find('.referenced-users').hide(); - }; - - Notes.prototype.putConflictEditWarningInPlace = function(noteEntity, $note) { - if ($note.find('.js-conflict-edit-warning').length === 0) { - const $alert = $(`<div class="js-conflict-edit-warning alert alert-danger"> - This comment has changed since you started editing, please review the - <a href="#note_${noteEntity.id}" target="_blank" rel="noopener noreferrer"> - updated comment - </a> - to ensure information is not lost - </div>`); - $alert.insertAfter($note.find('.note-text')); + if (reopenbtn.is('.btn-comment-and-reopen')) { + reopenbtn.removeClass('btn-comment-and-reopen'); } - }; - - Notes.prototype.updateNotesCount = function(updateCount) { - return this.notesCountBadge.text(parseInt(this.notesCountBadge.text(), 10) + updateCount); - }; - - Notes.prototype.toggleCommitList = function(e) { - const $element = $(e.currentTarget); - const $closestSystemCommitList = $element.siblings('.system-note-commit-list'); - - $element.find('.fa').toggleClass('fa-angle-down').toggleClass('fa-angle-up'); - $closestSystemCommitList.toggleClass('hide-shade'); - }; - - /** - Scans system notes with `ul` elements in system note body - then collapse long commit list pushed by user to make it less - intrusive. - */ - Notes.prototype.collapseLongCommitList = function() { - const systemNotes = $('#notes-list').find('li.system-note').has('ul'); - - $.each(systemNotes, function(index, systemNote) { - const $systemNote = $(systemNote); - const headerMessage = $systemNote.find('.note-text').find('p:first').text().replace(':', ''); - - $systemNote.find('.note-header .system-note-message').html(headerMessage); - - if ($systemNote.find('li').length > MAX_VISIBLE_COMMIT_LIST_COUNT) { - $systemNote.find('.note-text').addClass('system-note-commit-list'); - $systemNote.find('.system-note-commit-list-toggler').show(); - } else { - $systemNote.find('.note-text').addClass('system-note-commit-list hide-shade'); - } - }); - }; - - Notes.prototype.addFlash = function(...flashParams) { - this.flashInstance = new Flash(...flashParams); - }; - - Notes.prototype.clearFlash = function() { - if (this.flashInstance && this.flashInstance.flashContainer) { - this.flashInstance.flashContainer.hide(); - this.flashInstance = null; + if (closebtn.is('.btn-comment-and-close')) { + closebtn.removeClass('btn-comment-and-close'); } - }; - - Notes.prototype.cleanForm = function($form) { - // Remove JS classes that are not needed here - $form - .find('.js-comment-type-dropdown') - .removeClass('btn-group'); - - // Remove dropdown - $form - .find('.dropdown-menu') - .remove(); - - return $form; - }; - - /** - * Check if note does not exists on page - */ - Notes.isNewNote = function(noteEntity, noteIds) { - return $.inArray(noteEntity.id, noteIds) === -1; - }; - - /** - * Check if $note already contains the `noteEntity` content - */ - Notes.isUpdatedNote = function(noteEntity, $note) { - // There can be CRLF vs LF mismatches if we don't sanitize and compare the same way - const sanitizedNoteEntityText = normalizeNewlines(noteEntity.note.trim()); - const currentNoteText = normalizeNewlines( - $note.find('.original-note-content').first().text().trim() - ); - return sanitizedNoteEntityText !== currentNoteText; - }; - - Notes.checkMergeRequestStatus = function() { - if (gl.utils.getPagePath(1) === 'merge_requests') { - gl.mrWidget.checkStatus(); + if (discardbtn.is(':visible')) { + return discardbtn.hide(); } - }; + } + } + + putEditFormInPlace($el) { + var $editForm = $(this.getEditFormSelector($el)); + var $note = $el.closest('.note'); + + $editForm.insertAfter($note.find('.note-text')); + + var $originalContentEl = $note.find('.original-note-content'); + var originalContent = $originalContentEl.text().trim(); + var postUrl = $originalContentEl.data('post-url'); + var targetId = $originalContentEl.data('target-id'); + var targetType = $originalContentEl.data('target-type'); + + new gl.GLForm($editForm.find('form'), this.enableGFM); + + $editForm.find('form') + .attr('action', postUrl) + .attr('data-remote', 'true'); + $editForm.find('.js-form-target-id').val(targetId); + $editForm.find('.js-form-target-type').val(targetType); + $editForm.find('.js-note-text').focus().val(originalContent); + $editForm.find('.js-md-write-button').trigger('click'); + $editForm.find('.referenced-users').hide(); + } + + putConflictEditWarningInPlace(noteEntity, $note) { + if ($note.find('.js-conflict-edit-warning').length === 0) { + const $alert = $(`<div class="js-conflict-edit-warning alert alert-danger"> + This comment has changed since you started editing, please review the + <a href="#note_${noteEntity.id}" target="_blank" rel="noopener noreferrer"> + updated comment + </a> + to ensure information is not lost + </div>`); + $alert.insertAfter($note.find('.note-text')); + } + } - Notes.animateAppendNote = function(noteHtml, $notesList) { - const $note = $(noteHtml); + updateNotesCount(updateCount) { + return this.notesCountBadge.text(parseInt(this.notesCountBadge.text(), 10) + updateCount); + } - $note.addClass('fade-in-full').renderGFM(); - $notesList.append($note); - return $note; - }; + toggleCommitList(e) { + const $element = $(e.currentTarget); + const $closestSystemCommitList = $element.siblings('.system-note-commit-list'); - Notes.animateUpdateNote = function(noteHtml, $note) { - const $updatedNote = $(noteHtml); + $element.find('.fa').toggleClass('fa-angle-down').toggleClass('fa-angle-up'); + $closestSystemCommitList.toggleClass('hide-shade'); + } - $updatedNote.addClass('fade-in').renderGFM(); - $note.replaceWith($updatedNote); - return $updatedNote; - }; + /** + * Scans system notes with `ul` elements in system note body + * then collapse long commit list pushed by user to make it less + * intrusive. + */ + collapseLongCommitList() { + const systemNotes = $('#notes-list').find('li.system-note').has('ul'); - /** - * Get data from Form attributes to use for saving/submitting comment. - */ - Notes.prototype.getFormData = function($form) { - return { - formData: $form.serialize(), - formContent: _.escape($form.find('.js-note-text').val()), - formAction: $form.attr('action'), - }; - }; + $.each(systemNotes, function(index, systemNote) { + const $systemNote = $(systemNote); + const headerMessage = $systemNote.find('.note-text').find('p:first').text().replace(':', ''); - /** - * Identify if comment has any quick actions - */ - Notes.prototype.hasQuickActions = function(formContent) { - return REGEX_QUICK_ACTIONS.test(formContent); - }; - - /** - * Remove quick actions and leave comment with pure message - */ - Notes.prototype.stripQuickActions = function(formContent) { - return formContent.replace(REGEX_QUICK_ACTIONS, '').trim(); - }; + $systemNote.find('.note-header .system-note-message').html(headerMessage); - /** - * Gets appropriate description from quick actions found in provided `formContent` - */ - Notes.prototype.getQuickActionDescription = function (formContent, availableQuickActions = []) { - let tempFormContent; + if ($systemNote.find('li').length > MAX_VISIBLE_COMMIT_LIST_COUNT) { + $systemNote.find('.note-text').addClass('system-note-commit-list'); + $systemNote.find('.system-note-commit-list-toggler').show(); + } else { + $systemNote.find('.note-text').addClass('system-note-commit-list hide-shade'); + } + }); + } - // Identify executed quick actions from `formContent` - const executedCommands = availableQuickActions.filter((command, index) => { - const commandRegex = new RegExp(`/${command.name}`); - return commandRegex.test(formContent); - }); + addFlash(...flashParams) { + this.flashInstance = new Flash(...flashParams); + } - if (executedCommands && executedCommands.length) { - if (executedCommands.length > 1) { - tempFormContent = 'Applying multiple commands'; - } else { - const commandDescription = executedCommands[0].description.toLowerCase(); - tempFormContent = `Applying command to ${commandDescription}`; - } + clearFlash() { + if (this.flashInstance && this.flashInstance.flashContainer) { + this.flashInstance.flashContainer.hide(); + this.flashInstance = null; + } + } + + cleanForm($form) { + // Remove JS classes that are not needed here + $form + .find('.js-comment-type-dropdown') + .removeClass('btn-group'); + + // Remove dropdown + $form + .find('.dropdown-menu') + .remove(); + + return $form; + } + + /** + * Check if note does not exists on page + */ + static isNewNote(noteEntity, noteIds) { + return $.inArray(noteEntity.id, noteIds) === -1; + } + + /** + * Check if $note already contains the `noteEntity` content + */ + static isUpdatedNote(noteEntity, $note) { + // There can be CRLF vs LF mismatches if we don't sanitize and compare the same way + const sanitizedNoteEntityText = normalizeNewlines(noteEntity.note.trim()); + const currentNoteText = normalizeNewlines( + $note.find('.original-note-content').first().text().trim() + ); + return sanitizedNoteEntityText !== currentNoteText; + } + + static checkMergeRequestStatus() { + if (gl.utils.getPagePath(1) === 'merge_requests') { + gl.mrWidget.checkStatus(); + } + } + + static animateAppendNote(noteHtml, $notesList) { + const $note = $(noteHtml); + + $note.addClass('fade-in-full').renderGFM(); + $notesList.append($note); + return $note; + } + + static animateUpdateNote(noteHtml, $note) { + const $updatedNote = $(noteHtml); + + $updatedNote.addClass('fade-in').renderGFM(); + $note.replaceWith($updatedNote); + return $updatedNote; + } + + /** + * Get data from Form attributes to use for saving/submitting comment. + */ + getFormData($form) { + return { + formData: $form.serialize(), + formContent: _.escape($form.find('.js-note-text').val()), + formAction: $form.attr('action'), + }; + } + + /** + * Identify if comment has any quick actions + */ + hasQuickActions(formContent) { + return REGEX_QUICK_ACTIONS.test(formContent); + } + + /** + * Remove quick actions and leave comment with pure message + */ + stripQuickActions(formContent) { + return formContent.replace(REGEX_QUICK_ACTIONS, '').trim(); + } + + /** + * Gets appropriate description from quick actions found in provided `formContent` + */ + getQuickActionDescription(formContent, availableQuickActions = []) { + let tempFormContent; + + // Identify executed quick actions from `formContent` + const executedCommands = availableQuickActions.filter((command, index) => { + const commandRegex = new RegExp(`/${command.name}`); + return commandRegex.test(formContent); + }); + + if (executedCommands && executedCommands.length) { + if (executedCommands.length > 1) { + tempFormContent = 'Applying multiple commands'; } else { - tempFormContent = 'Applying command'; + const commandDescription = executedCommands[0].description.toLowerCase(); + tempFormContent = `Applying command to ${commandDescription}`; } + } else { + tempFormContent = 'Applying command'; + } - return tempFormContent; - }; - - /** - * Create placeholder note DOM element populated with comment body - * that we will show while comment is being posted. - * Once comment is _actually_ posted on server, we will have final element - * in response that we will show in place of this temporary element. - */ - Notes.prototype.createPlaceholderNote = function ({ formContent, uniqueId, isDiscussionNote, currentUsername, currentUserFullname, currentUserAvatar }) { - const discussionClass = isDiscussionNote ? 'discussion' : ''; - const $tempNote = $( - `<li id="${uniqueId}" class="note being-posted fade-in-half timeline-entry"> - <div class="timeline-entry-inner"> - <div class="timeline-icon"> - <a href="/${currentUsername}"> - <img class="avatar s40" src="${currentUserAvatar}"> - </a> - </div> - <div class="timeline-content ${discussionClass}"> - <div class="note-header"> - <div class="note-header-info"> - <a href="/${currentUsername}"> - <span class="hidden-xs">${currentUserFullname}</span> - <span class="note-headline-light">@${currentUsername}</span> - </a> - </div> + return tempFormContent; + } + + /** + * Create placeholder note DOM element populated with comment body + * that we will show while comment is being posted. + * Once comment is _actually_ posted on server, we will have final element + * in response that we will show in place of this temporary element. + */ + createPlaceholderNote({ formContent, uniqueId, isDiscussionNote, currentUsername, currentUserFullname, currentUserAvatar }) { + const discussionClass = isDiscussionNote ? 'discussion' : ''; + const $tempNote = $( + `<li id="${uniqueId}" class="note being-posted fade-in-half timeline-entry"> + <div class="timeline-entry-inner"> + <div class="timeline-icon"> + <a href="/${currentUsername}"> + <img class="avatar s40" src="${currentUserAvatar}"> + </a> + </div> + <div class="timeline-content ${discussionClass}"> + <div class="note-header"> + <div class="note-header-info"> + <a href="/${currentUsername}"> + <span class="hidden-xs">${currentUserFullname}</span> + <span class="note-headline-light">@${currentUsername}</span> + </a> + </div> + </div> + <div class="note-body"> + <div class="note-text"> + <p>${formContent}</p> </div> - <div class="note-body"> - <div class="note-text"> - <p>${formContent}</p> - </div> - </div> - </div> + </div> + </div> + </div> + </li>` + ); + + return $tempNote; + } + + /** + * Create Placeholder System Note DOM element populated with quick action description + */ + createPlaceholderSystemNote({ formContent, uniqueId }) { + const $tempNote = $( + `<li id="${uniqueId}" class="note system-note timeline-entry being-posted fade-in-half"> + <div class="timeline-entry-inner"> + <div class="timeline-content"> + <i>${formContent}</i> </div> - </li>` - ); - - return $tempNote; - }; - - /** - * Create Placeholder System Note DOM element populated with quick action description - */ - Notes.prototype.createPlaceholderSystemNote = function ({ formContent, uniqueId }) { - const $tempNote = $( - `<li id="${uniqueId}" class="note system-note timeline-entry being-posted fade-in-half"> - <div class="timeline-entry-inner"> - <div class="timeline-content"> - <i>${formContent}</i> - </div> - </div> - </li>` - ); + </div> + </li>` + ); + + return $tempNote; + } + + /** + * This method does following tasks step-by-step whenever a new comment + * is submitted by user (both main thread comments as well as discussion comments). + * + * 1) Get Form metadata + * 2) Identify comment type; a) Main thread b) Discussion thread c) Discussion resolve + * 3) Build temporary placeholder element (using `createPlaceholderNote`) + * 4) Show placeholder note on UI + * 5) Perform network request to submit the note using `gl.utils.ajaxPost` + * a) If request is successfully completed + * 1. Remove placeholder element + * 2. Show submitted Note element + * 3. Perform post-submit errands + * a. Mark discussion as resolved if comment submission was for resolve. + * b. Reset comment form to original state. + * b) If request failed + * 1. Remove placeholder element + * 2. Show error Flash message about failure + */ + postComment(e) { + e.preventDefault(); + + // Get Form metadata + const $submitBtn = $(e.target); + let $form = $submitBtn.parents('form'); + const $closeBtn = $form.find('.js-note-target-close'); + const isDiscussionNote = $submitBtn.parent().find('li.droplab-item-selected').attr('id') === 'discussion'; + const isMainForm = $form.hasClass('js-main-target-form'); + const isDiscussionForm = $form.hasClass('js-discussion-note-form'); + const isDiscussionResolve = $submitBtn.hasClass('js-comment-resolve-button'); + const { formData, formContent, formAction } = this.getFormData($form); + let noteUniqueId; + let systemNoteUniqueId; + let hasQuickActions = false; + let $notesContainer; + let tempFormContent; + + // Get reference to notes container based on type of comment + if (isDiscussionForm) { + $notesContainer = $form.parent('.discussion-notes').find('.notes'); + } else if (isMainForm) { + $notesContainer = $('ul.main-notes-list'); + } - return $tempNote; - }; + // If comment is to resolve discussion, disable submit buttons while + // comment posting is finished. + if (isDiscussionResolve) { + $submitBtn.disable(); + $form.find('.js-comment-submit-button').disable(); + } - /** - * This method does following tasks step-by-step whenever a new comment - * is submitted by user (both main thread comments as well as discussion comments). - * - * 1) Get Form metadata - * 2) Identify comment type; a) Main thread b) Discussion thread c) Discussion resolve - * 3) Build temporary placeholder element (using `createPlaceholderNote`) - * 4) Show placeholder note on UI - * 5) Perform network request to submit the note using `gl.utils.ajaxPost` - * a) If request is successfully completed - * 1. Remove placeholder element - * 2. Show submitted Note element - * 3. Perform post-submit errands - * a. Mark discussion as resolved if comment submission was for resolve. - * b. Reset comment form to original state. - * b) If request failed - * 1. Remove placeholder element - * 2. Show error Flash message about failure - */ - Notes.prototype.postComment = function(e) { - e.preventDefault(); - - // Get Form metadata - const $submitBtn = $(e.target); - let $form = $submitBtn.parents('form'); - const $closeBtn = $form.find('.js-note-target-close'); - const isDiscussionNote = $submitBtn.parent().find('li.droplab-item-selected').attr('id') === 'discussion'; - const isMainForm = $form.hasClass('js-main-target-form'); - const isDiscussionForm = $form.hasClass('js-discussion-note-form'); - const isDiscussionResolve = $submitBtn.hasClass('js-comment-resolve-button'); - const { formData, formContent, formAction } = this.getFormData($form); - let noteUniqueId; - let systemNoteUniqueId; - let hasQuickActions = false; - let $notesContainer; - let tempFormContent; - - // Get reference to notes container based on type of comment - if (isDiscussionForm) { - $notesContainer = $form.parent('.discussion-notes').find('.notes'); - } else if (isMainForm) { - $notesContainer = $('ul.main-notes-list'); - } + tempFormContent = formContent; + if (this.hasQuickActions(formContent)) { + tempFormContent = this.stripQuickActions(formContent); + hasQuickActions = true; + } - // If comment is to resolve discussion, disable submit buttons while - // comment posting is finished. - if (isDiscussionResolve) { - $submitBtn.disable(); - $form.find('.js-comment-submit-button').disable(); - } + // Show placeholder note + if (tempFormContent) { + noteUniqueId = _.uniqueId('tempNote_'); + $notesContainer.append(this.createPlaceholderNote({ + formContent: tempFormContent, + uniqueId: noteUniqueId, + isDiscussionNote, + currentUsername: gon.current_username, + currentUserFullname: gon.current_user_fullname, + currentUserAvatar: gon.current_user_avatar_url, + })); + } - tempFormContent = formContent; - if (this.hasQuickActions(formContent)) { - tempFormContent = this.stripQuickActions(formContent); - hasQuickActions = true; - } + // Show placeholder system note + if (hasQuickActions) { + systemNoteUniqueId = _.uniqueId('tempSystemNote_'); + $notesContainer.append(this.createPlaceholderSystemNote({ + formContent: this.getQuickActionDescription(formContent, AjaxCache.get(gl.GfmAutoComplete.dataSources.commands)), + uniqueId: systemNoteUniqueId, + })); + } - // Show placeholder note - if (tempFormContent) { - noteUniqueId = _.uniqueId('tempNote_'); - $notesContainer.append(this.createPlaceholderNote({ - formContent: tempFormContent, - uniqueId: noteUniqueId, - isDiscussionNote, - currentUsername: gon.current_username, - currentUserFullname: gon.current_user_fullname, - currentUserAvatar: gon.current_user_avatar_url, - })); + // Clear the form textarea + if ($notesContainer.length) { + if (isMainForm) { + this.resetMainTargetForm(e); + } else if (isDiscussionForm) { + this.removeDiscussionNoteForm($form); } + } - // Show placeholder system note - if (hasQuickActions) { - systemNoteUniqueId = _.uniqueId('tempSystemNote_'); - $notesContainer.append(this.createPlaceholderSystemNote({ - formContent: this.getQuickActionDescription(formContent, AjaxCache.get(gl.GfmAutoComplete.dataSources.commands)), - uniqueId: systemNoteUniqueId, - })); - } + /* eslint-disable promise/catch-or-return */ + // Make request to submit comment on server + gl.utils.ajaxPost(formAction, formData) + .then((note) => { + // Submission successful! remove placeholder + $notesContainer.find(`#${noteUniqueId}`).remove(); - // Clear the form textarea - if ($notesContainer.length) { - if (isMainForm) { - this.resetMainTargetForm(e); - } else if (isDiscussionForm) { - this.removeDiscussionNoteForm($form); + // Reset cached commands list when command is applied + if (hasQuickActions) { + $form.find('textarea.js-note-text').trigger('clear-commands-cache.atwho'); } - } - - /* eslint-disable promise/catch-or-return */ - // Make request to submit comment on server - gl.utils.ajaxPost(formAction, formData) - .then((note) => { - // Submission successful! remove placeholder - $notesContainer.find(`#${noteUniqueId}`).remove(); - // Reset cached commands list when command is applied - if (hasQuickActions) { - $form.find('textarea.js-note-text').trigger('clear-commands-cache.atwho'); - } - - // Clear previous form errors - this.clearFlashWrapper(); + // Clear previous form errors + this.clearFlashWrapper(); - // Check if this was discussion comment - if (isDiscussionForm) { - // Remove flash-container - $notesContainer.find('.flash-container').remove(); + // Check if this was discussion comment + if (isDiscussionForm) { + // Remove flash-container + $notesContainer.find('.flash-container').remove(); - // If comment intends to resolve discussion, do the same. - if (isDiscussionResolve) { - $form - .attr('data-discussion-id', $submitBtn.data('discussion-id')) - .attr('data-resolve-all', 'true') - .attr('data-project-path', $submitBtn.data('project-path')); - } + // If comment intends to resolve discussion, do the same. + if (isDiscussionResolve) { + $form + .attr('data-discussion-id', $submitBtn.data('discussion-id')) + .attr('data-resolve-all', 'true') + .attr('data-project-path', $submitBtn.data('project-path')); + } - // Show final note element on UI - this.addDiscussionNote($form, note, $notesContainer.length === 0); + // Show final note element on UI + this.addDiscussionNote($form, note, $notesContainer.length === 0); - // append flash-container to the Notes list - if ($notesContainer.length) { - $notesContainer.append('<div class="flash-container" style="display: none;"></div>'); - } - } else if (isMainForm) { // Check if this was main thread comment - // Show final note element on UI and perform form and action buttons cleanup - this.addNote($form, note); - this.reenableTargetFormSubmitButton(e); + // append flash-container to the Notes list + if ($notesContainer.length) { + $notesContainer.append('<div class="flash-container" style="display: none;"></div>'); } + } else if (isMainForm) { // Check if this was main thread comment + // Show final note element on UI and perform form and action buttons cleanup + this.addNote($form, note); + this.reenableTargetFormSubmitButton(e); + } - if (note.commands_changes) { - this.handleQuickActions(note); - } + if (note.commands_changes) { + this.handleQuickActions(note); + } - $form.trigger('ajax:success', [note]); - }).fail(() => { - // Submission failed, remove placeholder note and show Flash error message - $notesContainer.find(`#${noteUniqueId}`).remove(); + $form.trigger('ajax:success', [note]); + }).fail(() => { + // Submission failed, remove placeholder note and show Flash error message + $notesContainer.find(`#${noteUniqueId}`).remove(); - if (hasQuickActions) { - $notesContainer.find(`#${systemNoteUniqueId}`).remove(); - } + if (hasQuickActions) { + $notesContainer.find(`#${systemNoteUniqueId}`).remove(); + } - // Show form again on UI on failure - if (isDiscussionForm && $notesContainer.length) { - const replyButton = $notesContainer.parent().find('.js-discussion-reply-button'); - this.replyToDiscussionNote(replyButton[0]); - $form = $notesContainer.parent().find('form'); - } + // Show form again on UI on failure + if (isDiscussionForm && $notesContainer.length) { + const replyButton = $notesContainer.parent().find('.js-discussion-reply-button'); + this.replyToDiscussionNote(replyButton[0]); + $form = $notesContainer.parent().find('form'); + } - $form.find('.js-note-text').val(formContent); - this.reenableTargetFormSubmitButton(e); - this.addNoteError($form); - }); + $form.find('.js-note-text').val(formContent); + this.reenableTargetFormSubmitButton(e); + this.addNoteError($form); + }); - return $closeBtn.text($closeBtn.data('original-text')); - }; + return $closeBtn.text($closeBtn.data('original-text')); + } + + /** + * This method does following tasks step-by-step whenever an existing comment + * is updated by user (both main thread comments as well as discussion comments). + * + * 1) Get Form metadata + * 2) Update note element with new content + * 3) Perform network request to submit the updated note using `gl.utils.ajaxPost` + * a) If request is successfully completed + * 1. Show submitted Note element + * b) If request failed + * 1. Revert Note element to original content + * 2. Show error Flash message about failure + */ + updateComment(e) { + e.preventDefault(); + + // Get Form metadata + const $submitBtn = $(e.target); + const $form = $submitBtn.parents('form'); + const $closeBtn = $form.find('.js-note-target-close'); + const $editingNote = $form.parents('.note.is-editing'); + const $noteBody = $editingNote.find('.js-task-list-container'); + const $noteBodyText = $noteBody.find('.note-text'); + const { formData, formContent, formAction } = this.getFormData($form); + + // Cache original comment content + const cachedNoteBodyText = $noteBodyText.html(); + + // Show updated comment content temporarily + $noteBodyText.html(_.escape(formContent)); + $editingNote.removeClass('is-editing fade-in-full').addClass('being-posted fade-in-half'); + $editingNote.find('.note-headline-meta a').html('<i class="fa fa-spinner fa-spin" aria-label="Comment is being updated" aria-hidden="true"></i>'); + + /* eslint-disable promise/catch-or-return */ + // Make request to update comment on server + gl.utils.ajaxPost(formAction, formData) + .then((note) => { + // Submission successful! render final note element + this.updateNote(note, $editingNote); + }) + .fail(() => { + // Submission failed, revert back to original note + $noteBodyText.html(_.escape(cachedNoteBodyText)); + $editingNote.removeClass('being-posted fade-in'); + $editingNote.find('.fa.fa-spinner').remove(); + + // Show Flash message about failure + this.updateNoteError(); + }); - /** - * This method does following tasks step-by-step whenever an existing comment - * is updated by user (both main thread comments as well as discussion comments). - * - * 1) Get Form metadata - * 2) Update note element with new content - * 3) Perform network request to submit the updated note using `gl.utils.ajaxPost` - * a) If request is successfully completed - * 1. Show submitted Note element - * b) If request failed - * 1. Revert Note element to original content - * 2. Show error Flash message about failure - */ - Notes.prototype.updateComment = function(e) { - e.preventDefault(); - - // Get Form metadata - const $submitBtn = $(e.target); - const $form = $submitBtn.parents('form'); - const $closeBtn = $form.find('.js-note-target-close'); - const $editingNote = $form.parents('.note.is-editing'); - const $noteBody = $editingNote.find('.js-task-list-container'); - const $noteBodyText = $noteBody.find('.note-text'); - const { formData, formContent, formAction } = this.getFormData($form); - - // Cache original comment content - const cachedNoteBodyText = $noteBodyText.html(); - - // Show updated comment content temporarily - $noteBodyText.html(_.escape(formContent)); - $editingNote.removeClass('is-editing fade-in-full').addClass('being-posted fade-in-half'); - $editingNote.find('.note-headline-meta a').html('<i class="fa fa-spinner fa-spin" aria-label="Comment is being updated" aria-hidden="true"></i>'); - - /* eslint-disable promise/catch-or-return */ - // Make request to update comment on server - gl.utils.ajaxPost(formAction, formData) - .then((note) => { - // Submission successful! render final note element - this.updateNote(note, $editingNote); - }) - .fail(() => { - // Submission failed, revert back to original note - $noteBodyText.html(_.escape(cachedNoteBodyText)); - $editingNote.removeClass('being-posted fade-in'); - $editingNote.find('.fa.fa-spinner').remove(); - - // Show Flash message about failure - this.updateNoteError(); - }); - - return $closeBtn.text($closeBtn.data('original-text')); - }; + return $closeBtn.text($closeBtn.data('original-text')); + } +} - return Notes; - })(); -}).call(window); +window.Notes = Notes; diff --git a/app/assets/javascripts/prometheus_metrics/constants.js b/app/assets/javascripts/prometheus_metrics/constants.js new file mode 100644 index 00000000000..50f1248456e --- /dev/null +++ b/app/assets/javascripts/prometheus_metrics/constants.js @@ -0,0 +1,5 @@ +export default { + EMPTY: 'empty', + LOADING: 'loading', + LIST: 'list', +}; diff --git a/app/assets/javascripts/prometheus_metrics/index.js b/app/assets/javascripts/prometheus_metrics/index.js new file mode 100644 index 00000000000..a0c43c5abe1 --- /dev/null +++ b/app/assets/javascripts/prometheus_metrics/index.js @@ -0,0 +1,6 @@ +import PrometheusMetrics from './prometheus_metrics'; + +$(() => { + const prometheusMetrics = new PrometheusMetrics('.js-prometheus-metrics-monitoring'); + prometheusMetrics.loadActiveMetrics(); +}); diff --git a/app/assets/javascripts/prometheus_metrics/prometheus_metrics.js b/app/assets/javascripts/prometheus_metrics/prometheus_metrics.js new file mode 100644 index 00000000000..ef4d6df5138 --- /dev/null +++ b/app/assets/javascripts/prometheus_metrics/prometheus_metrics.js @@ -0,0 +1,109 @@ +import PANEL_STATE from './constants'; + +export default class PrometheusMetrics { + constructor(wrapperSelector) { + this.backOffRequestCounter = 0; + + this.$wrapper = $(wrapperSelector); + + this.$monitoredMetricsPanel = this.$wrapper.find('.js-panel-monitored-metrics'); + this.$monitoredMetricsCount = this.$monitoredMetricsPanel.find('.js-monitored-count'); + this.$monitoredMetricsLoading = this.$monitoredMetricsPanel.find('.js-loading-metrics'); + this.$monitoredMetricsEmpty = this.$monitoredMetricsPanel.find('.js-empty-metrics'); + this.$monitoredMetricsList = this.$monitoredMetricsPanel.find('.js-metrics-list'); + + this.$missingEnvVarPanel = this.$wrapper.find('.js-panel-missing-env-vars'); + this.$panelToggle = this.$missingEnvVarPanel.find('.js-panel-toggle'); + this.$missingEnvVarMetricCount = this.$missingEnvVarPanel.find('.js-env-var-count'); + this.$missingEnvVarMetricsList = this.$missingEnvVarPanel.find('.js-missing-var-metrics-list'); + + this.activeMetricsEndpoint = this.$monitoredMetricsPanel.data('active-metrics'); + + this.$panelToggle.on('click', e => this.handlePanelToggle(e)); + } + + /* eslint-disable class-methods-use-this */ + handlePanelToggle(e) { + const $toggleBtn = $(e.currentTarget); + const $currentPanelBody = $toggleBtn.closest('.panel').find('.panel-body'); + $currentPanelBody.toggleClass('hidden'); + if ($toggleBtn.hasClass('fa-caret-down')) { + $toggleBtn.removeClass('fa-caret-down').addClass('fa-caret-right'); + } else { + $toggleBtn.removeClass('fa-caret-right').addClass('fa-caret-down'); + } + } + + showMonitoringMetricsPanelState(stateName) { + switch (stateName) { + case PANEL_STATE.LOADING: + this.$monitoredMetricsLoading.removeClass('hidden'); + this.$monitoredMetricsEmpty.addClass('hidden'); + this.$monitoredMetricsList.addClass('hidden'); + break; + case PANEL_STATE.LIST: + this.$monitoredMetricsLoading.addClass('hidden'); + this.$monitoredMetricsEmpty.addClass('hidden'); + this.$monitoredMetricsList.removeClass('hidden'); + break; + default: + this.$monitoredMetricsLoading.addClass('hidden'); + this.$monitoredMetricsEmpty.removeClass('hidden'); + this.$monitoredMetricsList.addClass('hidden'); + break; + } + } + + populateActiveMetrics(metrics) { + let totalMonitoredMetrics = 0; + let totalMissingEnvVarMetrics = 0; + + metrics.forEach((metric) => { + this.$monitoredMetricsList.append(`<li>${metric.group}<span class="badge">${metric.active_metrics}</span></li>`); + totalMonitoredMetrics += metric.active_metrics; + if (metric.metrics_missing_requirements > 0) { + this.$missingEnvVarMetricsList.append(`<li>${metric.group}</li>`); + totalMissingEnvVarMetrics += 1; + } + }); + + this.$monitoredMetricsCount.text(totalMonitoredMetrics); + this.showMonitoringMetricsPanelState(PANEL_STATE.LIST); + + if (totalMissingEnvVarMetrics > 0) { + this.$missingEnvVarPanel.removeClass('hidden'); + this.$missingEnvVarPanel.find('.flash-container').off('click'); + this.$missingEnvVarMetricCount.text(totalMissingEnvVarMetrics); + } + } + + loadActiveMetrics() { + this.showMonitoringMetricsPanelState(PANEL_STATE.LOADING); + gl.utils.backOff((next, stop) => { + $.getJSON(this.activeMetricsEndpoint) + .done((res) => { + if (res && res.success) { + stop(res); + } else { + this.backOffRequestCounter = this.backOffRequestCounter += 1; + if (this.backOffRequestCounter < 3) { + next(); + } else { + stop(res); + } + } + }) + .fail(stop); + }) + .then((res) => { + if (res && res.data && res.data.length) { + this.populateActiveMetrics(res.data); + } else { + this.showMonitoringMetricsPanelState(PANEL_STATE.EMPTY); + } + }) + .catch(() => { + this.showMonitoringMetricsPanelState(PANEL_STATE.EMPTY); + }); + } +} diff --git a/app/assets/javascripts/right_sidebar.js b/app/assets/javascripts/right_sidebar.js index da7c0c5a36c..322162afdb8 100644 --- a/app/assets/javascripts/right_sidebar.js +++ b/app/assets/javascripts/right_sidebar.js @@ -10,8 +10,6 @@ import Cookies from 'js-cookie'; this.$sidebarInner = this.sidebar.find('.issuable-sidebar'); this.$navGitlab = $('.navbar-gitlab'); - this.$layoutNav = $('.layout-nav'); - this.$subScroll = $('.sub-nav-scroll'); this.$rightSidebar = $('.js-right-sidebar'); this.removeListeners(); @@ -215,7 +213,7 @@ import Cookies from 'js-cookie'; }; Sidebar.prototype.setSidebarHeight = function() { - const $navHeight = this.$navGitlab.outerHeight() + this.$layoutNav.outerHeight() + (this.$subScroll ? this.$subScroll.outerHeight() : 0); + const $navHeight = this.$navGitlab.outerHeight(); const diff = $navHeight - $(window).scrollTop(); if (diff > 0) { this.$rightSidebar.outerHeight($(window).height() - diff); diff --git a/app/assets/javascripts/settings_panels.js b/app/assets/javascripts/settings_panels.js index 59ff2a86293..7fa5996d600 100644 --- a/app/assets/javascripts/settings_panels.js +++ b/app/assets/javascripts/settings_panels.js @@ -4,7 +4,7 @@ function expandSectionParent($section, $content) { } function expandSection($section) { - $section.find('.js-settings-toggle').text('Close'); + $section.find('.js-settings-toggle').text('Collapse'); const $content = $section.find('.settings-content'); $content.addClass('expanded').off('scroll.expandSection').scrollTop(0); diff --git a/app/assets/javascripts/users_select.js b/app/assets/javascripts/users_select.js index ec45253e50b..46efdcf4202 100644 --- a/app/assets/javascripts/users_select.js +++ b/app/assets/javascripts/users_select.js @@ -643,7 +643,7 @@ UsersSelect.prototype.formatResult = function(user) { } else { avatar = gon.default_avatar_url; } - return "<div class='user-result " + (!user.username ? 'no-username' : void 0) + "'> <div class='user-image'><img class='avatar s24' src='" + avatar + "'></div> <div class='user-name'>" + user.name + "</div> <div class='user-username'>" + (user.username || "") + "</div> </div>"; + return "<div class='user-result " + (!user.username ? 'no-username' : void 0) + "'> <div class='user-image'><img class='avatar avatar-inline s32' src='" + avatar + "'></div> <div class='user-name dropdown-menu-user-full-name'>" + user.name + "</div> <div class='user-username dropdown-menu-user-username'>" + ("@" + user.username || "") + "</div> </div>"; }; UsersSelect.prototype.formatSelection = function(user) { diff --git a/app/assets/javascripts/vue_merge_request_widget/components/mr_widget_related_links.js b/app/assets/javascripts/vue_merge_request_widget/components/mr_widget_related_links.js index 686cb38cbb1..205804670fa 100644 --- a/app/assets/javascripts/vue_merge_request_widget/components/mr_widget_related_links.js +++ b/app/assets/javascripts/vue_merge_request_widget/components/mr_widget_related_links.js @@ -1,63 +1,42 @@ export default { name: 'MRWidgetRelatedLinks', props: { - isMerged: { type: Boolean, required: true }, relatedLinks: { type: Object, required: true }, }, computed: { - // TODO: the following should be handled by i18n - closingText() { - if (this.isMerged) { - return `Closed ${this.issueLabel('closing')}`; - } - - return `Closes ${this.issueLabel('closing')}`; - }, hasLinks() { const { closing, mentioned, assignToMe } = this.relatedLinks; return closing || mentioned || assignToMe; }, - // TODO: the following should be handled by i18n - mentionedText() { - if (this.isMerged) { - if (this.hasMultipleIssues(this.relatedLinks.mentioned)) { - return 'are mentioned but were not closed'; - } - - return 'is mentioned but was not closed'; - } - - if (this.hasMultipleIssues(this.relatedLinks.mentioned)) { - return 'are mentioned but will not be closed'; - } - - return 'is mentioned but will not be closed'; - }, }, methods: { hasMultipleIssues(text) { - return /<\/a>,? and <a/.test(text); + return !text ? false : text.match(/<\/a> and <a/); }, - // TODO: the following should be handled by i18n issueLabel(field) { return this.hasMultipleIssues(this.relatedLinks[field]) ? 'issues' : 'issue'; }, + verbLabel(field) { + return this.hasMultipleIssues(this.relatedLinks[field]) ? 'are' : 'is'; + }, }, template: ` - <div v-if="hasLinks"> + <section + v-if="hasLinks" + class="mr-info-list mr-links"> <div class="legend"></div> <p v-if="relatedLinks.closing"> - {{closingText}} + Closes {{issueLabel('closing')}} <span v-html="relatedLinks.closing"></span>. </p> <p v-if="relatedLinks.mentioned"> <span class="capitalize">{{issueLabel('mentioned')}}</span> <span v-html="relatedLinks.mentioned"></span> - {{mentionedText}} + {{verbLabel('mentioned')}} mentioned but will not be closed. </p> <p v-if="relatedLinks.assignToMe"> <span v-html="relatedLinks.assignToMe"></span> </p> - </div> + </section> `, }; diff --git a/app/assets/javascripts/vue_merge_request_widget/components/states/mr_widget_merged.js b/app/assets/javascripts/vue_merge_request_widget/components/states/mr_widget_merged.js index 9b8eed9016d..c7d32d18141 100644 --- a/app/assets/javascripts/vue_merge_request_widget/components/states/mr_widget_merged.js +++ b/app/assets/javascripts/vue_merge_request_widget/components/states/mr_widget_merged.js @@ -1,9 +1,7 @@ /* global Flash */ import mrWidgetAuthorTime from '../../components/mr_widget_author_time'; -import mrWidgetRelatedLinks from '../../components/mr_widget_related_links'; import eventHub from '../../event_hub'; -import '../../../flash'; export default { name: 'MRWidgetMerged', @@ -13,7 +11,6 @@ export default { }, components: { 'mr-widget-author-and-time': mrWidgetAuthorTime, - 'mr-widget-related-links': mrWidgetRelatedLinks, }, data() { return { @@ -21,9 +18,6 @@ export default { }; }, computed: { - shouldRenderRelatedLinks() { - return this.mr.relatedLinks && this.mr.isMerged; - }, shouldShowRemoveSourceBranch() { const { sourceBranchRemoved, isRemovingSourceBranch, canRemoveSourceBranch } = this.mr; @@ -92,10 +86,6 @@ export default { aria-hidden="true" /> The source branch is being removed. </p> - <mr-widget-related-links - v-if="shouldRenderRelatedLinks" - :is-merged="mr.isMerged()" - :related-links="mr.relatedLinks" /> </section> <div v-if="shouldShowMergedButtons" diff --git a/app/assets/javascripts/vue_merge_request_widget/mr_widget_options.js b/app/assets/javascripts/vue_merge_request_widget/mr_widget_options.js index 222d0b7f79e..2339a00ddd0 100644 --- a/app/assets/javascripts/vue_merge_request_widget/mr_widget_options.js +++ b/app/assets/javascripts/vue_merge_request_widget/mr_widget_options.js @@ -48,7 +48,7 @@ export default { return stateMaps.stateToComponentMap[this.mr.state]; }, shouldRenderMergeHelp() { - return !this.mr.isMerged; + return stateMaps.statesToShowHelpWidget.indexOf(this.mr.state) > -1; }, shouldRenderPipelines() { return Object.keys(this.mr.pipeline).length || this.mr.hasCI; @@ -238,14 +238,9 @@ export default { :is="componentName" :mr="mr" :service="service" /> - <section + <mr-widget-related-links v-if="shouldRenderRelatedLinks" - class="mr-info-list mr-links"> - <div class="legend"></div> - <mr-widget-related-links - :is-merged="mr.isMerged" - :related-links="mr.relatedLinks" /> - </section> + :related-links="mr.relatedLinks" /> <mr-widget-merge-help v-if="shouldRenderMergeHelp" /> </div> `, diff --git a/app/assets/javascripts/vue_merge_request_widget/stores/mr_widget_store.js b/app/assets/javascripts/vue_merge_request_widget/stores/mr_widget_store.js index ad73efb37e1..69bc1436284 100644 --- a/app/assets/javascripts/vue_merge_request_widget/stores/mr_widget_store.js +++ b/app/assets/javascripts/vue_merge_request_widget/stores/mr_widget_store.js @@ -1,18 +1,6 @@ import Timeago from 'timeago.js'; import { getStateKey } from '../dependencies'; -const unmergedStates = [ - 'locked', - 'conflicts', - 'workInProgress', - 'readyToMerge', - 'checking', - 'unresolvedDiscussions', - 'pipelineFailed', - 'pipelineBlocked', - 'autoMergeFailed', -]; - export default class MergeRequestStore { constructor(data) { @@ -77,7 +65,6 @@ export default class MergeRequestStore { this.mergeActionsContentPath = data.commit_change_content_path; this.isRemovingSourceBranch = this.isRemovingSourceBranch || false; this.isOpen = data.state === 'opened' || data.state === 'reopened' || false; - this.isMerged = unmergedStates.indexOf(data.state) === -1; this.hasMergeableDiscussionsState = data.mergeable_discussions_state === false; this.canRemoveSourceBranch = currentUser.can_remove_source_branch || false; this.canMerge = !!data.merge_path; diff --git a/app/assets/javascripts/vue_merge_request_widget/stores/state_maps.js b/app/assets/javascripts/vue_merge_request_widget/stores/state_maps.js index dd939d98d0f..605dd3a1ff4 100644 --- a/app/assets/javascripts/vue_merge_request_widget/stores/state_maps.js +++ b/app/assets/javascripts/vue_merge_request_widget/stores/state_maps.js @@ -19,6 +19,19 @@ const stateToComponentMap = { shaMismatch: 'mr-widget-sha-mismatch', }; +const statesToShowHelpWidget = [ + 'locked', + 'conflicts', + 'workInProgress', + 'readyToMerge', + 'checking', + 'unresolvedDiscussions', + 'pipelineFailed', + 'pipelineBlocked', + 'autoMergeFailed', +]; + export default { stateToComponentMap, + statesToShowHelpWidget, }; diff --git a/app/assets/stylesheets/framework/dropdowns.scss b/app/assets/stylesheets/framework/dropdowns.scss index cba890ce831..4f54ca24940 100644 --- a/app/assets/stylesheets/framework/dropdowns.scss +++ b/app/assets/stylesheets/framework/dropdowns.scss @@ -395,6 +395,11 @@ .dropdown-menu-align-right { left: auto; right: 0; + margin-top: -5px; + + @media (max-width: $screen-xs-max) { + left: 0; + } } .dropdown-menu-selectable { diff --git a/app/assets/stylesheets/framework/header.scss b/app/assets/stylesheets/framework/header.scss index c2a17c22524..0f60a071d53 100644 --- a/app/assets/stylesheets/framework/header.scss +++ b/app/assets/stylesheets/framework/header.scss @@ -349,6 +349,7 @@ header { min-width: 140px; margin-top: -5px; color: $gl-text-color; + left: auto; .current-user { padding: 5px 18px; diff --git a/app/assets/stylesheets/framework/nav.scss b/app/assets/stylesheets/framework/nav.scss index 3787ef370b2..28b2a7cfacd 100644 --- a/app/assets/stylesheets/framework/nav.scss +++ b/app/assets/stylesheets/framework/nav.scss @@ -45,8 +45,7 @@ li { display: flex; - a, - .btn-link { + a { padding: $gl-btn-padding; padding-bottom: 11px; font-size: 14px; @@ -68,29 +67,7 @@ } } - .btn-link { - padding-top: 16px; - padding-left: 15px; - padding-right: 15px; - border-left: none; - border-right: none; - border-top: none; - border-radius: 0; - - &:hover, - &:active, - &:focus { - background-color: transparent; - } - - &:active { - outline: 0; - box-shadow: none; - } - } - - &.active a, - &.active .btn-link { + &.active a { border-bottom: 2px solid $link-underline-blue; color: $black; font-weight: 600; diff --git a/app/assets/stylesheets/framework/timeline.scss b/app/assets/stylesheets/framework/timeline.scss index 10881987038..3d68a50f91f 100644 --- a/app/assets/stylesheets/framework/timeline.scss +++ b/app/assets/stylesheets/framework/timeline.scss @@ -44,6 +44,10 @@ &:target, &.target { background: $line-target-blue; + + &.system-note .note-body .note-text.system-note-commit-list::after { + background: linear-gradient(rgba($line-target-blue, 0.1) -100px, $line-target-blue 100%); + } } .avatar { diff --git a/app/assets/stylesheets/framework/variables.scss b/app/assets/stylesheets/framework/variables.scss index 1fcd8f39922..988463990e3 100644 --- a/app/assets/stylesheets/framework/variables.scss +++ b/app/assets/stylesheets/framework/variables.scss @@ -327,6 +327,7 @@ $note-disabled-comment-color: #b2b2b2; $note-targe3-outside: #fffff0; $note-targe3-inside: #ffffd3; $note-line2-border: #ddd; +$note-icon-gutter-width: 55px; /* diff --git a/app/assets/stylesheets/pages/environments.scss b/app/assets/stylesheets/pages/environments.scss index 89bd437b362..1046ebfa2e2 100644 --- a/app/assets/stylesheets/pages/environments.scss +++ b/app/assets/stylesheets/pages/environments.scss @@ -83,6 +83,7 @@ .avatar { float: none; + margin-right: 0; } } diff --git a/app/assets/stylesheets/pages/members.scss b/app/assets/stylesheets/pages/members.scss index 4be0e133b69..f21005895e4 100644 --- a/app/assets/stylesheets/pages/members.scss +++ b/app/assets/stylesheets/pages/members.scss @@ -136,10 +136,6 @@ width: 250px; } - @media (min-width: $screen-md-min) { - width: 350px; - } - &.input-short { @media (min-width: $screen-md-min) { width: 170px; diff --git a/app/assets/stylesheets/pages/merge_requests.scss b/app/assets/stylesheets/pages/merge_requests.scss index c0bd045f1fc..59e0624d94e 100644 --- a/app/assets/stylesheets/pages/merge_requests.scss +++ b/app/assets/stylesheets/pages/merge_requests.scss @@ -372,10 +372,6 @@ margin-left: 12px; } - &.mr-state-locked + .mr-info-list.mr-links { - margin-top: -16px; - } - &.empty-state { .artwork { margin-bottom: $gl-padding; @@ -423,7 +419,7 @@ .commit { margin: 0; - padding: 10px 0; + padding: 10px; list-style: none; &:hover { diff --git a/app/assets/stylesheets/pages/note_form.scss b/app/assets/stylesheets/pages/note_form.scss index 69fed4e6bf7..9877ed2cfd6 100644 --- a/app/assets/stylesheets/pages/note_form.scss +++ b/app/assets/stylesheets/pages/note_form.scss @@ -148,8 +148,20 @@ padding: 6px 0; } -.notes-form > li { - border: 0; +.notes.notes-form > li.timeline-entry { + @include notes-media('max', $screen-sm-max) { + padding: 0; + } + + .timeline-content { + @include notes-media('max', $screen-sm-max) { + margin: 0; + } + } + + .timeline-entry-inner { + border: 0; + } } .note-edit-form { diff --git a/app/assets/stylesheets/pages/notes.scss b/app/assets/stylesheets/pages/notes.scss index 8b7df4dd72b..f0dbe4249c5 100644 --- a/app/assets/stylesheets/pages/notes.scss +++ b/app/assets/stylesheets/pages/notes.scss @@ -14,16 +14,6 @@ ul.notes { margin: 0; padding: 0; - .timeline-content { - margin-left: 55px; - - &.timeline-content-form { - @include notes-media('max', $screen-sm-max) { - margin-left: 0; - } - } - } - .note-created-ago, .note-updated-at { white-space: nowrap; @@ -46,17 +36,49 @@ ul.notes { } } - > li { - padding: $gl-padding $gl-btn-padding; + > li { // .timeline-entry + padding: 0; display: block; position: relative; - border-bottom: 1px solid $white-normal; + border-bottom: 0; + + @include notes-media('min', $screen-sm-min) { + padding-left: $note-icon-gutter-width; + } - &:last-child { - // Override `.timeline > li:last-child { border-bottom: none; }` + .timeline-entry-inner { + padding: $gl-padding $gl-btn-padding; border-bottom: 1px solid $white-normal; } + &:target, + &.target { + border-bottom: 1px solid $white-normal; + + &:not(:first-child) { + border-top: 1px solid $white-normal; + margin-top: -1px; + } + + .timeline-entry-inner { + border-bottom: 0; + } + } + + .timeline-icon { + @include notes-media('min', $screen-sm-min) { + margin-left: -$note-icon-gutter-width; + } + } + + .timeline-content { + margin-left: $note-icon-gutter-width; + + @include notes-media('min', $screen-sm-min) { + margin-left: 0; + } + } + &.being-posted { pointer-events: none; opacity: 0.5; @@ -73,7 +95,7 @@ ul.notes { } &.note-discussion { - &.timeline-entry { + .timeline-entry-inner { padding: $gl-padding 10px; } } @@ -152,13 +174,8 @@ ul.notes { .system-note { font-size: 14px; - padding-left: 0; clear: both; - @include notes-media('min', $screen-sm-min) { - margin-left: 65px; - } - .note-header-info { padding-bottom: 0; } @@ -192,13 +209,16 @@ ul.notes { .timeline-icon { float: left; + @include notes-media('min', $screen-sm-min) { + margin-left: 0; + width: auto; + } + svg { width: 16px; height: 16px; fill: $gray-darkest; - position: absolute; - left: 0; - top: 2px; + margin-top: 2px; } } @@ -250,7 +270,7 @@ ul.notes { &::after { content: ''; width: 100%; - height: 67px; + height: 70px; position: absolute; left: 0; bottom: 0; @@ -639,15 +659,12 @@ ul.notes { .discussion-body, .diff-file { .notes .note { - padding-left: $gl-padding; - padding-right: $gl-padding; - - &.system-note { - padding-left: 0; + border-bottom: 1px solid $white-normal; - @media (min-width: $screen-sm-min) { - margin-left: 70px; - } + .timeline-entry-inner { + padding-left: $gl-padding; + padding-right: $gl-padding; + border-bottom: none; } } } diff --git a/app/assets/stylesheets/pages/pipelines.scss b/app/assets/stylesheets/pages/pipelines.scss index a85ba3a5955..9637d26e56d 100644 --- a/app/assets/stylesheets/pages/pipelines.scss +++ b/app/assets/stylesheets/pages/pipelines.scss @@ -133,7 +133,7 @@ overflow: hidden; display: inline-block; white-space: nowrap; - vertical-align: top; + vertical-align: middle; text-overflow: ellipsis; } diff --git a/app/assets/stylesheets/pages/projects.scss b/app/assets/stylesheets/pages/projects.scss index 062665bc634..562ecbc6986 100644 --- a/app/assets/stylesheets/pages/projects.scss +++ b/app/assets/stylesheets/pages/projects.scss @@ -380,7 +380,7 @@ a.deploy-project-label { padding: 0; background: transparent; border: none; - line-height: 36px; + line-height: 34px; margin: 0; > li + li::before { diff --git a/app/assets/stylesheets/pages/settings.scss b/app/assets/stylesheets/pages/settings.scss index 7697a1b1c58..d69a8e0995c 100644 --- a/app/assets/stylesheets/pages/settings.scss +++ b/app/assets/stylesheets/pages/settings.scss @@ -126,3 +126,66 @@ margin-left: 5px; } } + +.prometheus-metrics-monitoring { + .panel { + .panel-toggle { + width: 14px; + } + + .badge { + font-size: inherit; + } + + .panel-heading .badge-count { + color: $white-light; + background: $common-gray-dark; + } + + .panel-body { + padding: 0; + } + + .flash-container { + margin-bottom: 0; + cursor: default; + + .flash-notice { + border-radius: 0; + } + } + } + + .loading-metrics, + .empty-metrics { + padding: 30px 10px; + + p, + .btn { + margin-top: 10px; + margin-bottom: 0; + } + } + + .loading-metrics .metrics-load-spinner { + color: $loading-color; + } + + .metrics-list { + margin-bottom: 0; + + li { + padding: $gl-padding; + + .badge { + margin-left: 5px; + background: $badge-bg; + } + } + + /* Ensure we don't add border if there's only single li */ + li + li { + border-top: 1px solid $border-color; + } + } +} diff --git a/app/assets/stylesheets/pages/tree.scss b/app/assets/stylesheets/pages/tree.scss index ab63225147f..ce1a13c6afa 100644 --- a/app/assets/stylesheets/pages/tree.scss +++ b/app/assets/stylesheets/pages/tree.scss @@ -1,6 +1,72 @@ .tree-holder { - > .nav-block { - margin: 11px 0; + .nav-block { + margin: 10px 0; + + @media (min-width: $screen-sm-min) { + display: flex; + + .tree-ref-container { + flex: 1; + } + + .tree-controls { + text-align: right; + + .btn-group { + margin-left: 10px; + } + } + + .tree-ref-holder { + float: left; + margin-right: 15px; + } + + .repo-breadcrumb { + li:last-of-type { + position: relative; + } + } + + .add-to-tree-dropdown { + position: absolute; + left: 18px; + } + } + } + + @media (max-width: $screen-xs-max) { + .repo-breadcrumb { + margin-top: 10px; + position: relative; + + .dropdown-menu { + min-width: 100%; + width: 100%; + left: inherit; + right: 0; + } + } + + .add-to-tree-dropdown { + position: absolute; + left: 0; + right: 0; + } + + .tree-controls { + margin-bottom: 10px; + + .btn, + .dropdown, + .btn-group { + width: 100%; + } + + .btn { + margin: 10px 0 0; + } + } } .file-finder { @@ -131,11 +197,6 @@ } } -.tree-ref-holder { - float: left; - margin-right: 15px; -} - .blob-commit-info { list-style: none; margin: 0; @@ -159,16 +220,6 @@ color: $md-link-color; } -.tree-controls { - float: right; - position: relative; - z-index: 2; - - .project-action-button { - margin-left: $btn-side-margin; - } -} - .repo-charts { .sub-header { margin: 20px 0; diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 91694ebcd1d..824ce845706 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -40,6 +40,10 @@ class ApplicationController < ActionController::Base render_404 end + rescue_from(ActionController::UnknownFormat) do + render_404 + end + rescue_from Gitlab::Access::AccessDeniedError do |exception| render_403 end diff --git a/app/controllers/concerns/creates_commit.rb b/app/controllers/concerns/creates_commit.rb index 36ad307a93b..1a9904bbe57 100644 --- a/app/controllers/concerns/creates_commit.rb +++ b/app/controllers/concerns/creates_commit.rb @@ -97,8 +97,8 @@ module CreatesCommit def merge_request_exists? return @merge_request if defined?(@merge_request) - @merge_request = MergeRequestsFinder.new(current_user, project_id: @project.id).execute.opened. - find_by(source_project_id: @project_to_commit_into, source_branch: @branch_name, target_branch: @start_branch) + @merge_request = MergeRequestsFinder.new(current_user, project_id: @project.id).execute.opened + .find_by(source_project_id: @project_to_commit_into, source_branch: @branch_name, target_branch: @start_branch) end def different_project? diff --git a/app/controllers/concerns/membership_actions.rb b/app/controllers/concerns/membership_actions.rb index 8d07780f6c2..47d9ae350ae 100644 --- a/app/controllers/concerns/membership_actions.rb +++ b/app/controllers/concerns/membership_actions.rb @@ -15,8 +15,8 @@ module MembershipActions end def destroy - Members::DestroyService.new(membershipable, current_user, params). - execute(:all) + Members::DestroyService.new(membershipable, current_user, params) + .execute(:all) respond_to do |format| format.html do @@ -42,8 +42,8 @@ module MembershipActions end def leave - member = Members::DestroyService.new(membershipable, current_user, user_id: current_user.id). - execute(:all) + member = Members::DestroyService.new(membershipable, current_user, user_id: current_user.id) + .execute(:all) notice = if member.request? diff --git a/app/controllers/dashboard/projects_controller.rb b/app/controllers/dashboard/projects_controller.rb index 641c502dbe4..91c1e4dff79 100644 --- a/app/controllers/dashboard/projects_controller.rb +++ b/app/controllers/dashboard/projects_controller.rb @@ -22,8 +22,8 @@ class Dashboard::ProjectsController < Dashboard::ApplicationController end def starred - @projects = load_projects(params.merge(starred: true)). - includes(:forked_from_project, :tags).page(params[:page]) + @projects = load_projects(params.merge(starred: true)) + .includes(:forked_from_project, :tags).page(params[:page]) @groups = [] @@ -45,8 +45,8 @@ class Dashboard::ProjectsController < Dashboard::ApplicationController end def load_projects(finder_params) - ProjectsFinder.new(params: finder_params, current_user: current_user). - execute.includes(:route, namespace: :route) + ProjectsFinder.new(params: finder_params, current_user: current_user) + .execute.includes(:route, namespace: :route) end def load_events diff --git a/app/controllers/explore/projects_controller.rb b/app/controllers/explore/projects_controller.rb index 8f1870759e4..741879dee35 100644 --- a/app/controllers/explore/projects_controller.rb +++ b/app/controllers/explore/projects_controller.rb @@ -49,7 +49,7 @@ class Explore::ProjectsController < Explore::ApplicationController private def load_projects - ProjectsFinder.new(current_user: current_user, params: params). - execute.includes(:route, namespace: :route) + ProjectsFinder.new(current_user: current_user, params: params) + .execute.includes(:route, namespace: :route) end end diff --git a/app/controllers/jwt_controller.rb b/app/controllers/jwt_controller.rb index 11db164b3fa..4bceb1d67a3 100644 --- a/app/controllers/jwt_controller.rb +++ b/app/controllers/jwt_controller.rb @@ -11,8 +11,8 @@ class JwtController < ApplicationController service = SERVICES[params[:service]] return head :not_found unless service - result = service.new(@authentication_result.project, @authentication_result.actor, auth_params). - execute(authentication_abilities: @authentication_result.authentication_abilities) + result = service.new(@authentication_result.project, @authentication_result.actor, auth_params) + .execute(authentication_abilities: @authentication_result.authentication_abilities) render json: result, status: result[:http_status] end diff --git a/app/controllers/omniauth_callbacks_controller.rb b/app/controllers/omniauth_callbacks_controller.rb index 2a8c8ca4bad..b82681b197e 100644 --- a/app/controllers/omniauth_callbacks_controller.rb +++ b/app/controllers/omniauth_callbacks_controller.rb @@ -144,7 +144,7 @@ class OmniauthCallbacksController < Devise::OmniauthCallbacksController end def log_audit_event(user, options = {}) - AuditEventService.new(user, user, options). - for_authentication.security_event + AuditEventService.new(user, user, options) + .for_authentication.security_event end end diff --git a/app/controllers/profiles_controller.rb b/app/controllers/profiles_controller.rb index 72f34930ca8..f98a9e24de1 100644 --- a/app/controllers/profiles_controller.rb +++ b/app/controllers/profiles_controller.rb @@ -49,9 +49,9 @@ class ProfilesController < Profiles::ApplicationController end def audit_log - @events = AuditEvent.where(entity_type: "User", entity_id: current_user.id). - order("created_at DESC"). - page(params[:page]) + @events = AuditEvent.where(entity_type: "User", entity_id: current_user.id) + .order("created_at DESC") + .page(params[:page]) end def update_username diff --git a/app/controllers/projects/application_controller.rb b/app/controllers/projects/application_controller.rb index 603a51266da..3d7ce4f0222 100644 --- a/app/controllers/projects/application_controller.rb +++ b/app/controllers/projects/application_controller.rb @@ -53,9 +53,21 @@ class Projects::ApplicationController < ApplicationController end end + def check_project_feature_available!(feature) + render_404 unless project.feature_available?(feature, current_user) + end + + def check_issuables_available! + render_404 unless project.feature_available?(:issues, current_user) || + project.feature_available?(:merge_requests, current_user) + end + def method_missing(method_sym, *arguments, &block) - if method_sym.to_s =~ /\Aauthorize_(.*)!\z/ + case method_sym.to_s + when /\Aauthorize_(.*)!\z/ authorize_action!($1.to_sym) + when /\Acheck_(.*)_available!\z/ + check_project_feature_available!($1.to_sym) else super end diff --git a/app/controllers/projects/blob_controller.rb b/app/controllers/projects/blob_controller.rb index 66e6a9a451c..a82d6fd5a4a 100644 --- a/app/controllers/projects/blob_controller.rb +++ b/app/controllers/projects/blob_controller.rb @@ -187,7 +187,7 @@ class Projects::BlobController < Projects::ApplicationController end def set_last_commit_sha - @last_commit_sha = Gitlab::Git::Commit. - last_for_path(@repository, @ref, @path).sha + @last_commit_sha = Gitlab::Git::Commit + .last_for_path(@repository, @ref, @path).sha end end diff --git a/app/controllers/projects/branches_controller.rb b/app/controllers/projects/branches_controller.rb index 70b06cfd9b4..94a752c21eb 100644 --- a/app/controllers/projects/branches_controller.rb +++ b/app/controllers/projects/branches_controller.rb @@ -37,8 +37,8 @@ class Projects::BranchesController < Projects::ApplicationController redirect_to_autodeploy = project.empty_repo? && project.deployment_services.present? - result = CreateBranchService.new(project, current_user). - execute(branch_name, ref) + result = CreateBranchService.new(project, current_user) + .execute(branch_name, ref) if params[:issue_iid] issue = IssuesFinder.new(current_user, project_id: @project.id).find_by(iid: params[:issue_iid]) diff --git a/app/controllers/projects/commits_controller.rb b/app/controllers/projects/commits_controller.rb index f33797ca310..37b5a6e9d48 100644 --- a/app/controllers/projects/commits_controller.rb +++ b/app/controllers/projects/commits_controller.rb @@ -18,11 +18,11 @@ class Projects::CommitsController < Projects::ApplicationController @repository.commits(@ref, path: @path, limit: @limit, offset: @offset) end - @note_counts = project.notes.where(commit_id: @commits.map(&:id)). - group(:commit_id).count + @note_counts = project.notes.where(commit_id: @commits.map(&:id)) + .group(:commit_id).count - @merge_request = MergeRequestsFinder.new(current_user, project_id: @project.id).execute.opened. - find_by(source_project: @project, source_branch: @ref, target_branch: @repository.root_ref) + @merge_request = MergeRequestsFinder.new(current_user, project_id: @project.id).execute.opened + .find_by(source_project: @project, source_branch: @ref, target_branch: @repository.root_ref) respond_to do |format| format.html diff --git a/app/controllers/projects/compare_controller.rb b/app/controllers/projects/compare_controller.rb index 88dd600e5fe..ef400c4d745 100644 --- a/app/controllers/projects/compare_controller.rb +++ b/app/controllers/projects/compare_controller.rb @@ -61,7 +61,7 @@ class Projects::CompareController < Projects::ApplicationController end def merge_request - @merge_request ||= MergeRequestsFinder.new(current_user, project_id: @project.id).execute.opened. - find_by(source_project: @project, source_branch: @head_ref, target_branch: @start_ref) + @merge_request ||= MergeRequestsFinder.new(current_user, project_id: @project.id).execute.opened + .find_by(source_project: @project, source_branch: @head_ref, target_branch: @start_ref) end end diff --git a/app/controllers/projects/deployments_controller.rb b/app/controllers/projects/deployments_controller.rb index 6644deb49c9..47c312ffddf 100644 --- a/app/controllers/projects/deployments_controller.rb +++ b/app/controllers/projects/deployments_controller.rb @@ -22,6 +22,22 @@ class Projects::DeploymentsController < Projects::ApplicationController render_404 end + def additional_metrics + return render_404 unless deployment.has_additional_metrics? + + respond_to do |format| + format.json do + metrics = deployment.additional_metrics + + if metrics.any? + render json: metrics + else + head :no_content + end + end + end + end + private def deployment diff --git a/app/controllers/projects/discussions_controller.rb b/app/controllers/projects/discussions_controller.rb index f4a18a5e8f7..2e6ab7903b8 100644 --- a/app/controllers/projects/discussions_controller.rb +++ b/app/controllers/projects/discussions_controller.rb @@ -1,5 +1,5 @@ class Projects::DiscussionsController < Projects::ApplicationController - before_action :module_enabled + before_action :check_merge_requests_available! before_action :merge_request before_action :discussion before_action :authorize_resolve_discussion! @@ -34,8 +34,4 @@ class Projects::DiscussionsController < Projects::ApplicationController def authorize_resolve_discussion! access_denied! unless discussion.can_resolve?(current_user) end - - def module_enabled - render_404 unless @project.feature_available?(:merge_requests, current_user) - end end diff --git a/app/controllers/projects/environments_controller.rb b/app/controllers/projects/environments_controller.rb index efe83776834..f88a1ffd1e9 100644 --- a/app/controllers/projects/environments_controller.rb +++ b/app/controllers/projects/environments_controller.rb @@ -129,6 +129,16 @@ class Projects::EnvironmentsController < Projects::ApplicationController end end + def additional_metrics + respond_to do |format| + format.json do + additional_metrics = environment.additional_metrics || {} + + render json: additional_metrics, status: additional_metrics.any? ? :ok : :no_content + end + end + end + private def verify_api_request! diff --git a/app/controllers/projects/issues_controller.rb b/app/controllers/projects/issues_controller.rb index 56f76e752d0..dfc6baa34a4 100644 --- a/app/controllers/projects/issues_controller.rb +++ b/app/controllers/projects/issues_controller.rb @@ -9,7 +9,7 @@ class Projects::IssuesController < Projects::ApplicationController prepend_before_action :authenticate_user!, only: [:new] before_action :redirect_to_external_issue_tracker, only: [:index, :new] - before_action :module_enabled + before_action :check_issues_available! before_action :issue, except: [:index, :new, :create, :bulk_update] # Allow write(create) issue @@ -250,7 +250,7 @@ class Projects::IssuesController < Projects::ApplicationController return render_404 unless can?(current_user, :push_code, @project) && @issue.can_be_worked_on?(current_user) end - def module_enabled + def check_issues_available! return render_404 unless @project.feature_available?(:issues, current_user) && @project.default_issues_tracker? end diff --git a/app/controllers/projects/labels_controller.rb b/app/controllers/projects/labels_controller.rb index 1beac202efe..daa973c9281 100644 --- a/app/controllers/projects/labels_controller.rb +++ b/app/controllers/projects/labels_controller.rb @@ -1,7 +1,7 @@ class Projects::LabelsController < Projects::ApplicationController include ToggleSubscriptionAction - before_action :module_enabled + before_action :check_issuables_available! before_action :label, only: [:edit, :update, :destroy, :promote] before_action :find_labels, only: [:index, :set_priorities, :remove_priority, :toggle_subscription] before_action :authorize_read_label! @@ -135,12 +135,6 @@ class Projects::LabelsController < Projects::ApplicationController protected - def module_enabled - unless @project.feature_available?(:issues, current_user) || @project.feature_available?(:merge_requests, current_user) - return render_404 - end - end - def label_params params.require(:label).permit(:title, :description, :color) end diff --git a/app/controllers/projects/merge_requests_controller.rb b/app/controllers/projects/merge_requests_controller.rb index 314906b5f09..879ff6d393e 100644 --- a/app/controllers/projects/merge_requests_controller.rb +++ b/app/controllers/projects/merge_requests_controller.rb @@ -7,7 +7,7 @@ class Projects::MergeRequestsController < Projects::ApplicationController include ToggleAwardEmoji include IssuableCollections - before_action :module_enabled + before_action :check_merge_requests_available! before_action :merge_request, only: [ :edit, :update, :show, :diffs, :commits, :conflicts, :conflict_for_path, :pipelines, :merge, :pipeline_status, :ci_environments_status, :toggle_subscription, :cancel_merge_when_pipeline_succeeds, :remove_wip, :resolve_conflicts, :assign_related_issues, :commit_change_content @@ -143,8 +143,8 @@ class Projects::MergeRequestsController < Projects::ApplicationController # Get commits from repository # or from cache if already merged @commits = @merge_request.commits - @note_counts = Note.where(commit_id: @commits.map(&:id)). - group(:commit_id).count + @note_counts = Note.where(commit_id: @commits.map(&:id)) + .group(:commit_id).count render json: { html: view_to_html_string('projects/merge_requests/show/_commits') } end @@ -192,9 +192,9 @@ class Projects::MergeRequestsController < Projects::ApplicationController end begin - MergeRequests::Conflicts::ResolveService. - new(merge_request). - execute(current_user, params) + MergeRequests::Conflicts::ResolveService + .new(merge_request) + .execute(current_user, params) flash[:notice] = 'All merge conflicts were resolved. The merge request can now be merged.' @@ -461,10 +461,6 @@ class Projects::MergeRequestsController < Projects::ApplicationController return render_404 unless @conflicts_list.can_be_resolved_by?(current_user) end - def module_enabled - return render_404 unless @project.feature_available?(:merge_requests, current_user) - end - def validates_merge_request # Show git not found page # if there is no saved commits between source & target branch @@ -562,8 +558,8 @@ class Projects::MergeRequestsController < Projects::ApplicationController @commits = @merge_request.compare_commits.reverse @commit = @merge_request.diff_head_commit - @note_counts = Note.where(commit_id: @commits.map(&:id)). - group(:commit_id).count + @note_counts = Note.where(commit_id: @commits.map(&:id)) + .group(:commit_id).count @labels = LabelsFinder.new(current_user, project_id: @project.id).execute @@ -579,10 +575,10 @@ class Projects::MergeRequestsController < Projects::ApplicationController def merge_request_params params.require(:merge_request) - .permit(merge_request_params_ce) + .permit(merge_request_params_attributes) end - def merge_request_params_ce + def merge_request_params_attributes [ :assignee_id, :description, @@ -602,7 +598,11 @@ class Projects::MergeRequestsController < Projects::ApplicationController end def merge_params - params.permit(:should_remove_source_branch, :commit_message) + params.permit(merge_params_attributes) + end + + def merge_params_attributes + [:should_remove_source_branch, :commit_message] end # Make sure merge requests created before 8.0 diff --git a/app/controllers/projects/milestones_controller.rb b/app/controllers/projects/milestones_controller.rb index 62410d7f57f..953b1e83e49 100644 --- a/app/controllers/projects/milestones_controller.rb +++ b/app/controllers/projects/milestones_controller.rb @@ -1,7 +1,7 @@ class Projects::MilestonesController < Projects::ApplicationController include MilestoneActions - before_action :module_enabled + before_action :check_issuables_available! before_action :milestone, only: [:edit, :update, :destroy, :show, :merge_requests, :participants, :labels] # Allow read any milestone @@ -95,12 +95,6 @@ class Projects::MilestonesController < Projects::ApplicationController return render_404 unless can?(current_user, :admin_milestone, @project) end - def module_enabled - unless @project.feature_available?(:issues, current_user) || @project.feature_available?(:merge_requests, current_user) - return render_404 - end - end - def milestone_params params.require(:milestone).permit(:title, :description, :start_date, :due_date, :state_event) end diff --git a/app/controllers/projects/prometheus_controller.rb b/app/controllers/projects/prometheus_controller.rb new file mode 100644 index 00000000000..507468d7102 --- /dev/null +++ b/app/controllers/projects/prometheus_controller.rb @@ -0,0 +1,24 @@ +class Projects::PrometheusController < Projects::ApplicationController + before_action :authorize_read_project! + before_action :require_prometheus_metrics! + + def active_metrics + respond_to do |format| + format.json do + matched_metrics = project.prometheus_service.matched_metrics || {} + + if matched_metrics.any? + render json: matched_metrics + else + head :no_content + end + end + end + end + + private + + def require_prometheus_metrics! + render_404 unless project.prometheus_service.present? + end +end diff --git a/app/controllers/projects/settings/ci_cd_controller.rb b/app/controllers/projects/settings/ci_cd_controller.rb index 6f009d61950..24fe78bc1bd 100644 --- a/app/controllers/projects/settings/ci_cd_controller.rb +++ b/app/controllers/projects/settings/ci_cd_controller.rb @@ -14,8 +14,8 @@ module Projects def define_runners_variables @project_runners = @project.runners.ordered - @assignable_runners = current_user.ci_authorized_runners. - assignable_for(project).ordered.page(params[:page]).per(20) + @assignable_runners = current_user.ci_authorized_runners + .assignable_for(project).ordered.page(params[:page]).per(20) @shared_runners = Ci::Runner.shared.active @shared_runners_count = @shared_runners.count(:all) end diff --git a/app/controllers/projects/snippets_controller.rb b/app/controllers/projects/snippets_controller.rb index 8a8f8d6a27d..98dd307bd9d 100644 --- a/app/controllers/projects/snippets_controller.rb +++ b/app/controllers/projects/snippets_controller.rb @@ -5,7 +5,7 @@ class Projects::SnippetsController < Projects::ApplicationController include SnippetsActions include RendersBlob - before_action :module_enabled + before_action :check_snippets_available! before_action :snippet, only: [:show, :edit, :destroy, :update, :raw, :toggle_award_emoji, :mark_as_spam] # Allow read any snippet @@ -102,10 +102,6 @@ class Projects::SnippetsController < Projects::ApplicationController return render_404 unless can?(current_user, :admin_project_snippet, @snippet) end - def module_enabled - return render_404 unless @project.feature_available?(:snippets, current_user) - end - def snippet_params params.require(:project_snippet).permit(:title, :content, :file_name, :private, :visibility_level, :description) end diff --git a/app/controllers/projects/tags_controller.rb b/app/controllers/projects/tags_controller.rb index afbea3e2b40..ebc9f4edab4 100644 --- a/app/controllers/projects/tags_controller.rb +++ b/app/controllers/projects/tags_controller.rb @@ -29,8 +29,8 @@ class Projects::TagsController < Projects::ApplicationController end def create - result = Tags::CreateService.new(@project, current_user). - execute(params[:tag_name], params[:ref], params[:message], params[:release_description]) + result = Tags::CreateService.new(@project, current_user) + .execute(params[:tag_name], params[:ref], params[:message], params[:release_description]) if result[:status] == :success @tag = result[:tag] diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb index d7c702b94f8..0d8186dce02 100644 --- a/app/controllers/sessions_controller.rb +++ b/app/controllers/sessions_controller.rb @@ -128,8 +128,8 @@ class SessionsController < Devise::SessionsController end def log_audit_event(user, options = {}) - AuditEventService.new(user, user, options). - for_authentication.security_event + AuditEventService.new(user, user, options) + .for_authentication.security_event end def log_user_activity(user) diff --git a/app/controllers/sherlock/application_controller.rb b/app/controllers/sherlock/application_controller.rb index 682ca5e3821..6bdd3568a78 100644 --- a/app/controllers/sherlock/application_controller.rb +++ b/app/controllers/sherlock/application_controller.rb @@ -4,8 +4,8 @@ module Sherlock def find_transaction if params[:transaction_id] - @transaction = Gitlab::Sherlock.collection. - find_transaction(params[:transaction_id]) + @transaction = Gitlab::Sherlock.collection + .find_transaction(params[:transaction_id]) end end end diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index c211106fbaa..8131eba6a2f 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -106,11 +106,11 @@ class UsersController < ApplicationController def load_events # Get user activity feed for projects common for both users - @events = user.recent_events. - merge(projects_for_current_user). - references(:project). - with_associations. - limit_recent(20, params[:offset]) + @events = user.recent_events + .merge(projects_for_current_user) + .references(:project) + .with_associations + .limit_recent(20, params[:offset]) end def load_projects diff --git a/app/finders/events_finder.rb b/app/finders/events_finder.rb index 29beb6cb224..46ecbaba73a 100644 --- a/app/finders/events_finder.rb +++ b/app/finders/events_finder.rb @@ -33,8 +33,8 @@ class EventsFinder private def by_current_user_access(events) - events.merge(ProjectsFinder.new(current_user: current_user).execute). - joins(:project) + events.merge(ProjectsFinder.new(current_user: current_user).execute) + .joins(:project) end def by_action(events) diff --git a/app/finders/group_members_finder.rb b/app/finders/group_members_finder.rb index fce3775f40e..067aff408df 100644 --- a/app/finders/group_members_finder.rb +++ b/app/finders/group_members_finder.rb @@ -8,9 +8,9 @@ class GroupMembersFinder return group_members unless @group.parent - parents_members = GroupMember.non_request. - where(source_id: @group.ancestors.select(:id)). - where.not(user_id: @group.users.select(:id)) + parents_members = GroupMember.non_request + .where(source_id: @group.ancestors.select(:id)) + .where.not(user_id: @group.users.select(:id)) wheres = ["members.id IN (#{group_members.select(:id).to_sql})"] wheres << "members.id IN (#{parents_members.select(:id).to_sql})" diff --git a/app/helpers/commits_helper.rb b/app/helpers/commits_helper.rb index 5b5cdebe919..0accd1f8d77 100644 --- a/app/helpers/commits_helper.rb +++ b/app/helpers/commits_helper.rb @@ -85,20 +85,20 @@ module CommitsHelper if @path.blank? return link_to( - "Browse Files", + _("Browse Files"), namespace_project_tree_path(project.namespace, project, commit), class: "btn btn-default" ) elsif @repo.blob_at(commit.id, @path) return link_to( - "Browse File", + _("Browse File"), namespace_project_blob_path(project.namespace, project, tree_join(commit.id, @path)), class: "btn btn-default" ) elsif @path.present? return link_to( - "Browse Directory", + _("Browse Directory"), namespace_project_tree_path(project.namespace, project, tree_join(commit.id, @path)), class: "btn btn-default" diff --git a/app/helpers/form_helper.rb b/app/helpers/form_helper.rb index 014fc46b130..8ceb5c36bda 100644 --- a/app/helpers/form_helper.rb +++ b/app/helpers/form_helper.rb @@ -8,10 +8,10 @@ module FormHelper content_tag(:div, class: 'alert alert-danger', id: 'error_explanation') do content_tag(:h4, headline) << content_tag(:ul) do - model.errors.full_messages. - map { |msg| content_tag(:li, msg) }. - join. - html_safe + model.errors.full_messages + .map { |msg| content_tag(:li, msg) } + .join + .html_safe end end end diff --git a/app/helpers/projects_helper.rb b/app/helpers/projects_helper.rb index 0d0459f5a70..d10e0bd45b0 100644 --- a/app/helpers/projects_helper.rb +++ b/app/helpers/projects_helper.rb @@ -194,8 +194,8 @@ module ProjectsHelper end def load_pipeline_status(projects) - Gitlab::Cache::Ci::ProjectPipelineStatus. - load_in_batch_for_projects(projects) + Gitlab::Cache::Ci::ProjectPipelineStatus + .load_in_batch_for_projects(projects) end private diff --git a/app/helpers/search_helper.rb b/app/helpers/search_helper.rb index 9c46035057f..8f15904f068 100644 --- a/app/helpers/search_helper.rb +++ b/app/helpers/search_helper.rb @@ -97,8 +97,8 @@ module SearchHelper # Autocomplete results for the current user's projects def projects_autocomplete(term, limit = 5) - current_user.authorized_projects.search_by_title(term). - sorted_by_stars.non_archived.limit(limit).map do |p| + current_user.authorized_projects.search_by_title(term) + .sorted_by_stars.non_archived.limit(limit).map do |p| { category: "Projects", id: p.id, diff --git a/app/helpers/users_helper.rb b/app/helpers/users_helper.rb index 9c623c9ba7c..b5f54d3e154 100644 --- a/app/helpers/users_helper.rb +++ b/app/helpers/users_helper.rb @@ -4,4 +4,14 @@ module UsersHelper title: user.email, class: 'has-tooltip commit-committer-link') end + + def user_email_help_text(user) + return 'We also use email for avatar detection if no avatar is uploaded.' unless user.unconfirmed_email.present? + + confirmation_link = link_to 'Resend confirmation e-mail', user_confirmation_path(user: { email: @user.unconfirmed_email }), method: :post + + h('Please click the link in the confirmation email before continuing. It was sent to ') + + content_tag(:strong) { user.unconfirmed_email } + h('.') + + content_tag(:p) { confirmation_link } + end end diff --git a/app/helpers/wiki_helper.rb b/app/helpers/wiki_helper.rb index 3e3f6246fc5..99212a3438f 100644 --- a/app/helpers/wiki_helper.rb +++ b/app/helpers/wiki_helper.rb @@ -6,8 +6,8 @@ module WikiHelper # Returns a String composed of the capitalized name of each directory and the # capitalized name of the page itself. def breadcrumb(page_slug) - page_slug.split('/'). - map { |dir_or_page| WikiPage.unhyphenize(dir_or_page).capitalize }. - join(' / ') + page_slug.split('/') + .map { |dir_or_page| WikiPage.unhyphenize(dir_or_page).capitalize } + .join(' / ') end end diff --git a/app/models/award_emoji.rb b/app/models/award_emoji.rb index ebe60441603..91b62dabbcd 100644 --- a/app/models/award_emoji.rb +++ b/app/models/award_emoji.rb @@ -19,9 +19,9 @@ class AwardEmoji < ActiveRecord::Base class << self def votes_for_collection(ids, type) - select('name', 'awardable_id', 'COUNT(*) as count'). - where('name IN (?) AND awardable_type = ? AND awardable_id IN (?)', [DOWNVOTE_NAME, UPVOTE_NAME], type, ids). - group('name', 'awardable_id') + select('name', 'awardable_id', 'COUNT(*) as count') + .where('name IN (?) AND awardable_type = ? AND awardable_id IN (?)', [DOWNVOTE_NAME, UPVOTE_NAME], type, ids) + .group('name', 'awardable_id') end end diff --git a/app/models/ci/build.rb b/app/models/ci/build.rb index 58758f7ca8a..a300536532b 100644 --- a/app/models/ci/build.rb +++ b/app/models/ci/build.rb @@ -138,17 +138,6 @@ module Ci ExpandVariables.expand(environment, simple_variables) if environment end - def environment_url - return @environment_url if defined?(@environment_url) - - @environment_url = - if unexpanded_url = options&.dig(:environment, :url) - ExpandVariables.expand(unexpanded_url, simple_variables) - else - persisted_environment&.external_url - end - end - def has_environment? environment.present? end @@ -192,7 +181,7 @@ module Ci slugified.gsub(/[^a-z0-9]/, '-')[0..62] end - # Variables whose value does not depend on other variables + # Variables whose value does not depend on environment def simple_variables variables = predefined_variables variables += project.predefined_variables @@ -207,7 +196,8 @@ module Ci variables end - # All variables, including those dependent on other variables + # All variables, including those dependent on environment, which could + # contain unexpanded variables. def variables simple_variables.concat(persisted_environment_variables) end @@ -481,9 +471,10 @@ module Ci variables = persisted_environment.predefined_variables - if url = environment_url - variables << { key: 'CI_ENVIRONMENT_URL', value: url, public: true } - end + # Here we're passing unexpanded environment_url for runner to expand, + # and we need to make sure that CI_ENVIRONMENT_NAME and + # CI_ENVIRONMENT_SLUG so on are available for the URL be expanded. + variables << { key: 'CI_ENVIRONMENT_URL', value: environment_url, public: true } if environment_url variables end @@ -506,6 +497,10 @@ module Ci variables end + def environment_url + options&.dig(:environment, :url) || persisted_environment&.external_url + end + def build_attributes_from_config return {} unless pipeline.config_processor diff --git a/app/models/ci/pipeline.rb b/app/models/ci/pipeline.rb index 9ddecba5183..1b3e5a25ac2 100644 --- a/app/models/ci/pipeline.rb +++ b/app/models/ci/pipeline.rb @@ -168,8 +168,8 @@ module Ci end def stages_names - statuses.order(:stage_idx).distinct. - pluck(:stage, :stage_idx).map(&:first) + statuses.order(:stage_idx).distinct + .pluck(:stage, :stage_idx).map(&:first) end def legacy_stage(name) diff --git a/app/models/ci/runner.rb b/app/models/ci/runner.rb index 487ba61bc9c..d12f96f3d0b 100644 --- a/app/models/ci/runner.rb +++ b/app/models/ci/runner.rb @@ -30,8 +30,8 @@ module Ci scope :assignable_for, ->(project) do # FIXME: That `to_sql` is needed to workaround a weird Rails bug. # Without that, placeholders would miss one and couldn't match. - where(locked: false). - where.not("id IN (#{project.runners.select(:id).to_sql})").specific + where(locked: false) + .where.not("id IN (#{project.runners.select(:id).to_sql})").specific end validate :tag_constraints diff --git a/app/models/concerns/issuable.rb b/app/models/concerns/issuable.rb index 8e367576c9d..d178ee4422b 100644 --- a/app/models/concerns/issuable.rb +++ b/app/models/concerns/issuable.rb @@ -161,9 +161,9 @@ module Issuable # milestones_due_date = 'MIN(milestones.due_date)' - order_milestone_due_asc. - order_labels_priority(excluded_labels: excluded_labels, extra_select_columns: [milestones_due_date]). - reorder(Gitlab::Database.nulls_last_order(milestones_due_date, 'ASC'), + order_milestone_due_asc + .order_labels_priority(excluded_labels: excluded_labels, extra_select_columns: [milestones_due_date]) + .reorder(Gitlab::Database.nulls_last_order(milestones_due_date, 'ASC'), Gitlab::Database.nulls_last_order('highest_priority', 'ASC')) end @@ -182,9 +182,9 @@ module Issuable "(#{highest_priority}) AS highest_priority" ] + extra_select_columns - select(select_columns.join(', ')). - group(arel_table[:id]). - reorder(Gitlab::Database.nulls_last_order('highest_priority', 'ASC')) + select(select_columns.join(', ')) + .group(arel_table[:id]) + .reorder(Gitlab::Database.nulls_last_order('highest_priority', 'ASC')) end def with_label(title, sort = nil) diff --git a/app/models/concerns/relative_positioning.rb b/app/models/concerns/relative_positioning.rb index f1d8532a6d6..7cb9a28a284 100644 --- a/app/models/concerns/relative_positioning.rb +++ b/app/models/concerns/relative_positioning.rb @@ -18,10 +18,10 @@ module RelativePositioning prev_pos = nil if self.relative_position - prev_pos = self.class. - in_projects(project.id). - where('relative_position < ?', self.relative_position). - maximum(:relative_position) + prev_pos = self.class + .in_projects(project.id) + .where('relative_position < ?', self.relative_position) + .maximum(:relative_position) end prev_pos @@ -31,10 +31,10 @@ module RelativePositioning next_pos = nil if self.relative_position - next_pos = self.class. - in_projects(project.id). - where('relative_position > ?', self.relative_position). - minimum(:relative_position) + next_pos = self.class + .in_projects(project.id) + .where('relative_position > ?', self.relative_position) + .minimum(:relative_position) end next_pos diff --git a/app/models/concerns/routable.rb b/app/models/concerns/routable.rb index 63d02b76f6b..ec7796a9dbb 100644 --- a/app/models/concerns/routable.rb +++ b/app/models/concerns/routable.rb @@ -107,6 +107,14 @@ module Routable RequestStore[key] ||= uncached_full_path end + def build_full_path + if parent && path + parent.full_path + '/' + path + else + path + end + end + private def uncached_full_path @@ -135,14 +143,6 @@ module Routable end end - def build_full_path - if parent && path - parent.full_path + '/' + path - else - path - end - end - def update_route prepare_route route.save diff --git a/app/models/concerns/sortable.rb b/app/models/concerns/sortable.rb index b9a2d812edd..a155a064032 100644 --- a/app/models/concerns/sortable.rb +++ b/app/models/concerns/sortable.rb @@ -39,12 +39,12 @@ module Sortable private def highest_label_priority(target_type_column: nil, target_type: nil, target_column:, project_column:, excluded_labels: []) - query = Label.select(LabelPriority.arel_table[:priority].minimum). - left_join_priorities. - joins(:label_links). - where("label_priorities.project_id = #{project_column}"). - where("label_links.target_id = #{target_column}"). - reorder(nil) + query = Label.select(LabelPriority.arel_table[:priority].minimum) + .left_join_priorities + .joins(:label_links) + .where("label_priorities.project_id = #{project_column}") + .where("label_links.target_id = #{target_column}") + .reorder(nil) query = if target_type_column diff --git a/app/models/concerns/subscribable.rb b/app/models/concerns/subscribable.rb index 83daa9b1a64..f60a0f8f438 100644 --- a/app/models/concerns/subscribable.rb +++ b/app/models/concerns/subscribable.rb @@ -27,16 +27,16 @@ module Subscribable end def subscribers(project) - subscriptions_available(project). - where(subscribed: true). - map(&:user) + subscriptions_available(project) + .where(subscribed: true) + .map(&:user) end def toggle_subscription(user, project = nil) unsubscribe_from_other_levels(user, project) - find_or_initialize_subscription(user, project). - update(subscribed: !subscribed?(user, project)) + find_or_initialize_subscription(user, project) + .update(subscribed: !subscribed?(user, project)) end def subscribe(user, project = nil) @@ -69,14 +69,14 @@ module Subscribable end def find_or_initialize_subscription(user, project) - subscriptions. - find_or_initialize_by(user_id: user.id, project_id: project.try(:id)) + subscriptions + .find_or_initialize_by(user_id: user.id, project_id: project.try(:id)) end def subscriptions_available(project) t = Subscription.arel_table - subscriptions. - where(t[:project_id].eq(nil).or(t[:project_id].eq(project.try(:id)))) + subscriptions + .where(t[:project_id].eq(nil).or(t[:project_id].eq(project.try(:id)))) end end diff --git a/app/models/deployment.rb b/app/models/deployment.rb index 85e7901dfee..056c49e7162 100644 --- a/app/models/deployment.rb +++ b/app/models/deployment.rb @@ -58,10 +58,10 @@ class Deployment < ActiveRecord::Base def update_merge_request_metrics! return unless environment.update_merge_request_metrics? - merge_requests = project.merge_requests. - joins(:metrics). - where(target_branch: self.ref, merge_request_metrics: { first_deployed_to_production_at: nil }). - where("merge_request_metrics.merged_at <= ?", self.created_at) + merge_requests = project.merge_requests + .joins(:metrics) + .where(target_branch: self.ref, merge_request_metrics: { first_deployed_to_production_at: nil }) + .where("merge_request_metrics.merged_at <= ?", self.created_at) if previous_deployment merge_requests = merge_requests.where("merge_request_metrics.merged_at >= ?", previous_deployment.created_at) @@ -76,17 +76,17 @@ class Deployment < ActiveRecord::Base merge_requests.map(&:id) end - MergeRequest::Metrics. - where(merge_request_id: merge_request_ids, first_deployed_to_production_at: nil). - update_all(first_deployed_to_production_at: self.created_at) + MergeRequest::Metrics + .where(merge_request_id: merge_request_ids, first_deployed_to_production_at: nil) + .update_all(first_deployed_to_production_at: self.created_at) end def previous_deployment @previous_deployment ||= - project.deployments.joins(:environment). - where(environments: { name: self.environment.name }, ref: self.ref). - where.not(id: self.id). - take + project.deployments.joins(:environment) + .where(environments: { name: self.environment.name }, ref: self.ref) + .where.not(id: self.id) + .take end def stop_action @@ -114,6 +114,17 @@ class Deployment < ActiveRecord::Base project.monitoring_service.deployment_metrics(self) end + def has_additional_metrics? + project.prometheus_service.present? + end + + def additional_metrics + return {} unless project.prometheus_service.present? + + metrics = project.prometheus_service.additional_deployment_metrics(self) + metrics&.merge(deployment_time: created_at.to_i) || {} + end + private def ref_path diff --git a/app/models/environment.rb b/app/models/environment.rb index d5b974b2d31..7ad36f1d80c 100644 --- a/app/models/environment.rb +++ b/app/models/environment.rb @@ -40,9 +40,9 @@ class Environment < ActiveRecord::Base scope :stopped, -> { with_state(:stopped) } scope :order_by_last_deployed_at, -> do max_deployment_id_sql = - Deployment.select(Deployment.arel_table[:id].maximum). - where(Deployment.arel_table[:environment_id].eq(arel_table[:id])). - to_sql + Deployment.select(Deployment.arel_table[:id].maximum) + .where(Deployment.arel_table[:environment_id].eq(arel_table[:id])) + .to_sql order(Gitlab::Database.nulls_first_order("(#{max_deployment_id_sql})", 'ASC')) end @@ -157,6 +157,16 @@ class Environment < ActiveRecord::Base project.monitoring_service.environment_metrics(self) if has_metrics? end + def has_additional_metrics? + project.prometheus_service.present? && available? && last_deployment.present? + end + + def additional_metrics + if has_additional_metrics? + project.prometheus_service.additional_environment_metrics(self) + end + end + # An environment name is not necessarily suitable for use in URLs, DNS # or other third-party contexts, so provide a slugified version. A slug has # the following properties: diff --git a/app/models/event.rb b/app/models/event.rb index fad6ff03927..29bc141c5cd 100644 --- a/app/models/event.rb +++ b/app/models/event.rb @@ -376,9 +376,9 @@ class Event < ActiveRecord::Base # At this point it's possible for multiple threads/processes to try to # update the project. Only one query should actually perform the update, # hence we add the extra WHERE clause for last_activity_at. - Project.unscoped.where(id: project_id). - where('last_activity_at <= ?', RESET_PROJECT_ACTIVITY_INTERVAL.ago). - update_all(last_activity_at: created_at) + Project.unscoped.where(id: project_id) + .where('last_activity_at <= ?', RESET_PROJECT_ACTIVITY_INTERVAL.ago) + .update_all(last_activity_at: created_at) end def authored_by?(user) @@ -392,7 +392,7 @@ class Event < ActiveRecord::Base end def set_last_repository_updated_at - Project.unscoped.where(id: project_id). - update_all(last_repository_updated_at: created_at) + Project.unscoped.where(id: project_id) + .update_all(last_repository_updated_at: created_at) end end diff --git a/app/models/group.rb b/app/models/group.rb index 5bb2cdc5eff..0b93460d473 100644 --- a/app/models/group.rb +++ b/app/models/group.rb @@ -206,8 +206,8 @@ class Group < Namespace end def refresh_members_authorized_projects - UserProjectAccessChangedService.new(user_ids_for_project_authorizations). - execute + UserProjectAccessChangedService.new(user_ids_for_project_authorizations) + .execute end def user_ids_for_project_authorizations @@ -225,10 +225,10 @@ class Group < Namespace def max_member_access_for_user(user) return GroupMember::OWNER if user.admin? - members_with_parents. - where(user_id: user). - reorder(access_level: :desc). - first&. + members_with_parents + .where(user_id: user) + .reorder(access_level: :desc) + .first&. access_level || GroupMember::NO_ACCESS end diff --git a/app/models/issue.rb b/app/models/issue.rb index f0f525aea21..3a9a6dba601 100644 --- a/app/models/issue.rb +++ b/app/models/issue.rb @@ -124,8 +124,8 @@ class Issue < ActiveRecord::Base end def self.order_by_position_and_priority - order_labels_priority. - reorder(Gitlab::Database.nulls_last_order('relative_position', 'ASC'), + order_labels_priority + .reorder(Gitlab::Database.nulls_last_order('relative_position', 'ASC'), Gitlab::Database.nulls_last_order('highest_priority', 'ASC'), "id DESC") end diff --git a/app/models/issue_collection.rb b/app/models/issue_collection.rb index f0b7d9914c8..49f011c113f 100644 --- a/app/models/issue_collection.rb +++ b/app/models/issue_collection.rb @@ -17,9 +17,9 @@ class IssueCollection # Given all the issue projects we get a list of projects that the current # user has at least reporter access to. - projects_with_reporter_access = user. - projects_with_reporter_access_limited_to(project_ids). - pluck(:id) + projects_with_reporter_access = user + .projects_with_reporter_access_limited_to(project_ids) + .pluck(:id) collection.select do |issue| if projects_with_reporter_access.include?(issue.project_id) diff --git a/app/models/label.rb b/app/models/label.rb index 955d6b4079b..ed6a8411da9 100644 --- a/app/models/label.rb +++ b/app/models/label.rb @@ -46,9 +46,9 @@ class Label < ActiveRecord::Base labels = Label.arel_table priorities = LabelPriority.arel_table - label_priorities = labels.join(priorities, Arel::Nodes::OuterJoin). - on(labels[:id].eq(priorities[:label_id]).and(priorities[:project_id].eq(project.id))). - join_sources + label_priorities = labels.join(priorities, Arel::Nodes::OuterJoin) + .on(labels[:id].eq(priorities[:label_id]).and(priorities[:project_id].eq(project.id))) + .join_sources joins(label_priorities).where(priorities[:priority].eq(nil)) end @@ -57,9 +57,9 @@ class Label < ActiveRecord::Base labels = Label.arel_table priorities = LabelPriority.arel_table - label_priorities = labels.join(priorities, Arel::Nodes::OuterJoin). - on(labels[:id].eq(priorities[:label_id])). - join_sources + label_priorities = labels.join(priorities, Arel::Nodes::OuterJoin) + .on(labels[:id].eq(priorities[:label_id])) + .join_sources joins(label_priorities) end diff --git a/app/models/member.rb b/app/models/member.rb index 788a32dd8e3..dc9247bc9a0 100644 --- a/app/models/member.rb +++ b/app/models/member.rb @@ -99,9 +99,9 @@ class Member < ActiveRecord::Base users = User.arel_table members = Member.arel_table - member_users = members.join(users, Arel::Nodes::OuterJoin). - on(members[:user_id].eq(users[:id])). - join_sources + member_users = members.join(users, Arel::Nodes::OuterJoin) + .on(members[:user_id].eq(users[:id])) + .join_sources joins(member_users) end diff --git a/app/models/merge_request.rb b/app/models/merge_request.rb index ea22ab53587..f581a25f093 100644 --- a/app/models/merge_request.rb +++ b/app/models/merge_request.rb @@ -577,8 +577,8 @@ class MergeRequest < ActiveRecord::Base messages = [title, description] messages.concat(commits.map(&:safe_message)) if merge_request_diff - Gitlab::ClosingIssueExtractor.new(project, current_user). - closed_by_message(messages.join("\n")) + Gitlab::ClosingIssueExtractor.new(project, current_user) + .closed_by_message(messages.join("\n")) else [] end diff --git a/app/models/merge_requests_closing_issues.rb b/app/models/merge_requests_closing_issues.rb index daafb137be4..7f7c114803d 100644 --- a/app/models/merge_requests_closing_issues.rb +++ b/app/models/merge_requests_closing_issues.rb @@ -7,9 +7,9 @@ class MergeRequestsClosingIssues < ActiveRecord::Base class << self def count_for_collection(ids) - group(:issue_id). - where(issue_id: ids). - pluck('issue_id', 'COUNT(*) as count') + group(:issue_id) + .where(issue_id: ids) + .pluck('issue_id', 'COUNT(*) as count') end end end diff --git a/app/models/milestone.rb b/app/models/milestone.rb index 0a6fc064aec..d2e2749f70d 100644 --- a/app/models/milestone.rb +++ b/app/models/milestone.rb @@ -98,11 +98,11 @@ class Milestone < ActiveRecord::Base if Gitlab::Database.postgresql? rel.order(:project_id, :due_date).select('DISTINCT ON (project_id) id') else - rel. - group(:project_id). - having('due_date = MIN(due_date)'). - pluck(:id, :project_id, :due_date). - map(&:first) + rel + .group(:project_id) + .having('due_date = MIN(due_date)') + .pluck(:id, :project_id, :due_date) + .map(&:first) end end diff --git a/app/models/namespace.rb b/app/models/namespace.rb index b48d73dcae7..583d4fb5244 100644 --- a/app/models/namespace.rb +++ b/app/models/namespace.rb @@ -181,16 +181,16 @@ class Namespace < ActiveRecord::Base def ancestors return self.class.none unless parent_id - Gitlab::GroupHierarchy. - new(self.class.where(id: parent_id)). - base_and_ancestors + Gitlab::GroupHierarchy + .new(self.class.where(id: parent_id)) + .base_and_ancestors end # Returns all the descendants of the current namespace. def descendants - Gitlab::GroupHierarchy. - new(self.class.where(parent_id: id)). - base_and_descendants + Gitlab::GroupHierarchy + .new(self.class.where(parent_id: id)) + .base_and_descendants end def user_ids_for_project_authorizations @@ -253,10 +253,10 @@ class Namespace < ActiveRecord::Base end def refresh_access_of_projects_invited_groups - Group. - joins(project_group_links: :project). - where(projects: { namespace_id: id }). - find_each(&:refresh_members_authorized_projects) + Group + .joins(project_group_links: :project) + .where(projects: { namespace_id: id }) + .find_each(&:refresh_members_authorized_projects) end def remove_exports! diff --git a/app/models/note.rb b/app/models/note.rb index 3221e653e30..ca6999427c0 100644 --- a/app/models/note.rb +++ b/app/models/note.rb @@ -137,9 +137,9 @@ class Note < ActiveRecord::Base end def count_for_collection(ids, type) - user.select('noteable_id', 'COUNT(*) as count'). - group(:noteable_id). - where(noteable_type: type, noteable_id: ids) + user.select('noteable_id', 'COUNT(*) as count') + .group(:noteable_id) + .where(noteable_type: type, noteable_id: ids) end end diff --git a/app/models/project.rb b/app/models/project.rb index 36ec4f398ca..2c2685875f8 100644 --- a/app/models/project.rb +++ b/app/models/project.rb @@ -244,8 +244,8 @@ class Project < ActiveRecord::Base scope :inside_path, ->(path) do # We need routes alias rs for JOIN so it does not conflict with # includes(:route) which we use in ProjectsFinder. - joins("INNER JOIN routes rs ON rs.source_id = projects.id AND rs.source_type = 'Project'"). - where('rs.path LIKE ?', "#{sanitize_sql_like(path)}/%") + joins("INNER JOIN routes rs ON rs.source_id = projects.id AND rs.source_type = 'Project'") + .where('rs.path LIKE ?', "#{sanitize_sql_like(path)}/%") end # "enabled" here means "not disabled". It includes private features! @@ -270,10 +270,10 @@ class Project < ActiveRecord::Base # logged in user. def self.public_or_visible_to_user(user = nil) if user - authorized = user. - project_authorizations. - select(1). - where('project_authorizations.project_id = projects.id') + authorized = user + .project_authorizations + .select(1) + .where('project_authorizations.project_id = projects.id') levels = Gitlab::VisibilityLevel.levels_for_user(user) @@ -298,11 +298,11 @@ class Project < ActiveRecord::Base elsif user column = ProjectFeature.quoted_access_level_column(feature) - authorized = user.project_authorizations.select(1). - where('project_authorizations.project_id = projects.id') + authorized = user.project_authorizations.select(1) + .where('project_authorizations.project_id = projects.id') - with_project_feature. - where("#{column} IN (?) OR (#{column} = ? AND EXISTS (?))", + with_project_feature + .where("#{column} IN (?) OR (#{column} = ? AND EXISTS (?))", visible, ProjectFeature::PRIVATE, authorized) @@ -369,14 +369,14 @@ class Project < ActiveRecord::Base # unscoping unnecessary conditions that'll be applied # when executing `where("projects.id IN (#{union.to_sql})")` projects = unscoped.select(:id).where( - ptable[:path].matches(pattern). - or(ptable[:name].matches(pattern)). - or(ptable[:description].matches(pattern)) + ptable[:path].matches(pattern) + .or(ptable[:name].matches(pattern)) + .or(ptable[:description].matches(pattern)) ) - namespaces = unscoped.select(:id). - joins(:namespace). - where(ntable[:name].matches(pattern)) + namespaces = unscoped.select(:id) + .joins(:namespace) + .where(ntable[:name].matches(pattern)) union = Gitlab::SQL::Union.new([projects, namespaces]) @@ -417,8 +417,8 @@ class Project < ActiveRecord::Base end def trending - joins('INNER JOIN trending_projects ON projects.id = trending_projects.project_id'). - reorder('trending_projects.id ASC') + joins('INNER JOIN trending_projects ON projects.id = trending_projects.project_id') + .reorder('trending_projects.id ASC') end def cached_count diff --git a/app/models/project_authorization.rb b/app/models/project_authorization.rb index def09675253..73302207e6b 100644 --- a/app/models/project_authorization.rb +++ b/app/models/project_authorization.rb @@ -7,9 +7,9 @@ class ProjectAuthorization < ActiveRecord::Base validates :user, uniqueness: { scope: [:project, :access_level] }, presence: true def self.select_from_union(union) - select(['project_id', 'MAX(access_level) AS access_level']). - from("(#{union.to_sql}) #{ProjectAuthorization.table_name}"). - group(:project_id) + select(['project_id', 'MAX(access_level) AS access_level']) + .from("(#{union.to_sql}) #{ProjectAuthorization.table_name}") + .group(:project_id) end def self.insert_authorizations(rows, per_batch = 1000) diff --git a/app/models/project_services/mattermost_slash_commands_service.rb b/app/models/project_services/mattermost_slash_commands_service.rb index c2f887e24a0..4d2037286a2 100644 --- a/app/models/project_services/mattermost_slash_commands_service.rb +++ b/app/models/project_services/mattermost_slash_commands_service.rb @@ -20,8 +20,8 @@ class MattermostSlashCommandsService < SlashCommandsService end def configure(user, params) - token = Mattermost::Command.new(user). - create(command(params)) + token = Mattermost::Command.new(user) + .create(command(params)) update(active: true, token: token) if token rescue Mattermost::Error => e diff --git a/app/models/project_services/prometheus_service.rb b/app/models/project_services/prometheus_service.rb index 110b8bc209b..c9df678f97e 100644 --- a/app/models/project_services/prometheus_service.rb +++ b/app/models/project_services/prometheus_service.rb @@ -28,17 +28,6 @@ class PrometheusService < MonitoringService 'Prometheus monitoring' end - def help - <<-MD.strip_heredoc - Retrieves the Kubernetes node metrics `container_cpu_usage_seconds_total` - and `container_memory_usage_bytes` from the configured Prometheus server. - - If you are not using [Auto-Deploy](https://docs.gitlab.com/ee/ci/autodeploy/index.html) - or have set up your own Prometheus server, an `environment` label is required on each metric to - [identify the Environment](https://docs.gitlab.com/ce/user/project/integrations/prometheus.html#metrics-and-labels). - MD - end - def self.to_param 'prometheus' end @@ -50,6 +39,7 @@ class PrometheusService < MonitoringService name: 'api_url', title: 'API URL', placeholder: 'Prometheus API Base URL, like http://prometheus.example.com/', + help: 'By default, Prometheus listens on ‘http://localhost:9090’. It’s not recommended to change the default address and port as this might affect or conflict with other services running on the GitLab server.', required: true } ] @@ -65,23 +55,34 @@ class PrometheusService < MonitoringService end def environment_metrics(environment) - with_reactive_cache(Gitlab::Prometheus::Queries::EnvironmentQuery.name, environment.id, &:itself) + with_reactive_cache(Gitlab::Prometheus::Queries::EnvironmentQuery.name, environment.id, &method(:rename_data_to_metrics)) end def deployment_metrics(deployment) - metrics = with_reactive_cache(Gitlab::Prometheus::Queries::DeploymentQuery.name, deployment.id, &:itself) + metrics = with_reactive_cache(Gitlab::Prometheus::Queries::DeploymentQuery.name, deployment.id, &method(:rename_data_to_metrics)) metrics&.merge(deployment_time: created_at.to_i) || {} end + def additional_environment_metrics(environment) + with_reactive_cache(Gitlab::Prometheus::Queries::AdditionalMetricsEnvironmentQuery.name, environment.id, &:itself) + end + + def additional_deployment_metrics(deployment) + with_reactive_cache(Gitlab::Prometheus::Queries::AdditionalMetricsDeploymentQuery.name, deployment.id, &:itself) + end + + def matched_metrics + with_reactive_cache(Gitlab::Prometheus::Queries::MatchedMetricsQuery.name, &:itself) + end + # Cache metrics for specific environment def calculate_reactive_cache(query_class_name, *args) return unless active? && project && !project.pending_delete? - metrics = Kernel.const_get(query_class_name).new(client).query(*args) - + data = Kernel.const_get(query_class_name).new(client).query(*args) { success: true, - metrics: metrics, + data: data, last_update: Time.now.utc } rescue Gitlab::PrometheusError => err @@ -91,4 +92,11 @@ class PrometheusService < MonitoringService def client @prometheus ||= Gitlab::PrometheusClient.new(api_url: api_url) end + + private + + def rename_data_to_metrics(metrics) + metrics[:metrics] = metrics.delete :data + metrics + end end diff --git a/app/models/project_team.rb b/app/models/project_team.rb index e1cc56551ba..674eacd28e8 100644 --- a/app/models/project_team.rb +++ b/app/models/project_team.rb @@ -172,10 +172,10 @@ class ProjectTeam return access if user_ids.empty? - users_access = project.project_authorizations. - where(user: user_ids). - group(:user_id). - maximum(:access_level) + users_access = project.project_authorizations + .where(user: user_ids) + .group(:user_id) + .maximum(:access_level) access.merge!(users_access) diff --git a/app/models/repository.rb b/app/models/repository.rb index 7460515fea8..c67475357d9 100644 --- a/app/models/repository.rb +++ b/app/models/repository.rb @@ -241,11 +241,11 @@ class Repository cache.fetch(:"diverging_commit_counts_#{branch.name}") do # Rugged seems to throw a `ReferenceError` when given branch_names rather # than SHA-1 hashes - number_commits_behind = raw_repository. - count_commits_between(branch.dereferenced_target.sha, root_ref_hash) + number_commits_behind = raw_repository + .count_commits_between(branch.dereferenced_target.sha, root_ref_hash) - number_commits_ahead = raw_repository. - count_commits_between(root_ref_hash, branch.dereferenced_target.sha) + number_commits_ahead = raw_repository + .count_commits_between(root_ref_hash, branch.dereferenced_target.sha) { behind: number_commits_behind, ahead: number_commits_ahead } end diff --git a/app/models/todo.rb b/app/models/todo.rb index 696d139af74..7af54b2beb2 100644 --- a/app/models/todo.rb +++ b/app/models/todo.rb @@ -70,9 +70,9 @@ class Todo < ActiveRecord::Base highest_priority = highest_label_priority(params).to_sql - select("#{table_name}.*, (#{highest_priority}) AS highest_priority"). - order(Gitlab::Database.nulls_last_order('highest_priority', 'ASC')). - order('todos.created_at') + select("#{table_name}.*, (#{highest_priority}) AS highest_priority") + .order(Gitlab::Database.nulls_last_order('highest_priority', 'ASC')) + .order('todos.created_at') end end diff --git a/app/models/user.rb b/app/models/user.rb index 782c162e1f3..954a30155f7 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -223,13 +223,13 @@ class User < ActiveRecord::Base scope :order_oldest_sign_in, -> { reorder(Gitlab::Database.nulls_last_order('last_sign_in_at', 'ASC')) } def self.with_two_factor - joins("LEFT OUTER JOIN u2f_registrations AS u2f ON u2f.user_id = users.id"). - where("u2f.id IS NOT NULL OR otp_required_for_login = ?", true).distinct(arel_table[:id]) + joins("LEFT OUTER JOIN u2f_registrations AS u2f ON u2f.user_id = users.id") + .where("u2f.id IS NOT NULL OR otp_required_for_login = ?", true).distinct(arel_table[:id]) end def self.without_two_factor - joins("LEFT OUTER JOIN u2f_registrations AS u2f ON u2f.user_id = users.id"). - where("u2f.id IS NULL AND otp_required_for_login = ?", false) + joins("LEFT OUTER JOIN u2f_registrations AS u2f ON u2f.user_id = users.id") + .where("u2f.id IS NULL AND otp_required_for_login = ?", false) end # @@ -300,9 +300,9 @@ class User < ActiveRecord::Base pattern = "%#{query}%" where( - table[:name].matches(pattern). - or(table[:email].matches(pattern)). - or(table[:username].matches(pattern)) + table[:name].matches(pattern) + .or(table[:email].matches(pattern)) + .or(table[:username].matches(pattern)) ) end @@ -317,10 +317,10 @@ class User < ActiveRecord::Base matched_by_emails_user_ids = email_table.project(email_table[:user_id]).where(email_table[:email].matches(pattern)) where( - table[:name].matches(pattern). - or(table[:email].matches(pattern)). - or(table[:username].matches(pattern)). - or(table[:id].in(matched_by_emails_user_ids)) + table[:name].matches(pattern) + .or(table[:email].matches(pattern)) + .or(table[:username].matches(pattern)) + .or(table[:id].in(matched_by_emails_user_ids)) ) end @@ -503,8 +503,8 @@ class User < ActiveRecord::Base # Returns the groups a user has access to def authorized_groups - union = Gitlab::SQL::Union. - new([groups.select(:id), authorized_projects.select(:namespace_id)]) + union = Gitlab::SQL::Union + .new([groups.select(:id), authorized_projects.select(:namespace_id)]) Group.where("namespaces.id IN (#{union.to_sql})") end @@ -533,8 +533,8 @@ class User < ActiveRecord::Base projects = super() if min_access_level - projects = projects. - where('project_authorizations.access_level >= ?', min_access_level) + projects = projects + .where('project_authorizations.access_level >= ?', min_access_level) end projects @@ -619,9 +619,9 @@ class User < ActiveRecord::Base next unless project if project.repository.branch_exists?(event.branch_name) - merge_requests = MergeRequest.where("created_at >= ?", event.created_at). - where(source_project_id: project.id, - source_branch: event.branch_name) + merge_requests = MergeRequest.where("created_at >= ?", event.created_at) + .where(source_project_id: project.id, + source_branch: event.branch_name) merge_requests.empty? end end @@ -832,8 +832,8 @@ class User < ActiveRecord::Base def toggle_star(project) UsersStarProject.transaction do - user_star_project = users_star_projects. - where(project: project, user: self).lock(true).first + user_star_project = users_star_projects + .where(project: project, user: self).lock(true).first if user_star_project user_star_project.destroy @@ -869,11 +869,11 @@ class User < ActiveRecord::Base # ms on a database with a similar size to GitLab.com's database. On the other # hand, using a subquery means we can get the exact same data in about 40 ms. def contributed_projects - events = Event.select(:project_id). - contributions.where(author_id: self). - where("created_at > ?", Time.now - 1.year). - uniq. - reorder(nil) + events = Event.select(:project_id) + .contributions.where(author_id: self) + .where("created_at > ?", Time.now - 1.year) + .uniq + .reorder(nil) Project.where(id: events) end @@ -884,9 +884,9 @@ class User < ActiveRecord::Base def ci_authorized_runners @ci_authorized_runners ||= begin - runner_ids = Ci::RunnerProject. - where("ci_runner_projects.project_id IN (#{ci_projects_union.to_sql})"). - select(:runner_id) + runner_ids = Ci::RunnerProject + .where("ci_runner_projects.project_id IN (#{ci_projects_union.to_sql})") + .select(:runner_id) Ci::Runner.specific.where(id: runner_ids) end end diff --git a/app/models/wiki_page.rb b/app/models/wiki_page.rb index c771c22f46a..224eb3cd4d0 100644 --- a/app/models/wiki_page.rb +++ b/app/models/wiki_page.rb @@ -22,16 +22,16 @@ class WikiPage def self.group_by_directory(pages) return [] if pages.blank? - pages.sort_by { |page| [page.directory, page.slug] }. - group_by(&:directory). - map do |dir, pages| + pages.sort_by { |page| [page.directory, page.slug] } + .group_by(&:directory) + .map do |dir, pages| if dir.present? WikiDirectory.new(dir, pages) else pages end - end. - flatten + end + .flatten end def self.unhyphenize(name) diff --git a/app/services/ci/create_pipeline_service.rb b/app/services/ci/create_pipeline_service.rb index 769749c9925..942145c4a8c 100644 --- a/app/services/ci/create_pipeline_service.rb +++ b/app/services/ci/create_pipeline_service.rb @@ -67,8 +67,8 @@ module Ci def update_merge_requests_head_pipeline return unless pipeline.latest? - MergeRequest.where(source_project: @pipeline.project, source_branch: @pipeline.ref). - update_all(head_pipeline_id: @pipeline.id) + MergeRequest.where(source_project: @pipeline.project, source_branch: @pipeline.ref) + .update_all(head_pipeline_id: @pipeline.id) end def skip_ci? diff --git a/app/services/ci/create_trigger_request_service.rb b/app/services/ci/create_trigger_request_service.rb index beb27a5a597..cf3d4aee2bc 100644 --- a/app/services/ci/create_trigger_request_service.rb +++ b/app/services/ci/create_trigger_request_service.rb @@ -3,8 +3,8 @@ module Ci def execute(project, trigger, ref, variables = nil) trigger_request = trigger.trigger_requests.create(variables: variables) - pipeline = Ci::CreatePipelineService.new(project, trigger.owner, ref: ref). - execute(:trigger, ignore_skip_ci: true, trigger_request: trigger_request) + pipeline = Ci::CreatePipelineService.new(project, trigger.owner, ref: ref) + .execute(:trigger, ignore_skip_ci: true, trigger_request: trigger_request) trigger_request if pipeline.persisted? end diff --git a/app/services/ci/register_job_service.rb b/app/services/ci/register_job_service.rb index d6a4280ce4c..af84d4c7427 100644 --- a/app/services/ci/register_job_service.rb +++ b/app/services/ci/register_job_service.rb @@ -54,15 +54,15 @@ module Ci def builds_for_shared_runner new_builds. # don't run projects which have not enabled shared runners and builds - joins(:project).where(projects: { shared_runners_enabled: true }). - joins('LEFT JOIN project_features ON ci_builds.project_id = project_features.project_id'). - where('project_features.builds_access_level IS NULL or project_features.builds_access_level > 0'). + joins(:project).where(projects: { shared_runners_enabled: true }) + .joins('LEFT JOIN project_features ON ci_builds.project_id = project_features.project_id') + .where('project_features.builds_access_level IS NULL or project_features.builds_access_level > 0'). # Implement fair scheduling # this returns builds that are ordered by number of running builds # we prefer projects that don't use shared runners at all - joins("LEFT JOIN (#{running_builds_for_shared_runners.to_sql}) AS project_builds ON ci_builds.project_id=project_builds.project_id"). - order('COALESCE(project_builds.running_builds, 0) ASC', 'ci_builds.id ASC') + joins("LEFT JOIN (#{running_builds_for_shared_runners.to_sql}) AS project_builds ON ci_builds.project_id=project_builds.project_id") + .order('COALESCE(project_builds.running_builds, 0) ASC', 'ci_builds.id ASC') end def builds_for_specific_runner @@ -70,8 +70,8 @@ module Ci end def running_builds_for_shared_runners - Ci::Build.running.where(runner: Ci::Runner.shared). - group(:project_id).select(:project_id, 'count(*) AS running_builds') + Ci::Build.running.where(runner: Ci::Runner.shared) + .group(:project_id).select(:project_id, 'count(*) AS running_builds') end def new_builds diff --git a/app/services/concerns/issues/resolve_discussions.rb b/app/services/concerns/issues/resolve_discussions.rb index 910a2a15e5d..7d45b4aa26a 100644 --- a/app/services/concerns/issues/resolve_discussions.rb +++ b/app/services/concerns/issues/resolve_discussions.rb @@ -10,9 +10,9 @@ module Issues def merge_request_to_resolve_discussions_of return @merge_request_to_resolve_discussions_of if defined?(@merge_request_to_resolve_discussions_of) - @merge_request_to_resolve_discussions_of = MergeRequestsFinder.new(current_user, project_id: project.id). - execute. - find_by(iid: merge_request_to_resolve_discussions_of_iid) + @merge_request_to_resolve_discussions_of = MergeRequestsFinder.new(current_user, project_id: project.id) + .execute + .find_by(iid: merge_request_to_resolve_discussions_of_iid) end def discussions_to_resolve diff --git a/app/services/create_deployment_service.rb b/app/services/create_deployment_service.rb index 46823418bb0..63b85c3de7d 100644 --- a/app/services/create_deployment_service.rb +++ b/app/services/create_deployment_service.rb @@ -2,7 +2,7 @@ class CreateDeploymentService attr_reader :job delegate :expanded_environment_name, - :environment_url, + :variables, :project, to: :job @@ -14,7 +14,8 @@ class CreateDeploymentService return unless executable? ActiveRecord::Base.transaction do - environment.external_url = environment_url if environment_url + environment.external_url = expanded_environment_url if + expanded_environment_url environment.fire_state_event(action) return unless environment.save @@ -49,6 +50,17 @@ class CreateDeploymentService @environment_options ||= job.options&.dig(:environment) || {} end + def expanded_environment_url + return @expanded_environment_url if defined?(@expanded_environment_url) + + @expanded_environment_url = + ExpandVariables.expand(environment_url, variables) if environment_url + end + + def environment_url + environment_options[:url] + end + def on_stop environment_options[:on_stop] end diff --git a/app/services/files/update_service.rb b/app/services/files/update_service.rb index f23a9f6d57c..bcca1386bed 100644 --- a/app/services/files/update_service.rb +++ b/app/services/files/update_service.rb @@ -28,8 +28,8 @@ module Files end def last_commit - @last_commit ||= Gitlab::Git::Commit. - last_for_path(@start_project.repository, @start_branch, @file_path) + @last_commit ||= Gitlab::Git::Commit + .last_for_path(@start_project.repository, @start_branch, @file_path) end def validate! diff --git a/app/services/git_push_service.rb b/app/services/git_push_service.rb index fb1d4aed58b..20d1fb29289 100644 --- a/app/services/git_push_service.rb +++ b/app/services/git_push_service.rb @@ -86,8 +86,8 @@ class GitPushService < BaseService push_commits.last(PROCESS_COMMIT_LIMIT).each do |commit| if commit.matches_cross_reference_regex? - ProcessCommitWorker. - perform_async(project.id, current_user.id, commit.to_hash, default) + ProcessCommitWorker + .perform_async(project.id, current_user.id, commit.to_hash, default) end end end diff --git a/app/services/issuable_base_service.rb b/app/services/issuable_base_service.rb index c8db4728aea..8dd0846f3bc 100644 --- a/app/services/issuable_base_service.rb +++ b/app/services/issuable_base_service.rb @@ -144,8 +144,8 @@ class IssuableBaseService < BaseService def merge_quick_actions_into_params!(issuable) description, command_params = - QuickActions::InterpretService.new(project, current_user). - execute(params[:description], issuable) + QuickActions::InterpretService.new(project, current_user) + .execute(params[:description], issuable) # Avoid a description already set on an issuable to be overwritten by a nil params[:description] = description if params.key?(:description) diff --git a/app/services/issues/create_service.rb b/app/services/issues/create_service.rb index 3cf4b82b9f2..718a7ac1f22 100644 --- a/app/services/issues/create_service.rb +++ b/app/services/issues/create_service.rb @@ -30,8 +30,8 @@ module Issues Discussions::ResolveService.new(project, current_user, merge_request: merge_request_to_resolve_discussions_of, - follow_up_issue: issue). - execute(discussions_to_resolve) + follow_up_issue: issue) + .execute(discussions_to_resolve) end private diff --git a/app/services/labels/promote_service.rb b/app/services/labels/promote_service.rb index 76d0ba67b07..43b539ded53 100644 --- a/app/services/labels/promote_service.rb +++ b/app/services/labels/promote_service.rb @@ -26,29 +26,29 @@ module Labels private def label_ids_for_merge(new_label) - LabelsFinder. - new(current_user, title: new_label.title, group_id: project.group.id). - execute(skip_authorization: true). - where.not(id: new_label). - select(:id) # Can't use pluck() to avoid object-creation because of the batching + LabelsFinder + .new(current_user, title: new_label.title, group_id: project.group.id) + .execute(skip_authorization: true) + .where.not(id: new_label) + .select(:id) # Can't use pluck() to avoid object-creation because of the batching end def update_issuables(new_label, label_ids) - LabelLink. - where(label: label_ids). - update_all(label_id: new_label) + LabelLink + .where(label: label_ids) + .update_all(label_id: new_label) end def update_issue_board_lists(new_label, label_ids) - List. - where(label: label_ids). - update_all(label_id: new_label) + List + .where(label: label_ids) + .update_all(label_id: new_label) end def update_priorities(new_label, label_ids) - LabelPriority. - where(label: label_ids). - update_all(label_id: new_label) + LabelPriority + .where(label: label_ids) + .update_all(label_id: new_label) end def update_project_labels(label_ids) diff --git a/app/services/labels/transfer_service.rb b/app/services/labels/transfer_service.rb index 514679ed29d..d2ece354efc 100644 --- a/app/services/labels/transfer_service.rb +++ b/app/services/labels/transfer_service.rb @@ -41,16 +41,16 @@ module Labels end def group_labels_applied_to_issues - Label.joins(:issues). - where( + Label.joins(:issues) + .where( issues: { project_id: project.id }, labels: { type: 'GroupLabel', group_id: old_group.id } ) end def group_labels_applied_to_merge_requests - Label.joins(:merge_requests). - where( + Label.joins(:merge_requests) + .where( merge_requests: { target_project_id: project.id }, labels: { type: 'GroupLabel', group_id: old_group.id } ) @@ -64,15 +64,15 @@ module Labels end def update_label_links(labels, old_label_id:, new_label_id:) - LabelLink.joins(:label). - merge(labels). - where(label_id: old_label_id). - update_all(label_id: new_label_id) + LabelLink.joins(:label) + .merge(labels) + .where(label_id: old_label_id) + .update_all(label_id: new_label_id) end def update_label_priorities(old_label_id:, new_label_id:) - LabelPriority.where(project_id: project.id, label_id: old_label_id). - update_all(label_id: new_label_id) + LabelPriority.where(project_id: project.id, label_id: old_label_id) + .update_all(label_id: new_label_id) end end end diff --git a/app/services/members/authorized_destroy_service.rb b/app/services/members/authorized_destroy_service.rb index f846d72498f..de3a252d6c6 100644 --- a/app/services/members/authorized_destroy_service.rb +++ b/app/services/members/authorized_destroy_service.rb @@ -26,30 +26,30 @@ module Members def unassign_issues_and_merge_requests(member) if member.is_a?(GroupMember) - issues = Issue.unscoped.select(1). - joins(:project). - where('issues.id = issue_assignees.issue_id AND projects.namespace_id = ?', member.source_id) + issues = Issue.unscoped.select(1) + .joins(:project) + .where('issues.id = issue_assignees.issue_id AND projects.namespace_id = ?', member.source_id) # DELETE FROM issue_assignees WHERE user_id = X AND EXISTS (...) - IssueAssignee.unscoped. - where('user_id = :user_id AND EXISTS (:sub)', user_id: member.user_id, sub: issues). - delete_all + IssueAssignee.unscoped + .where('user_id = :user_id AND EXISTS (:sub)', user_id: member.user_id, sub: issues) + .delete_all - MergeRequestsFinder.new(user, group_id: member.source_id, assignee_id: member.user_id). - execute. - update_all(assignee_id: nil) + MergeRequestsFinder.new(user, group_id: member.source_id, assignee_id: member.user_id) + .execute + .update_all(assignee_id: nil) else project = member.source # SELECT 1 FROM issues WHERE issues.id = issue_assignees.issue_id AND issues.project_id = X - issues = Issue.unscoped.select(1). - where('issues.id = issue_assignees.issue_id'). - where(project_id: project.id) + issues = Issue.unscoped.select(1) + .where('issues.id = issue_assignees.issue_id') + .where(project_id: project.id) # DELETE FROM issue_assignees WHERE user_id = X AND EXISTS (...) - IssueAssignee.unscoped. - where('user_id = :user_id AND EXISTS (:sub)', user_id: member.user_id, sub: issues). - delete_all + IssueAssignee.unscoped + .where('user_id = :user_id AND EXISTS (:sub)', user_id: member.user_id, sub: issues) + .delete_all project.merge_requests.opened.assigned_to(member.user).update_all(assignee_id: nil) end diff --git a/app/services/merge_requests/conflicts/resolve_service.rb b/app/services/merge_requests/conflicts/resolve_service.rb index c2c335b8461..6b6e231f4f9 100644 --- a/app/services/merge_requests/conflicts/resolve_service.rb +++ b/app/services/merge_requests/conflicts/resolve_service.rb @@ -27,10 +27,10 @@ module MergeRequests tree: merge_index.write_tree(rugged) } - conflicts_for_resolution. - project. - repository. - resolve_conflicts(current_user, merge_request.source_branch, commit_params) + conflicts_for_resolution + .project + .repository + .resolve_conflicts(current_user, merge_request.source_branch, commit_params) end end diff --git a/app/services/merge_requests/merge_service.rb b/app/services/merge_requests/merge_service.rb index fac3ac7a4c7..b247cb89e5e 100644 --- a/app/services/merge_requests/merge_service.rb +++ b/app/services/merge_requests/merge_service.rb @@ -61,8 +61,8 @@ module MergeRequests MergeRequests::PostMergeService.new(project, current_user).execute(merge_request) if params[:should_remove_source_branch].present? || @merge_request.force_remove_source_branch? - DeleteBranchService.new(@merge_request.source_project, branch_deletion_user). - execute(merge_request.source_branch) + DeleteBranchService.new(@merge_request.source_project, branch_deletion_user) + .execute(merge_request.source_branch) end end diff --git a/app/services/merge_requests/refresh_service.rb b/app/services/merge_requests/refresh_service.rb index 81d217929d5..e0e7c43f802 100644 --- a/app/services/merge_requests/refresh_service.rb +++ b/app/services/merge_requests/refresh_service.rb @@ -43,9 +43,9 @@ module MergeRequests end filter_merge_requests(merge_requests).each do |merge_request| - MergeRequests::PostMergeService. - new(merge_request.target_project, @current_user). - execute(merge_request) + MergeRequests::PostMergeService + .new(merge_request.target_project, @current_user) + .execute(merge_request) end end @@ -56,8 +56,8 @@ module MergeRequests # Refresh merge request diff if we push to source or target branch of merge request # Note: we should update merge requests from forks too def reload_merge_requests - merge_requests = @project.merge_requests.opened. - by_source_or_target_branch(@branch_name).to_a + merge_requests = @project.merge_requests.opened + .by_source_or_target_branch(@branch_name).to_a # Fork merge requests merge_requests += MergeRequest.opened diff --git a/app/services/notes/quick_actions_service.rb b/app/services/notes/quick_actions_service.rb index 8f81b54164a..a8d0cc15527 100644 --- a/app/services/notes/quick_actions_service.rb +++ b/app/services/notes/quick_actions_service.rb @@ -22,8 +22,8 @@ module Notes def extract_commands(note, options = {}) return [note.note, {}] unless supported?(note) - QuickActions::InterpretService.new(project, current_user, options). - execute(note.note, note.noteable) + QuickActions::InterpretService.new(project, current_user, options) + .execute(note.note, note.noteable) end def execute(command_params, note) diff --git a/app/services/tags/create_service.rb b/app/services/tags/create_service.rb index 1756da9e519..674792f6138 100644 --- a/app/services/tags/create_service.rb +++ b/app/services/tags/create_service.rb @@ -19,8 +19,8 @@ module Tags if new_tag if release_description - CreateReleaseService.new(@project, @current_user). - execute(tag_name, release_description) + CreateReleaseService.new(@project, @current_user) + .execute(tag_name, release_description) end success.merge(tag: new_tag) diff --git a/app/validators/dynamic_path_validator.rb b/app/validators/dynamic_path_validator.rb index 27ac60637fd..4688aabc2a8 100644 --- a/app/validators/dynamic_path_validator.rb +++ b/app/validators/dynamic_path_validator.rb @@ -26,7 +26,7 @@ class DynamicPathValidator < ActiveModel::EachValidator end def path_valid_for_record?(record, value) - full_path = record.respond_to?(:full_path) ? record.full_path : value + full_path = record.respond_to?(:build_full_path) ? record.build_full_path : value return true unless full_path diff --git a/app/views/groups/merge_requests.html.haml b/app/views/groups/merge_requests.html.haml index 8fe0bd149f3..45e39252e16 100644 --- a/app/views/groups/merge_requests.html.haml +++ b/app/views/groups/merge_requests.html.haml @@ -18,5 +18,4 @@ - if current_user To see all merge requests you should visit #{link_to 'dashboard', merge_requests_dashboard_path} page. - .prepend-top-default - = render 'shared/merge_requests' + = render 'shared/merge_requests' diff --git a/app/views/profiles/show.html.haml b/app/views/profiles/show.html.haml index 15672289c65..087ae778b0f 100644 --- a/app/views/profiles/show.html.haml +++ b/app/views/profiles/show.html.haml @@ -1,6 +1,6 @@ = render 'profiles/head' -= form_for @user, url: profile_path, method: :put, html: { multipart: true, class: "edit-user prepend-top-default" }, authenticity_token: true do |f| += bootstrap_form_for @user, url: profile_path, method: :put, html: { multipart: true, class: 'edit-user prepend-top-default' }, authenticity_token: true do |f| = form_errors(@user) .row @@ -11,11 +11,11 @@ - if @user.avatar? You can change your avatar here - if gravatar_enabled? - or remove the current avatar to revert to #{link_to Gitlab.config.gravatar.host, "http://" + Gitlab.config.gravatar.host} + or remove the current avatar to revert to #{link_to Gitlab.config.gravatar.host, 'http://' + Gitlab.config.gravatar.host} - else You can upload an avatar here - if gravatar_enabled? - or change it at #{link_to Gitlab.config.gravatar.host, "http://" + Gitlab.config.gravatar.host} + or change it at #{link_to Gitlab.config.gravatar.host, 'http://' + Gitlab.config.gravatar.host} .col-lg-9 .clearfix.avatar-image.append-bottom-default = link_to avatar_icon(@user, 400), target: '_blank', rel: 'noopener noreferrer' do @@ -26,12 +26,12 @@ %a.btn.js-choose-user-avatar-button Browse file... %span.avatar-file-name.prepend-left-default.js-avatar-filename No file chosen - = f.file_field :avatar, class: "js-user-avatar-input hidden", accept: "image/*" + = f.file_field_without_bootstrap :avatar, class: 'js-user-avatar-input hidden', accept: 'image/*' .help-block The maximum file size allowed is 200KB. - if @user.avatar? %hr - = link_to 'Remove avatar', profile_avatar_path, data: { confirm: "Avatar will be removed. Are you sure?" }, method: :delete, class: "btn btn-gray" + = link_to 'Remove avatar', profile_avatar_path, data: { confirm: 'Avatar will be removed. Are you sure?' }, method: :delete, class: 'btn btn-gray' %hr .row .col-lg-3.profile-settings-sidebar @@ -43,91 +43,50 @@ Some options are unavailable for LDAP accounts .col-lg-9 .row - .form-group.col-md-9 - = f.label :name, class: "label-light" - = f.text_field :name, class: "form-control", required: true - %span.help-block Enter your name, so people you know can recognize you. + = f.text_field :name, required: true, wrapper: { class: 'col-md-9' }, + help: 'Enter your name, so people you know can recognize you.' + = f.text_field :id, readonly: true, label: 'User ID', wrapper: { class: 'col-md-3' } - .form-group.col-md-3 - = f.label :id, class: 'label-light' do - User ID - = f.text_field :id, class: 'form-control', readonly: true - - - .form-group - = f.label :email, class: "label-light" - - if @user.external_email? - = f.text_field :email, class: "form-control", required: true, readonly: true - %span.help-block.light - Your email address was automatically set based on your #{email_provider_label} account. - - else - - if @user.temp_oauth_email? - = f.text_field :email, class: "form-control", required: true, value: nil - - else - = f.text_field :email, class: "form-control", required: true - - if @user.unconfirmed_email.present? - %span.help-block - Please click the link in the confirmation email before continuing. It was sent to - = succeed "." do - %strong= @user.unconfirmed_email - %p - = link_to "Resend confirmation e-mail", user_confirmation_path(user: { email: @user.unconfirmed_email }), method: :post - - - else - %span.help-block We also use email for avatar detection if no avatar is uploaded. - .form-group - = f.label :public_email, class: "label-light" - = f.select :public_email, options_for_select(@user.all_emails, selected: @user.public_email), { include_blank: 'Do not show on profile' }, class: "select2" - %span.help-block This email will be displayed on your public profile. - .form-group - = f.label :preferred_language, class: "label-light" - = f.select :preferred_language, Gitlab::I18n::AVAILABLE_LANGUAGES.map { |value, label| [label, value] }, - {}, class: "select2" - %span.help-block This feature is experimental and translations are not complete yet. - .form-group - = f.label :skype, class: "label-light" - = f.text_field :skype, class: "form-control" - .form-group - = f.label :linkedin, class: "label-light" - = f.text_field :linkedin, class: "form-control" - .form-group - = f.label :twitter, class: "label-light" - = f.text_field :twitter, class: "form-control" - .form-group - = f.label :website_url, 'Website', class: "label-light" - = f.text_field :website_url, class: "form-control" - .form-group - = f.label :location, 'Location', class: "label-light" - = f.text_field :location, class: "form-control" - .form-group - = f.label :organization, 'Organization', class: "label-light" - = f.text_field :organization, class: "form-control" - .form-group - = f.label :bio, class: "label-light" - = f.text_area :bio, rows: 4, class: "form-control", maxlength: 250 - %span.help-block Tell us about yourself in fewer than 250 characters. + - if @user.external_email? + = f.text_field :email, required: true, readonly: true, help: 'Your email address was automatically set based on your #{email_provider_label} account.' + - else + = f.text_field :email, required: true, value: (@user.email unless @user.temp_oauth_email?), + help: user_email_help_text(@user) + = f.select :public_email, options_for_select(@user.all_emails, selected: @user.public_email), + { help: 'This email will be displayed on your public profile.', include_blank: 'Do not show on profile' }, + control_class: 'select2' + = f.select :preferred_language, Gitlab::I18n::AVAILABLE_LANGUAGES.map { |value, label| [label, value] }, + { help: 'This feature is experimental and translations are not complete yet.' }, + control_class: 'select2' + = f.text_field :skype + = f.text_field :linkedin + = f.text_field :twitter + = f.text_field :website_url, label: 'Website' + = f.text_field :location + = f.text_field :organization + = f.text_area :bio, rows: 4, maxlength: 250, help: 'Tell us about yourself in fewer than 250 characters.' .prepend-top-default.append-bottom-default - = f.submit 'Update profile settings', class: "btn btn-success" - = link_to "Cancel", user_path(current_user), class: "btn btn-cancel" + = f.submit 'Update profile settings', class: 'btn btn-success' + = link_to 'Cancel', user_path(current_user), class: 'btn btn-cancel' .modal.modal-profile-crop .modal-dialog .modal-content .modal-header - %button.close{ :type => "button", :'data-dismiss' => "modal" } + %button.close{ type: 'button', 'data-dismiss': 'modal' } %span × %h4.modal-title Position and size your new avatar .modal-body .profile-crop-image-container - %img.modal-profile-crop-image{ alt: "Avatar cropper" } + %img.modal-profile-crop-image{ alt: 'Avatar cropper' } .crop-controls .btn-group - %button.btn.btn-primary{ data: { method: "zoom", option: "0.1" } } + %button.btn.btn-primary{ data: { method: 'zoom', option: '0.1' } } %span.fa.fa-search-plus - %button.btn.btn-primary{ data: { method: "zoom", option: "-0.1" } } + %button.btn.btn-primary{ data: { method: 'zoom', option: '-0.1' } } %span.fa.fa-search-minus .modal-footer - %button.btn.btn-primary.js-upload-user-avatar{ :type => "button" } + %button.btn.btn-primary.js-upload-user-avatar{ type: 'button' } Set new profile picture diff --git a/app/views/projects/_find_file_link.html.haml b/app/views/projects/_find_file_link.html.haml index c748ccf65e6..cb4d2bbacf5 100644 --- a/app/views/projects/_find_file_link.html.haml +++ b/app/views/projects/_find_file_link.html.haml @@ -1,3 +1,3 @@ -= link_to namespace_project_find_file_path(@project.namespace, @project, @ref), class: 'btn btn-grouped shortcuts-find-file', rel: 'nofollow' do += link_to namespace_project_find_file_path(@project.namespace, @project, @ref), class: 'btn shortcuts-find-file', rel: 'nofollow' do = icon('search') %span= _('Find file') diff --git a/app/views/projects/blob/_breadcrumb.html.haml b/app/views/projects/blob/_breadcrumb.html.haml index 0ad9f258e48..5840e9863f4 100644 --- a/app/views/projects/blob/_breadcrumb.html.haml +++ b/app/views/projects/blob/_breadcrumb.html.haml @@ -1,9 +1,26 @@ - blame = local_assigns.fetch(:blame, false) .nav-block + .tree-ref-container + .tree-ref-holder + = render 'shared/ref_switcher', destination: 'blob', path: @path + + %ul.breadcrumb.repo-breadcrumb + %li + = link_to namespace_project_tree_path(@project.namespace, @project, @ref) do + = @project.path + - path_breadcrumbs do |title, path| + - title = truncate(title, length: 40) + %li + - if path == @path + = link_to namespace_project_blob_path(@project.namespace, @project, tree_join(@ref, path)) do + %strong= title + - else + = link_to title, namespace_project_tree_path(@project.namespace, @project, tree_join(@ref, path)) + .tree-controls = render 'projects/find_file_link' - .btn-group.prepend-left-10{ role: "group" }< + .btn-group{ role: "group" }< -# only show normal/blame view links for text files - if blob.readable_text? - if blame @@ -18,19 +35,3 @@ = link_to 'Permalink', namespace_project_blob_path(@project.namespace, @project, tree_join(@commit.sha, @path)), class: 'btn js-data-file-blob-permalink-url' - - .tree-ref-holder - = render 'shared/ref_switcher', destination: 'blob', path: @path - - %ul.breadcrumb.repo-breadcrumb - %li - = link_to namespace_project_tree_path(@project.namespace, @project, @ref) do - = @project.path - - path_breadcrumbs do |title, path| - - title = truncate(title, length: 40) - %li - - if path == @path - = link_to namespace_project_blob_path(@project.namespace, @project, tree_join(@ref, path)) do - %strong= title - - else - = link_to title, namespace_project_tree_path(@project.namespace, @project, tree_join(@ref, path)) diff --git a/app/views/projects/commits/_commits.html.haml b/app/views/projects/commits/_commits.html.haml index d3380c917e4..93fd0789c11 100644 --- a/app/views/projects/commits/_commits.html.haml +++ b/app/views/projects/commits/_commits.html.haml @@ -3,8 +3,8 @@ - commits.chunk { |c| c.committed_date.in_time_zone.to_date }.each do |day, commits| %li.commit-header.js-commit-header{ data: { day: day } } - %span.day= day.strftime('%d %b, %Y') - %span.commits-count= pluralize(commits.count, 'commit') + %span.day= l(day, format: '%d %b, %Y') + %span.commits-count= n_("%d commit", "%d commits", commits.count) % commits.count %li.commits-row{ data: { day: day } } %ul.content-list.commit-list @@ -12,4 +12,4 @@ - if hidden > 0 %li.alert.alert-warning - #{number_with_delimiter(hidden)} additional commits have been omitted to prevent performance issues. + = n_('%d additional commit has been omitted to prevent performance issues.', '%d additional commits have been omitted to prevent performance issues.', hidden) % number_with_delimiter(hidden) diff --git a/app/views/projects/commits/show.html.haml b/app/views/projects/commits/show.html.haml index c1c2fb3d299..fabd825aec8 100644 --- a/app/views/projects/commits/show.html.haml +++ b/app/views/projects/commits/show.html.haml @@ -1,6 +1,6 @@ - @no_container = true -- page_title "Commits", @ref +- page_title _("Commits"), @ref = content_for :meta_tags do = auto_discovery_link_tag(:atom, namespace_project_commits_url(@project.namespace, @project, @ref, rss_url_options), title: "#{@project.name}:#{@ref} commits") @@ -18,16 +18,16 @@ .block-controls.hidden-xs.hidden-sm - if @merge_request.present? .control - = link_to "View open merge request", namespace_project_merge_request_path(@project.namespace, @project, @merge_request), class: 'btn' + = link_to _("View open merge request"), namespace_project_merge_request_path(@project.namespace, @project, @merge_request), class: 'btn' - elsif create_mr_button?(@repository.root_ref, @ref) .control - = link_to "Create merge request", create_mr_path(@repository.root_ref, @ref), class: 'btn btn-success' + = link_to _("Create merge request"), create_mr_path(@repository.root_ref, @ref), class: 'btn btn-success' .control = form_tag(namespace_project_commits_path(@project.namespace, @project, @id), method: :get, class: 'commits-search-form') do - = search_field_tag :search, params[:search], { placeholder: 'Filter by commit message', id: 'commits-search', class: 'form-control search-text-input input-short', spellcheck: false } + = search_field_tag :search, params[:search], { placeholder: _('Filter by commit message'), id: 'commits-search', class: 'form-control search-text-input input-short', spellcheck: false } .control - = link_to namespace_project_commits_path(@project.namespace, @project, @ref, rss_url_options), title: "Commits feed", class: 'btn' do + = link_to namespace_project_commits_path(@project.namespace, @project, @ref, rss_url_options), title: _("Commits feed"), class: 'btn' do = icon("rss") %div{ id: dom_id(@project) } diff --git a/app/views/projects/deploy_keys/_index.html.haml b/app/views/projects/deploy_keys/_index.html.haml index 6e038ffd9c0..cb98ce04430 100644 --- a/app/views/projects/deploy_keys/_index.html.haml +++ b/app/views/projects/deploy_keys/_index.html.haml @@ -4,7 +4,7 @@ %h4 Deploy Keys %button.btn.js-settings-toggle - = expanded ? 'Close' : 'Expand' + = expanded ? 'Collapse' : 'Expand' %p Deploy keys allow read-only or read-write (if enabled) access to your repository. Deploy keys can be used for CI, staging or production servers. You can create a deploy key or add an existing one. .settings-content.no-animate{ class: ('expanded' if expanded) } diff --git a/app/views/projects/deployments/_deployment.html.haml b/app/views/projects/deployments/_deployment.html.haml index 9b2ec9ae41c..26f3c297260 100644 --- a/app/views/projects/deployments/_deployment.html.haml +++ b/app/views/projects/deployments/_deployment.html.haml @@ -3,24 +3,25 @@ .table-mobile-header{ role: 'rowheader' } ID %strong.table-mobile-content ##{deployment.iid} - .table-section.section-40{ role: 'gridcell' } + .table-section.section-30{ role: 'gridcell' } .table-mobile-header{ role: 'rowheader' } Commit = render 'projects/deployments/commit', deployment: deployment - .table-section.section-15.build-column{ role: 'gridcell' } + .table-section.section-25.build-column{ role: 'gridcell' } .table-mobile-header{ role: 'rowheader' } Job - if deployment.deployable - = link_to [@project.namespace.becomes(Namespace), @project, deployment.deployable], class: 'build-link table-mobile-content' do - #{deployment.deployable.name} (##{deployment.deployable.id}) - - if deployment.user - by - = user_avatar(user: deployment.user, size: 20) + .table-mobile-content + = link_to [@project.namespace.becomes(Namespace), @project, deployment.deployable], class: 'build-link' do + #{deployment.deployable.name} (##{deployment.deployable.id}) + - if deployment.user + by + = user_avatar(user: deployment.user, size: 20) .table-section.section-15{ role: 'gridcell' } .table-mobile-header{ role: 'rowheader' } Created %span.table-mobile-content= time_ago_with_tooltip(deployment.created_at) .table-section.section-20.table-button-footer{ role: 'gridcell' } - .btn-group.table-action-button + .btn-group.table-action-buttons = render 'projects/deployments/actions', deployment: deployment = render 'projects/deployments/rollback', deployment: deployment diff --git a/app/views/projects/edit.html.haml b/app/views/projects/edit.html.haml index 296e37e20e6..78057facde7 100644 --- a/app/views/projects/edit.html.haml +++ b/app/views/projects/edit.html.haml @@ -1,10 +1,12 @@ +- @content_class = "limit-container-width" unless fluid_layout + = render "projects/settings/head" .project-edit-container .row.prepend-top-default - .col-lg-3.profile-settings-sidebar + .col-lg-4.profile-settings-sidebar %h4.prepend-top-0 Project settings - .col-lg-9 + .col-lg-8 .project-edit-errors = form_for [@project.namespace.becomes(Namespace), @project], remote: true, html: { multipart: true, class: "edit-project" }, authenticity_token: true do |f| %fieldset @@ -39,66 +41,66 @@ Sharing & Permissions .form_group.prepend-top-20.sharing-and-permissions .row.js-visibility-select - .col-md-9 + .col-md-8 .label-light = label_tag :project_visibility, 'Project Visibility', class: 'label-light', for: :project_visibility_level = link_to icon('question-circle'), help_page_path("public_access/public_access") %span.help-block - .col-md-3.visibility-select-container + .col-md-4.visibility-select-container = render('projects/visibility_select', model_method: :visibility_level, form: f, selected_level: @project.visibility_level) = f.fields_for :project_feature do |feature_fields| %fieldset.features .row - .col-md-9.project-feature + .col-md-8.project-feature = feature_fields.label :repository_access_level, "Repository", class: 'label-light' %span.help-block View and edit files in this project - .col-md-3.js-repo-access-level + .col-md-4.js-repo-access-level = project_feature_access_select(:repository_access_level) .row - .col-md-9.project-feature.nested + .col-md-8.project-feature.nested = feature_fields.label :merge_requests_access_level, "Merge requests", class: 'label-light' %span.help-block Submit changes to be merged upstream - .col-md-3 + .col-md-4 = project_feature_access_select(:merge_requests_access_level) .row - .col-md-9.project-feature.nested + .col-md-8.project-feature.nested = feature_fields.label :builds_access_level, "Pipelines", class: 'label-light' %span.help-block Build, test, and deploy your changes - .col-md-3 + .col-md-4 = project_feature_access_select(:builds_access_level) .row - .col-md-9.project-feature + .col-md-8.project-feature = feature_fields.label :snippets_access_level, "Snippets", class: 'label-light' %span.help-block Share code pastes with others out of Git repository - .col-md-3 + .col-md-4 = project_feature_access_select(:snippets_access_level) .row - .col-md-9.project-feature + .col-md-8.project-feature = feature_fields.label :issues_access_level, "Issues", class: 'label-light' %span.help-block Lightweight issue tracking system for this project - .col-md-3 + .col-md-4 = project_feature_access_select(:issues_access_level) .row - .col-md-9.project-feature + .col-md-8.project-feature = feature_fields.label :wiki_access_level, "Wiki", class: 'label-light' %span.help-block Pages for project documentation - .col-md-3 + .col-md-4 = project_feature_access_select(:wiki_access_level) .form-group = render 'shared/allow_request_access', form: f - if Gitlab.config.lfs.enabled && current_user.admin? .row.js-lfs-enabled - .col-md-9 + .col-md-8 = f.label :lfs_enabled, 'LFS', class: 'label-light' %span.help-block Git Large File Storage = link_to icon('question-circle'), help_page_path('workflow/lfs/manage_large_binaries_with_git_lfs') - .col-md-3 + .col-md-4 .select-wrapper = f.select :lfs_enabled, [%w(Enabled true), %w(Disabled false)], {}, selected: @project.lfs_enabled?, class: 'pull-right form-control project-repo-select select-control', data: { field: 'lfs_enabled' } = icon('chevron-down') @@ -138,19 +140,19 @@ .row.prepend-top-default %hr .row.prepend-top-default - .col-lg-3 + .col-lg-4 %h4.prepend-top-0 Housekeeping %p.append-bottom-0 %p Runs a number of housekeeping tasks within the current repository, such as compressing file revisions and removing unreachable objects. - .col-lg-9 + .col-lg-8 = link_to 'Housekeeping', housekeeping_namespace_project_path(@project.namespace, @project), method: :post, class: "btn btn-default" %hr .row.prepend-top-default - .col-lg-3 + .col-lg-4 %h4.prepend-top-0 Export project %p.append-bottom-0 @@ -159,7 +161,7 @@ %p Once the exported file is ready, you will receive a notification email with a download link. - .col-lg-9 + .col-lg-8 - if @project.export_project_path = link_to 'Download export', download_export_namespace_project_path(@project.namespace, @project), @@ -190,7 +192,7 @@ - if can? current_user, :archive_project, @project %hr .row.prepend-top-default - .col-lg-3 + .col-lg-4 %h4.warning-title.prepend-top-0 - if @project.archived? Unarchive project @@ -201,7 +203,7 @@ Unarchiving the project will mark its repository as active. The project can be committed to. - else Archiving the project will mark its repository as read-only. It is hidden from the dashboard and doesn't show up in searches. - .col-lg-9 + .col-lg-8 - if @project.archived? %p %strong Once active this project shows up in the search and on the dashboard. @@ -216,10 +218,10 @@ method: :post, class: "btn btn-warning" %hr .row.prepend-top-default - .col-lg-3 + .col-lg-4 %h4.prepend-top-0.warning-title Rename repository - .col-lg-9 + .col-lg-8 = render 'projects/errors' = form_for([@project.namespace.becomes(Namespace), @project]) do |f| .form-group.project_name_holder @@ -244,12 +246,12 @@ - if can?(current_user, :change_namespace, @project) %hr .row.prepend-top-default - .col-lg-3 + .col-lg-4 %h4.prepend-top-0.danger-title Transfer project to new group %p.append-bottom-0 Please select the group you want to transfer this project to in the dropdown to the right. - .col-lg-9 + .col-lg-8 = form_for([@project.namespace.becomes(Namespace), @project], url: transfer_namespace_project_path(@project.namespace, @project), method: :put, remote: true, html: { class: 'js-project-transfer-form' } ) do |f| .form-group = label_tag :new_namespace_id, nil, class: 'label-light' do @@ -265,7 +267,7 @@ - if @project.forked? && can?(current_user, :remove_fork_project, @project) %hr .row.prepend-top-default.append-bottom-default - .col-lg-3 + .col-lg-4 %h4.prepend-top-0.danger-title Remove fork relationship %p.append-bottom-0 @@ -273,7 +275,7 @@ This will remove the fork relationship to source project = succeed "." do = link_to @project.forked_from_project.name_with_namespace, project_path(@project.forked_from_project) - .col-lg-9 + .col-lg-8 = form_for([@project.namespace.becomes(Namespace), @project], url: remove_fork_namespace_project_path(@project.namespace, @project), method: :delete, remote: true, html: { class: 'transfer-project' }) do |f| %p %strong Once removed, the fork relationship cannot be restored and you will no longer be able to send merge requests to the source. @@ -281,12 +283,12 @@ - if can?(current_user, :remove_project, @project) %hr .row.prepend-top-default.append-bottom-default - .col-lg-3 + .col-lg-4 %h4.prepend-top-0.danger-title Remove project %p.append-bottom-0 Removing the project will delete its repository and all related resources including issues, merge requests etc. - .col-lg-9 + .col-lg-8 = form_tag(namespace_project_path(@project.namespace, @project), method: :delete) do %p %strong Removed projects cannot be restored! diff --git a/app/views/projects/hooks/_index.html.haml b/app/views/projects/hooks/_index.html.haml index 676b7c345bc..776681ea09a 100644 --- a/app/views/projects/hooks/_index.html.haml +++ b/app/views/projects/hooks/_index.html.haml @@ -1,12 +1,12 @@ .row.prepend-top-default - .col-lg-3 + .col-lg-4 %h4.prepend-top-0 = page_title %p #{link_to 'Webhooks', help_page_path('user/project/integrations/webhooks')} can be used for binding events when something is happening within the project. - .col-lg-9.append-bottom-default + .col-lg-8.append-bottom-default = form_for @hook, as: :hook, url: polymorphic_path([@project.namespace.becomes(Namespace), @project, :hooks]) do |f| = render partial: 'shared/web_hooks/form', locals: { form: f, hook: @hook } = f.submit 'Add webhook', class: 'btn btn-create' diff --git a/app/views/projects/pipelines_settings/_badge.html.haml b/app/views/projects/pipelines_settings/_badge.html.haml index 43bbd735059..3de518c8b9a 100644 --- a/app/views/projects/pipelines_settings/_badge.html.haml +++ b/app/views/projects/pipelines_settings/_badge.html.haml @@ -1,8 +1,8 @@ %div{ class: badge.title.gsub(' ', '-') } - .col-lg-3.profile-settings-sidebar + .col-lg-4.profile-settings-sidebar %h4.prepend-top-0 = badge.title.capitalize - .col-lg-9 + .col-lg-8 .prepend-top-10 .panel.panel-default .panel-heading diff --git a/app/views/projects/pipelines_settings/_show.html.haml b/app/views/projects/pipelines_settings/_show.html.haml index 3b17daeb6da..580129ca809 100644 --- a/app/views/projects/pipelines_settings/_show.html.haml +++ b/app/views/projects/pipelines_settings/_show.html.haml @@ -1,8 +1,8 @@ .row.prepend-top-default - .col-lg-3.profile-settings-sidebar + .col-lg-4.profile-settings-sidebar %h4.prepend-top-0 Pipelines - .col-lg-9 + .col-lg-8 = form_for @project, url: namespace_project_pipelines_settings_path(@project.namespace.becomes(Namespace), @project) do |f| %fieldset.builds-feature - unless @repository.gitlab_ci_yml diff --git a/app/views/projects/project_members/_index.html.haml b/app/views/projects/project_members/_index.html.haml index cfae371e169..fa99610c0be 100644 --- a/app/views/projects/project_members/_index.html.haml +++ b/app/views/projects/project_members/_index.html.haml @@ -1,5 +1,5 @@ .row.prepend-top-default - .col-lg-3.settings-sidebar + .col-lg-4.settings-sidebar %h4.prepend-top-0 Project members - if can?(current_user, :admin_project_member, @project) @@ -13,7 +13,7 @@ %i Masters or %i Owners - .col-lg-9 + .col-lg-8 .light - if can?(current_user, :admin_project_member, @project) %ul.nav-links.project-member-tabs{ role: 'tablist' } diff --git a/app/views/projects/protected_branches/_index.html.haml b/app/views/projects/protected_branches/_index.html.haml index 9af67649741..5d2422bdf54 100644 --- a/app/views/projects/protected_branches/_index.html.haml +++ b/app/views/projects/protected_branches/_index.html.haml @@ -7,7 +7,7 @@ %h4 Protected Branches %button.btn.js-settings-toggle - = expanded ? 'Close' : 'Expand' + = expanded ? 'Collapse' : 'Expand' %p Keep stable branches secure and force developers to use merge requests. .settings-content.no-animate{ class: ('expanded' if expanded) } diff --git a/app/views/projects/protected_tags/_index.html.haml b/app/views/projects/protected_tags/_index.html.haml index 976e1d7e93f..8250f692a69 100644 --- a/app/views/projects/protected_tags/_index.html.haml +++ b/app/views/projects/protected_tags/_index.html.haml @@ -7,7 +7,7 @@ %h4 Protected Tags %button.btn.js-settings-toggle - = expanded ? 'Close' : 'Expand' + = expanded ? 'Collapse' : 'Expand' %p Limit access to creating and updating tags. .settings-content.no-animate{ class: ('expanded' if expanded) } diff --git a/app/views/projects/services/_form.html.haml b/app/views/projects/services/_form.html.haml index 9167789a69d..6dffc026392 100644 --- a/app/views/projects/services/_form.html.haml +++ b/app/views/projects/services/_form.html.haml @@ -23,3 +23,7 @@ - disabled_title = @service.disabled_title = link_to 'Cancel', namespace_project_settings_integrations_path(@project.namespace, @project), class: 'btn btn-cancel' + +- if lookup_context.template_exists?('show', "projects/services/#{@service.to_param}", true) + %hr + = render "projects/services/#{@service.to_param}/show" diff --git a/app/views/projects/services/_index.html.haml b/app/views/projects/services/_index.html.haml index 86d5a0ec7b8..997b702da33 100644 --- a/app/views/projects/services/_index.html.haml +++ b/app/views/projects/services/_index.html.haml @@ -1,9 +1,9 @@ .row.prepend-top-default.append-bottom-default - .col-lg-3 + .col-lg-4 %h4.prepend-top-0 Project services %p Project services allow you to integrate GitLab with other applications - .col-lg-9 + .col-lg-8 %table.table %colgroup %col diff --git a/app/views/projects/services/prometheus/_show.html.haml b/app/views/projects/services/prometheus/_show.html.haml new file mode 100644 index 00000000000..c4ac384ca1a --- /dev/null +++ b/app/views/projects/services/prometheus/_show.html.haml @@ -0,0 +1,45 @@ +- content_for :page_specific_javascripts do + = webpack_bundle_tag('prometheus_metrics') + +.row.prepend-top-default.append-bottom-default.prometheus-metrics-monitoring.js-prometheus-metrics-monitoring + .col-lg-3 + %h4.prepend-top-0 + Metrics + %p + Metrics are automatically configured and monitored + based on a library of metrics from popular exporters. + = link_to 'More information', '#' + + .col-lg-9 + .panel.panel-default.js-panel-monitored-metrics{ data: { "active-metrics" => "#{namespace_project_prometheus_active_metrics_path(@project.namespace, @project, :json)}" } } + .panel-heading + %h3.panel-title + Monitored + %span.badge.js-monitored-count 0 + .panel-body + .loading-metrics.text-center.js-loading-metrics + = icon('spinner spin 3x', class: 'metrics-load-spinner') + %p Finding and configuring metrics... + .empty-metrics.text-center.hidden.js-empty-metrics + = custom_icon('icon_empty_metrics') + %p No metrics are being monitored. To start monitoring, deploy to an environment. + = link_to project_environments_path(@project), title: 'View environments', class: 'btn btn-success' do + View environments + %ul.list-unstyled.metrics-list.hidden.js-metrics-list + + .panel.panel-default.hidden.js-panel-missing-env-vars + .panel-heading + %h3.panel-title + = icon('caret-right lg fw', class: 'panel-toggle js-panel-toggle', 'aria-label' => 'Toggle panel') + Missing environment variable + %span.badge.js-env-var-count 0 + .panel-body.hidden + .flash-container + .flash-notice + .flash-text + To set up automatic monitoring, add the environment variable + %code + $CI_ENVIRONMENT_SLUG + to exporter’s queries. + = link_to 'More information', '#' + %ul.list-unstyled.metrics-list.js-missing-var-metrics-list diff --git a/app/views/projects/settings/ci_cd/show.html.haml b/app/views/projects/settings/ci_cd/show.html.haml index e8d2e91bd76..00ccc3ec41e 100644 --- a/app/views/projects/settings/ci_cd/show.html.haml +++ b/app/views/projects/settings/ci_cd/show.html.haml @@ -1,3 +1,4 @@ +- @content_class = "limit-container-width" unless fluid_layout - page_title "Pipelines" = render "projects/settings/head" diff --git a/app/views/projects/settings/integrations/show.html.haml b/app/views/projects/settings/integrations/show.html.haml index f69992566b5..1d1d0849289 100644 --- a/app/views/projects/settings/integrations/show.html.haml +++ b/app/views/projects/settings/integrations/show.html.haml @@ -1,3 +1,4 @@ +- @content_class = "limit-container-width" unless fluid_layout - page_title 'Integrations' = render "projects/settings/head" = render 'projects/hooks/index' diff --git a/app/views/projects/settings/members/show.html.haml b/app/views/projects/settings/members/show.html.haml index 343807b87cd..1e7695ac397 100644 --- a/app/views/projects/settings/members/show.html.haml +++ b/app/views/projects/settings/members/show.html.haml @@ -1,3 +1,5 @@ +- @content_class = "limit-container-width" unless fluid_layout + - page_title "Members" = render "projects/settings/head" diff --git a/app/views/projects/tree/_tree_header.html.haml b/app/views/projects/tree/_tree_header.html.haml index abde2a48587..00da76349da 100644 --- a/app/views/projects/tree/_tree_header.html.haml +++ b/app/views/projects/tree/_tree_header.html.haml @@ -1,79 +1,81 @@ -.tree-controls - = render 'projects/find_file_link' - - = link_to s_('Commits|History'), namespace_project_commits_path(@project.namespace, @project, @id), class: 'btn btn-grouped' - - = render 'projects/buttons/download', project: @project, ref: @ref +.tree-ref-container + .tree-ref-holder + = render 'shared/ref_switcher', destination: 'tree', path: @path -.tree-ref-holder - = render 'shared/ref_switcher', destination: 'tree', path: @path - -%ul.breadcrumb.repo-breadcrumb - %li - = link_to namespace_project_tree_path(@project.namespace, @project, @ref) do - = @project.path - - path_breadcrumbs do |title, path| + %ul.breadcrumb.repo-breadcrumb %li - = link_to truncate(title, length: 40), namespace_project_tree_path(@project.namespace, @project, tree_join(@ref, path)) + = link_to namespace_project_tree_path(@project.namespace, @project, @ref) do + = @project.path + - path_breadcrumbs do |title, path| + %li + = link_to truncate(title, length: 40), namespace_project_tree_path(@project.namespace, @project, tree_join(@ref, path)) - - if current_user - %li - - if !on_top_of_branch? - %span.btn.add-to-tree.disabled.has-tooltip{ title: _("You can only add files when you are on a branch"), data: { container: 'body' } } - = icon('plus') - - else - %span.dropdown - %a.dropdown-toggle.btn.add-to-tree{ href: '#', "data-toggle" => "dropdown" } + - if current_user + %li + - if !on_top_of_branch? + %span.btn.add-to-tree.disabled.has-tooltip{ title: _("You can only add files when you are on a branch"), data: { container: 'body' } } = icon('plus') - %ul.dropdown-menu - - if can_edit_tree? - %li - = link_to namespace_project_new_blob_path(@project.namespace, @project, @id) do - = icon('pencil fw') - #{ _('New file') } - %li - = link_to '#modal-upload-blob', { 'data-target' => '#modal-upload-blob', 'data-toggle' => 'modal' } do - = icon('file fw') - #{ _('Upload file') } - %li - = link_to '#modal-create-new-dir', { 'data-target' => '#modal-create-new-dir', 'data-toggle' => 'modal' } do - = icon('folder fw') - #{ _('New directory') } - - elsif can?(current_user, :fork_project, @project) - %li - - continue_params = { to: namespace_project_new_blob_path(@project.namespace, @project, @id), - notice: edit_in_new_fork_notice, - notice_now: edit_in_new_fork_notice_now } - - fork_path = namespace_project_forks_path(@project.namespace, @project, namespace_key: current_user.namespace.id, - continue: continue_params) - = link_to fork_path, method: :post do - = icon('pencil fw') - #{ _('New file') } + - else + %span.dropdown + %a.dropdown-toggle.btn.add-to-tree{ href: '#', "data-toggle" => "dropdown", "data-target" => ".add-to-tree-dropdown" } + = icon('plus') + .add-to-tree-dropdown + %ul.dropdown-menu + - if can_edit_tree? + %li + = link_to namespace_project_new_blob_path(@project.namespace, @project, @id) do + = icon('pencil fw') + #{ _('New file') } + %li + = link_to '#modal-upload-blob', { 'data-target' => '#modal-upload-blob', 'data-toggle' => 'modal' } do + = icon('file fw') + #{ _('Upload file') } + %li + = link_to '#modal-create-new-dir', { 'data-target' => '#modal-create-new-dir', 'data-toggle' => 'modal' } do + = icon('folder fw') + #{ _('New directory') } + - elsif can?(current_user, :fork_project, @project) + %li + - continue_params = { to: namespace_project_new_blob_path(@project.namespace, @project, @id), + notice: edit_in_new_fork_notice, + notice_now: edit_in_new_fork_notice_now } + - fork_path = namespace_project_forks_path(@project.namespace, @project, namespace_key: current_user.namespace.id, + continue: continue_params) + = link_to fork_path, method: :post do + = icon('pencil fw') + #{ _('New file') } + %li + - continue_params = { to: request.fullpath, + notice: edit_in_new_fork_notice + " Try to upload a file again.", + notice_now: edit_in_new_fork_notice_now } + - fork_path = namespace_project_forks_path(@project.namespace, @project, namespace_key: current_user.namespace.id, + continue: continue_params) + = link_to fork_path, method: :post do + = icon('file fw') + #{ _('Upload file') } + %li + - continue_params = { to: request.fullpath, + notice: edit_in_new_fork_notice + " Try to create a new directory again.", + notice_now: edit_in_new_fork_notice_now } + - fork_path = namespace_project_forks_path(@project.namespace, @project, namespace_key: current_user.namespace.id, + continue: continue_params) + = link_to fork_path, method: :post do + = icon('folder fw') + #{ _('New directory') } + + %li.divider %li - - continue_params = { to: request.fullpath, - notice: edit_in_new_fork_notice + " Try to upload a file again.", - notice_now: edit_in_new_fork_notice_now } - - fork_path = namespace_project_forks_path(@project.namespace, @project, namespace_key: current_user.namespace.id, - continue: continue_params) - = link_to fork_path, method: :post do - = icon('file fw') - #{ _('Upload file') } + = link_to new_namespace_project_branch_path(@project.namespace, @project) do + = icon('code-fork fw') + #{ _('New branch') } %li - - continue_params = { to: request.fullpath, - notice: edit_in_new_fork_notice + " Try to create a new directory again.", - notice_now: edit_in_new_fork_notice_now } - - fork_path = namespace_project_forks_path(@project.namespace, @project, namespace_key: current_user.namespace.id, - continue: continue_params) - = link_to fork_path, method: :post do - = icon('folder fw') - #{ _('New directory') } + = link_to new_namespace_project_tag_path(@project.namespace, @project) do + = icon('tags fw') + #{ _('New tag') } + +.tree-controls + = render 'projects/find_file_link' - %li.divider - %li - = link_to new_namespace_project_branch_path(@project.namespace, @project) do - = icon('code-fork fw') - #{ _('New branch') } - %li - = link_to new_namespace_project_tag_path(@project.namespace, @project) do - = icon('tags fw') - #{ _('New tag') } + = link_to s_('Commits|History'), namespace_project_commits_path(@project.namespace, @project, @id), class: 'btn' + + = render 'projects/buttons/download', project: @project, ref: @ref diff --git a/app/views/projects/triggers/_index.html.haml b/app/views/projects/triggers/_index.html.haml index cc74e50a5e3..e9a2f803edd 100644 --- a/app/views/projects/triggers/_index.html.haml +++ b/app/views/projects/triggers/_index.html.haml @@ -1,7 +1,7 @@ .row.prepend-top-default.append-bottom-default.triggers-container - .col-lg-3 + .col-lg-4 = render "projects/triggers/content" - .col-lg-9 + .col-lg-8 .panel.panel-default .panel-heading %h4.panel-title diff --git a/app/views/projects/variables/_index.html.haml b/app/views/projects/variables/_index.html.haml index 1b852a9c5b3..5e6786f6698 100644 --- a/app/views/projects/variables/_index.html.haml +++ b/app/views/projects/variables/_index.html.haml @@ -1,7 +1,7 @@ .row.prepend-top-default.append-bottom-default - .col-lg-3 + .col-lg-4 = render "projects/variables/content" - .col-lg-9 + .col-lg-8 %h5.prepend-top-0 Add a variable = render "projects/variables/form", btn_text: "Add new variable" diff --git a/app/views/shared/icons/_icon_empty_metrics.svg b/app/views/shared/icons/_icon_empty_metrics.svg new file mode 100644 index 00000000000..24fa353f3ba --- /dev/null +++ b/app/views/shared/icons/_icon_empty_metrics.svg @@ -0,0 +1,5 @@ +<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64"> + <g fill="#E5E5E5"> + <path d="M32 64C30.8954305 64 30 63.1045695 30 62 30 60.8954305 30.8954305 60 32 60 33.8894444 60 35.7536611 59.8131396 37.574335 59.4454933 38.6570511 59.2268618 39.7120017 59.9273408 39.9306331 61.0100569 40.1492646 62.0927729 39.4487856 63.1477235 38.3660695 63.366355 36.285133 63.7865558 34.1557023 64 32 64zM49.2301062 58.9696428C51.0302775 57.8173242 52.7114504 56.4871355 54.247711 55.0008916 55.0415758 54.232873 55.0625283 52.9667164 54.2945097 52.1728516 53.5264912 51.3789869 52.2603346 51.3580344 51.4664698 52.1260529 50.1212672 53.4274592 48.6493395 54.5920875 47.0736141 55.6007347 46.1433158 56.1962335 45.8719072 57.4331365 46.4674061 58.3634348 47.0629049 59.2937331 48.2998079 59.5651416 49.2301062 58.9696428zM61.0426034 45.4531856C61.9412068 43.5163476 62.6441937 41.4911051 63.1388045 39.4034279 63.393449 38.3286117 62.7285685 37.2508708 61.6537523 36.9962262 60.5789361 36.7415816 59.5011952 37.4064621 59.2465506 38.4812784 58.8141946 40.3061875 58.1997219 42.0764286 57.4141077 43.7697311 56.9492346 44.7717126 57.3846469 45.9608331 58.3866284 46.4257062 59.3886098 46.8905793 60.5777303 46.455167 61.0426034 45.4531856zM63.7270657 27.8034151C63.4476841 25.6718707 62.9558906 23.5863203 62.2616468 21.5714028 61.9018246 20.527084 60.7635435 19.9721898 59.7192246 20.3320119 58.6749058 20.6918341 58.1200116 21.8301152 58.4798337 22.874434 59.0867105 24.6357842 59.5166381 26.45898 59.760988 28.3232492 59.9045362 29.4184513 60.9087418 30.1899192 62.0039439 30.046371 63.099146 29.9028228 63.8706139 28.8986173 63.7270657 27.8034151zM56.4699838 11.3781121C55.0919588 9.74451505 53.5537382 8.25140603 51.8798083 6.92273835 51.0146495 6.23602588 49.7566092 6.38068523 49.0698968 7.24584403 48.3831843 8.11100284 48.5278436 9.36904308 49.3930024 10.0557555 50.8587525 11.2191822 52.2058153 12.5267396 53.4125204 13.9572433 54.1247279 14.8015385 55.3865225 14.9086168 56.2308177 14.1964094 57.0751129 13.484202 57.1821912 12.2224073 56.4699838 11.3781121zM41.481294 1.42849704C39.4470333.798260231 37.3474846.371987025 35.2067823.158824109 34.1076485.0493765922 33.1278998.851675811 33.0184523 1.95080957 32.9090048 3.04994333 33.711304 4.02969203 34.8104377 4.13913955 36.6833634 4.32563829 38.5191483 4.69835932 40.297557 5.24933028 41.3526509 5.57621023 42.4729622 4.98587613 42.7998421 3.93078217 43.1267221 2.8756882 42.536388 1.75537699 41.481294 1.42849704zM23.6558195 1.0993008C21.5852929 1.6571259 19.5822296 2.42161363 17.6728876 3.37914679 16.6855233 3.874309 16.2865147 5.07613416 16.7816769 6.06349841 17.2768392 7.05086266 18.4786643 7.44987125 19.4660286 6.95470905 21.1354949 6.11747332 22.8864813 5.44919307 24.6963667 4.96158787 25.7629079 4.67424869 26.3945759 3.57671185 26.1072367 2.51017072 25.8198975 1.44362959 24.7223606.811961615 23.6558195 1.0993008zM8.36290105 10.4291871C6.92120358 12.00815 5.63985273 13.7275139 4.53998784 15.5610549 3.97179016 16.5082746 4.27904822 17.7367631 5.22626792 18.3049608 6.17348763 18.8731585 7.40197615 18.5659004 7.97017383 17.6186807 8.9327668 16.0139803 10.054503 14.5087932 11.3168098 13.126301 12.0615972 12.3106016 12.0041117 11.0455771 11.1884123 10.3007897 10.372713 9.55600224 9.10768848 9.61348772 8.36290105 10.4291871zM.450120287 26.6230259C.151304663 28.3883054 0 30.1850053 0 32 0 32.2974081.00406268322 32.594367.0121750297 32.8908218.0423897377 33.994978.96197903 34.8655796 2.0661352 34.8353649 3.17029137 34.8051502 4.04089294 33.8855609 4.01067824 32.7814047 4.00356366 32.521412 4 32.2609289 4 32 4 30.4089462 4.13249902 28.8355581 4.39401589 27.2906242 4.57836807 26.2015475 3.84494393 25.1692294 2.75586724 24.9848772 1.66679054 24.800525.634472466 25.5339492.450120287 26.6230259zM2.45830096 44.3202494C3.28286321 46.2952494 4.30407075 48.1806071 5.50459135 49.9494734 6.124886 50.8634254 7.36863868 51.1014818 8.28259072 50.4811871 9.19654276 49.8608925 9.43459912 48.6171398 8.81430448 47.7031878 7.76386025 46.1554464 6.87058107 44.5062706 6.14951581 42.7791677 5.72395784 41.7598668 4.55266835 41.2785432 3.53336751 41.7041011 2.51406668 42.1296591 2.03274299 43.3009486 2.45830096 44.3202494zM13.73374 58.2776222C15.4883094 59.4994144 17.3614388 60.5433005 19.3262717 61.39161 20.3403619 61.8294398 21.5173756 61.3622885 21.9552054 60.3481983 22.3930351 59.3341082 21.9258838 58.1570945 20.9117937 57.7192647 19.1934726 56.9773858 17.5548741 56.0642026 16.0195384 54.9950736 15.1130877 54.3638678 13.8665707 54.5869979 13.2353649 55.4934487 12.6041591 56.3998995 12.8272892 57.6464164 13.73374 58.2776222zM30.6955071 63.9738646C29.5918263 63.9295649 28.7330282 62.9989428 28.7773279 61.895262 28.8216276 60.7915812 29.7522497 59.9327832 30.8559305 59.9770829 31.2344492 59.9922759 31.6140624 59.9999282 31.9946308 59.9999995 33.0992003 60.0002065 33.994463 60.8958047 33.994256 62.0003742 33.9940491 63.1049437 33.0984508 64.0002064 31.9938814 63.9999994 31.5600677 63.9999181 31.1272192 63.9911927 30.6955071 63.9738646zM30.1721098 44.2840559C30.7941711 46.023825 33.2407935 46.0619159 33.9167124 44.3423547L38.9452693 31.5495297 41.1315797 35.2685507C41.4908522 35.8796908 42.1468005 36.2549751 42.8557214 36.2549751L51.1106965 36.2549751C52.215266 36.2549751 53.1106965 35.3595446 53.1106965 34.2549751 53.1106965 33.1504056 52.215266 32.2549751 51.1106965 32.2549751L43.9999712 32.2549751 40.3112064 25.9802055C39.465988 24.5424477 37.3358287 24.7099356 36.7257006 26.2621229L32.1439734 37.9181973 26.2115967 21.3266406C25.5807315 19.562249 23.0875908 19.5563214 22.4483429 21.3176933L18.4775633 32.2587065 13 32.2587065C11.8954305 32.2587065 11 33.154137 11 34.2587065 11 35.363276 11.8954305 36.2587065 13 36.2587065L19.8793532 36.2587065C20.720826 36.2587065 21.4722973 35.732004 21.7593685 34.9410132L24.314328 27.9011249 30.1721098 44.2840559z"/> + </g> +</svg> diff --git a/app/views/shared/issuable/_nav.html.haml b/app/views/shared/issuable/_nav.html.haml index cf7ba52d840..3f03cc7a275 100644 --- a/app/views/shared/issuable/_nav.html.haml +++ b/app/views/shared/issuable/_nav.html.haml @@ -1,24 +1,25 @@ - type = local_assigns.fetch(:type, :issues) - page_context_word = type.to_s.humanize(capitalize: false) - issuables = @issues || @merge_requests -- closed_title = 'Filter by issues that are currently closed.' %ul.nav-links.issues-state-filters %li{ class: active_when(params[:state] == 'opened') }> - %button.btn.btn-link{ id: 'state-opened', title: "Filter by #{page_context_word} that are currently opened.", type: 'button', data: { state: 'opened' } } + = link_to page_filter_path(state: 'opened', label: true), id: 'state-opened', title: "Filter by #{page_context_word} that are currently opened.", data: { state: 'opened' } do #{issuables_state_counter_text(type, :opened)} - if type == :merge_requests %li{ class: active_when(params[:state] == 'merged') }> - %button.btn.btn-link{ id: 'state-merged', title: 'Filter by merge requests that are currently merged.', type: 'button', data: { state: 'merged' } } + = link_to page_filter_path(state: 'merged', label: true), id: 'state-merged', title: 'Filter by merge requests that are currently merged.', data: { state: 'merged' } do #{issuables_state_counter_text(type, :merged)} - - closed_title = 'Filter by merge requests that are currently closed and unmerged.' - - %li{ class: active_when(params[:state] == 'closed') }> - %button.btn.btn-link{ id: 'state-closed', title: closed_title, type: 'button', data: { state: 'closed' } } - #{issuables_state_counter_text(type, :closed)} + %li{ class: active_when(params[:state] == 'closed') }> + = link_to page_filter_path(state: 'closed', label: true), id: 'state-closed', title: 'Filter by merge requests that are currently closed and unmerged.', data: { state: 'closed' } do + #{issuables_state_counter_text(type, :closed)} + - else + %li{ class: active_when(params[:state] == 'closed') }> + = link_to page_filter_path(state: 'closed', label: true), id: 'state-closed', title: 'Filter by issues that are currently closed.', data: { state: 'closed' } do + #{issuables_state_counter_text(type, :closed)} %li{ class: active_when(params[:state] == 'all') }> - %button.btn.btn-link{ id: 'state-all', title: "Show all #{page_context_word}.", type: 'button', data: { state: 'all' } } + = link_to page_filter_path(state: 'all', label: true), id: 'state-all', title: "Show all #{page_context_word}.", data: { state: 'all' } do #{issuables_state_counter_text(type, :all)} diff --git a/app/views/shared/notes/_notes_with_form.html.haml b/app/views/shared/notes/_notes_with_form.html.haml index 0cca8d875d2..f0fcc414756 100644 --- a/app/views/shared/notes/_notes_with_form.html.haml +++ b/app/views/shared/notes/_notes_with_form.html.haml @@ -6,13 +6,14 @@ - if can_create_note? %ul.notes.notes-form.timeline %li.timeline-entry - .flash-container.timeline-content + .timeline-entry-inner + .flash-container.timeline-content - .timeline-icon.hidden-xs.hidden-sm - %a.author_link{ href: user_path(current_user) } - = image_tag avatar_icon(current_user), alt: current_user.to_reference, class: 'avatar s40' - .timeline-content.timeline-content-form - = render "shared/notes/form", view: diff_view, supports_autocomplete: autocomplete + .timeline-icon.hidden-xs.hidden-sm + %a.author_link{ href: user_path(current_user) } + = image_tag avatar_icon(current_user), alt: current_user.to_reference, class: 'avatar s40' + .timeline-content.timeline-content-form + = render "shared/notes/form", view: diff_view, supports_autocomplete: autocomplete - elsif !current_user .disabled-comment.text-center.prepend-top-default Please diff --git a/app/workers/merge_worker.rb b/app/workers/merge_worker.rb index 79efca4f2f9..48e2da338f6 100644 --- a/app/workers/merge_worker.rb +++ b/app/workers/merge_worker.rb @@ -7,7 +7,7 @@ class MergeWorker current_user = User.find(current_user_id) merge_request = MergeRequest.find(merge_request_id) - MergeRequests::MergeService.new(merge_request.target_project, current_user, params). - execute(merge_request) + MergeRequests::MergeService.new(merge_request.target_project, current_user, params) + .execute(merge_request) end end diff --git a/app/workers/process_commit_worker.rb b/app/workers/process_commit_worker.rb index fe6a49976e0..c0c03848a40 100644 --- a/app/workers/process_commit_worker.rb +++ b/app/workers/process_commit_worker.rb @@ -47,8 +47,8 @@ class ProcessCommitWorker # therefor we use IssueCollection here and skip the authorization check in # Issues::CloseService#execute. IssueCollection.new(issues).updatable_by_user(user).each do |issue| - Issues::CloseService.new(project, author). - close_issue(issue, commit: commit) + Issues::CloseService.new(project, author) + .close_issue(issue, commit: commit) end end @@ -57,8 +57,8 @@ class ProcessCommitWorker return if mentioned_issues.empty? - Issue::Metrics.where(issue_id: mentioned_issues.map(&:id), first_mentioned_in_commit_at: nil). - update_all(first_mentioned_in_commit_at: commit.committed_date) + Issue::Metrics.where(issue_id: mentioned_issues.map(&:id), first_mentioned_in_commit_at: nil) + .update_all(first_mentioned_in_commit_at: commit.committed_date) end def build_commit(project, hash) diff --git a/app/workers/project_cache_worker.rb b/app/workers/project_cache_worker.rb index 8ff9d07860f..505ff9e086e 100644 --- a/app/workers/project_cache_worker.rb +++ b/app/workers/project_cache_worker.rb @@ -32,8 +32,8 @@ class ProjectCacheWorker private def try_obtain_lease_for(project_id, section) - Gitlab::ExclusiveLease. - new("project_cache_worker:#{project_id}:#{section}", timeout: LEASE_TIMEOUT). - try_obtain + Gitlab::ExclusiveLease + .new("project_cache_worker:#{project_id}:#{section}", timeout: LEASE_TIMEOUT) + .try_obtain end end diff --git a/app/workers/propagate_service_template_worker.rb b/app/workers/propagate_service_template_worker.rb index 5ce0e0405d0..6b607451c7a 100644 --- a/app/workers/propagate_service_template_worker.rb +++ b/app/workers/propagate_service_template_worker.rb @@ -14,8 +14,8 @@ class PropagateServiceTemplateWorker private def try_obtain_lease_for(template_id) - Gitlab::ExclusiveLease. - new("propagate_service_template_worker:#{template_id}", timeout: LEASE_TIMEOUT). - try_obtain + Gitlab::ExclusiveLease + .new("propagate_service_template_worker:#{template_id}", timeout: LEASE_TIMEOUT) + .try_obtain end end diff --git a/app/workers/prune_old_events_worker.rb b/app/workers/prune_old_events_worker.rb index 392abb9c21b..2b43bb19ad1 100644 --- a/app/workers/prune_old_events_worker.rb +++ b/app/workers/prune_old_events_worker.rb @@ -10,9 +10,9 @@ class PruneOldEventsWorker '(id IN (SELECT id FROM (?) ids_to_remove))', Event.unscoped.where( 'created_at < ?', - (12.months + 1.day).ago). - select(:id). - limit(10_000)). - delete_all + (12.months + 1.day).ago) + .select(:id) + .limit(10_000)) + .delete_all end end diff --git a/app/workers/repository_check/batch_worker.rb b/app/workers/repository_check/batch_worker.rb index c3e7491ec4e..b94d83bd709 100644 --- a/app/workers/repository_check/batch_worker.rb +++ b/app/workers/repository_check/batch_worker.rb @@ -32,10 +32,10 @@ module RepositoryCheck # has to sit and wait for this query to finish. def project_ids limit = 10_000 - never_checked_projects = Project.where('last_repository_check_at IS NULL AND created_at < ?', 24.hours.ago). - limit(limit).pluck(:id) - old_check_projects = Project.where('last_repository_check_at < ?', 1.month.ago). - reorder('last_repository_check_at ASC').limit(limit).pluck(:id) + never_checked_projects = Project.where('last_repository_check_at IS NULL AND created_at < ?', 24.hours.ago) + .limit(limit).pluck(:id) + old_check_projects = Project.where('last_repository_check_at < ?', 1.month.ago) + .reorder('last_repository_check_at ASC').limit(limit).pluck(:id) never_checked_projects + old_check_projects end diff --git a/app/workers/update_user_activity_worker.rb b/app/workers/update_user_activity_worker.rb index b3c2f13aa33..31bbdb69edb 100644 --- a/app/workers/update_user_activity_worker.rb +++ b/app/workers/update_user_activity_worker.rb @@ -7,8 +7,8 @@ class UpdateUserActivityWorker ids = pairs.keys conditions = 'WHEN id = ? THEN ? ' * ids.length - User.where(id: ids). - update_all([ + User.where(id: ids) + .update_all([ "last_activity_on = CASE #{conditions} ELSE last_activity_on END", *pairs.to_a.flatten ]) |