Commit f69f6a23 authored by Robert Speicher's avatar Robert Speicher

Merge branch 'ce-to-ee-2018-03-13' into 'master'

CE upstream - 2018-03-13 15:27 UTC

See merge request gitlab-org/gitlab-ee!4948
parents ddbbd3bd 9177133b
<script> <script>
import $ from 'jquery'; import $ from 'jquery';
import { mapActions, mapGetters } from 'vuex'; import { mapActions, mapGetters, mapState } from 'vuex';
import _ from 'underscore'; import _ from 'underscore';
import Autosize from 'autosize'; import Autosize from 'autosize';
import { __, sprintf } from '~/locale'; import { __, sprintf } from '~/locale';
...@@ -53,6 +53,9 @@ ...@@ -53,6 +53,9 @@
'getNotesData', 'getNotesData',
'openState', 'openState',
]), ]),
...mapState([
'isToggleStateButtonLoading',
]),
noteableDisplayName() { noteableDisplayName() {
return this.noteableType.replace(/_/g, ' '); return this.noteableType.replace(/_/g, ' ');
}, },
...@@ -143,6 +146,7 @@ ...@@ -143,6 +146,7 @@
'closeIssue', 'closeIssue',
'reopenIssue', 'reopenIssue',
'toggleIssueLocalState', 'toggleIssueLocalState',
'toggleStateButtonLoading',
]), ]),
setIsSubmitButtonDisabled(note, isSubmitting) { setIsSubmitButtonDisabled(note, isSubmitting) {
if (!_.isEmpty(note) && !isSubmitting) { if (!_.isEmpty(note) && !isSubmitting) {
...@@ -170,13 +174,14 @@ ...@@ -170,13 +174,14 @@
if (this.noteType === constants.DISCUSSION) { if (this.noteType === constants.DISCUSSION) {
noteData.data.note.type = constants.DISCUSSION_NOTE; noteData.data.note.type = constants.DISCUSSION_NOTE;
} }
this.note = ''; // Empty textarea while being requested. Repopulate in catch this.note = ''; // Empty textarea while being requested. Repopulate in catch
this.resizeTextarea(); this.resizeTextarea();
this.stopPolling(); this.stopPolling();
this.saveNote(noteData) this.saveNote(noteData)
.then((res) => { .then((res) => {
this.isSubmitting = false; this.enableButton();
this.restartPolling(); this.restartPolling();
if (res.errors) { if (res.errors) {
...@@ -198,7 +203,7 @@ ...@@ -198,7 +203,7 @@
} }
}) })
.catch(() => { .catch(() => {
this.isSubmitting = false; this.enableButton();
this.discard(false); this.discard(false);
const msg = const msg =
`Your comment could not be submitted! `Your comment could not be submitted!
...@@ -220,6 +225,7 @@ Please check your network connection and try again.`; ...@@ -220,6 +225,7 @@ Please check your network connection and try again.`;
.then(() => this.enableButton()) .then(() => this.enableButton())
.catch(() => { .catch(() => {
this.enableButton(); this.enableButton();
this.toggleStateButtonLoading(false);
Flash( Flash(
sprintf( sprintf(
__('Something went wrong while closing the %{issuable}. Please try again later'), __('Something went wrong while closing the %{issuable}. Please try again later'),
...@@ -232,6 +238,7 @@ Please check your network connection and try again.`; ...@@ -232,6 +238,7 @@ Please check your network connection and try again.`;
.then(() => this.enableButton()) .then(() => this.enableButton())
.catch(() => { .catch(() => {
this.enableButton(); this.enableButton();
this.toggleStateButtonLoading(false);
Flash( Flash(
sprintf( sprintf(
__('Something went wrong while reopening the %{issuable}. Please try again later'), __('Something went wrong while reopening the %{issuable}. Please try again later'),
...@@ -419,13 +426,13 @@ append-right-10 comment-type-dropdown js-comment-type-dropdown droplab-dropdown" ...@@ -419,13 +426,13 @@ append-right-10 comment-type-dropdown js-comment-type-dropdown droplab-dropdown"
<loading-button <loading-button
v-if="canUpdateIssue" v-if="canUpdateIssue"
:loading="isSubmitting" :loading="isToggleStateButtonLoading"
@click="handleSave(true)" @click="handleSave(true)"
:container-class="[ :container-class="[
actionButtonClassNames, actionButtonClassNames,
'btn btn-comment btn-comment-and-close js-action-button' 'btn btn-comment btn-comment-and-close js-action-button'
]" ]"
:disabled="isSubmitting" :disabled="isToggleStateButtonLoading || isSubmitting"
:label="issueActionButtonTitle" :label="issueActionButtonTitle"
/> />
......
...@@ -71,21 +71,32 @@ export const toggleResolveNote = ({ commit }, { endpoint, isResolved, discussion ...@@ -71,21 +71,32 @@ export const toggleResolveNote = ({ commit }, { endpoint, isResolved, discussion
commit(mutationType, res); commit(mutationType, res);
}); });
export const closeIssue = ({ commit, dispatch, state }) => service export const closeIssue = ({ commit, dispatch, state }) => {
dispatch('toggleStateButtonLoading', true);
return service
.toggleIssueState(state.notesData.closePath) .toggleIssueState(state.notesData.closePath)
.then(res => res.json()) .then(res => res.json())
.then((data) => { .then((data) => {
commit(types.CLOSE_ISSUE); commit(types.CLOSE_ISSUE);
dispatch('emitStateChangedEvent', data); dispatch('emitStateChangedEvent', data);
dispatch('toggleStateButtonLoading', false);
}); });
};
export const reopenIssue = ({ commit, dispatch, state }) => service export const reopenIssue = ({ commit, dispatch, state }) => {
dispatch('toggleStateButtonLoading', true);
return service
.toggleIssueState(state.notesData.reopenPath) .toggleIssueState(state.notesData.reopenPath)
.then(res => res.json()) .then(res => res.json())
.then((data) => { .then((data) => {
commit(types.REOPEN_ISSUE); commit(types.REOPEN_ISSUE);
dispatch('emitStateChangedEvent', data); dispatch('emitStateChangedEvent', data);
dispatch('toggleStateButtonLoading', false);
}); });
};
export const toggleStateButtonLoading = ({ commit }, value) =>
commit(types.TOGGLE_STATE_BUTTON_LOADING, value);
export const emitStateChangedEvent = ({ commit, getters }, data) => { export const emitStateChangedEvent = ({ commit, getters }, data) => {
const event = new CustomEvent('issuable_vue_app:change', { detail: { const event = new CustomEvent('issuable_vue_app:change', { detail: {
......
...@@ -12,6 +12,9 @@ export default new Vuex.Store({ ...@@ -12,6 +12,9 @@ export default new Vuex.Store({
targetNoteHash: null, targetNoteHash: null,
lastFetchedAt: null, lastFetchedAt: null,
// View layer
isToggleStateButtonLoading: false,
// holds endpoints and permissions provided through haml // holds endpoints and permissions provided through haml
notesData: {}, notesData: {},
userData: {}, userData: {},
......
...@@ -17,3 +17,4 @@ export const UPDATE_DISCUSSION = 'UPDATE_DISCUSSION'; ...@@ -17,3 +17,4 @@ export const UPDATE_DISCUSSION = 'UPDATE_DISCUSSION';
// Issue // Issue
export const CLOSE_ISSUE = 'CLOSE_ISSUE'; export const CLOSE_ISSUE = 'CLOSE_ISSUE';
export const REOPEN_ISSUE = 'REOPEN_ISSUE'; export const REOPEN_ISSUE = 'REOPEN_ISSUE';
export const TOGGLE_STATE_BUTTON_LOADING = 'TOGGLE_STATE_BUTTON_LOADING';
...@@ -199,4 +199,8 @@ export default { ...@@ -199,4 +199,8 @@ export default {
[types.REOPEN_ISSUE](state) { [types.REOPEN_ISSUE](state) {
Object.assign(state.noteableData, { state: constants.REOPENED }); Object.assign(state.noteableData, { state: constants.REOPENED });
}, },
[types.TOGGLE_STATE_BUTTON_LOADING](state, value) {
Object.assign(state, { isToggleStateButtonLoading: value });
},
}; };
...@@ -14,8 +14,6 @@ export default class PerformanceBar { ...@@ -14,8 +14,6 @@ export default class PerformanceBar {
init(opts) { init(opts) {
const $container = $(opts.container); const $container = $(opts.container);
this.$sqlProfileLink = $container.find('.js-toggle-modal-peek-sql');
this.$sqlProfileModal = $container.find('#modal-peek-pg-queries');
this.$lineProfileLink = $container.find('.js-toggle-modal-peek-line-profile'); this.$lineProfileLink = $container.find('.js-toggle-modal-peek-line-profile');
this.$lineProfileModal = $('#modal-peek-line-profile'); this.$lineProfileModal = $('#modal-peek-line-profile');
this.initEventListeners(); this.initEventListeners();
...@@ -23,7 +21,6 @@ export default class PerformanceBar { ...@@ -23,7 +21,6 @@ export default class PerformanceBar {
} }
initEventListeners() { initEventListeners() {
this.$sqlProfileLink.on('click', () => this.handleSQLProfileLink());
this.$lineProfileLink.on('click', e => this.handleLineProfileLink(e)); this.$lineProfileLink.on('click', e => this.handleLineProfileLink(e));
$(document).on('click', '.js-lineprof-file', PerformanceBar.toggleLineProfileFile); $(document).on('click', '.js-lineprof-file', PerformanceBar.toggleLineProfileFile);
} }
...@@ -36,10 +33,6 @@ export default class PerformanceBar { ...@@ -36,10 +33,6 @@ export default class PerformanceBar {
} }
} }
handleSQLProfileLink() {
PerformanceBar.toggleModal(this.$sqlProfileModal);
}
handleLineProfileLink(e) { handleLineProfileLink(e) {
const lineProfilerParameter = getParameterValues('lineprofiler'); const lineProfilerParameter = getParameterValues('lineprofiler');
const lineProfilerParameterRegex = new RegExp(`lineprofiler=${lineProfilerParameter[0]}`); const lineProfilerParameterRegex = new RegExp(`lineprofiler=${lineProfilerParameter[0]}`);
......
...@@ -198,8 +198,6 @@ ...@@ -198,8 +198,6 @@
.commit-actions { .commit-actions {
@media (min-width: $screen-sm-min) { @media (min-width: $screen-sm-min) {
font-size: 0;
.fa-spinner { .fa-spinner {
font-size: 12px; font-size: 12px;
} }
...@@ -208,7 +206,7 @@ ...@@ -208,7 +206,7 @@
.ci-status-link { .ci-status-link {
display: inline-block; display: inline-block;
position: relative; position: relative;
top: 1px; top: 2px;
} }
.btn-clipboard, .btn-clipboard,
...@@ -230,7 +228,7 @@ ...@@ -230,7 +228,7 @@
.ci-status-icon { .ci-status-icon {
position: relative; position: relative;
top: 1px; top: 2px;
} }
} }
......
module ImportHelper module ImportHelper
include ::Gitlab::Utils::StrongMemoize
def has_ci_cd_only_params? def has_ci_cd_only_params?
false false
end end
...@@ -75,17 +77,18 @@ module ImportHelper ...@@ -75,17 +77,18 @@ module ImportHelper
private private
def github_project_url(full_path) def github_project_url(full_path)
"#{github_root_url}/#{full_path}" URI.join(github_root_url, full_path).to_s
end end
def github_root_url def github_root_url
return @github_url if defined?(@github_url) strong_memoize(:github_url) do
provider = Gitlab::Auth::OAuth::Provider.config_for('github')
provider = Gitlab.config.omniauth.providers.find { |p| p.name == 'github' } provider&.dig('url').presence || 'https://github.com'
@github_url = provider.fetch('url', 'https://github.com') if provider end
end end
def gitea_project_url(full_path) def gitea_project_url(full_path)
"#{@gitea_host_url.sub(%r{/+\z}, '')}/#{full_path}" URI.join(@gitea_host_url, full_path).to_s
end end
end end
...@@ -2,9 +2,4 @@ module JavascriptHelper ...@@ -2,9 +2,4 @@ module JavascriptHelper
def page_specific_javascript_tag(js) def page_specific_javascript_tag(js)
javascript_include_tag asset_path(js) javascript_include_tag asset_path(js)
end end
# deprecated; use webpack_bundle_tag directly instead
def page_specific_javascript_bundle_tag(bundle)
webpack_bundle_tag(bundle)
end
end end
- local_assigns.fetch(:view)
%span.bold
%span{ title: 'Invoke Time', data: { defer_to: "#{view.defer_key}-gc_time" } }...
\/
%span{ title: 'Invoke Count', data: { defer_to: "#{view.defer_key}-invokes" } }...
gc
- local_assigns.fetch(:view) - local_assigns.fetch(:view)
%strong %button.btn-blank.btn-link.bold{ type: 'button', data: { toggle: 'modal', target: '#modal-peek-gitaly-details' } }
%span{ data: { defer_to: "#{view.defer_key}-duration" } } ... %span{ data: { defer_to: "#{view.defer_key}-duration" } }...
\/ \/
%span{ data: { defer_to: "#{view.defer_key}-calls" } } ... %span{ data: { defer_to: "#{view.defer_key}-calls" } }...
Gitaly #modal-peek-gitaly-details.modal{ tabindex: -1, role: 'dialog' }
.modal-dialog.modal-full
.modal-content
.modal-header
%button.close{ type: 'button', data: { dismiss: 'modal' }, 'aria-label' => 'Close' }
%span{ 'aria-hidden' => 'true' }
&times;
%h4
Gitaly requests
.modal-body{ data: { defer_to: "#{view.defer_key}-details" } }...
gitaly
- local_assigns.fetch(:view)
%span.bold
%span{ data: { defer_to: "#{view.defer_key}-duration" } }...
\/
%span{ data: { defer_to: "#{view.defer_key}-calls" } }...
redis
- local_assigns.fetch(:view)
%span.bold
%span{ data: { defer_to: "#{view.defer_key}-duration" } }...
\/
%span{ data: { defer_to: "#{view.defer_key}-calls" } }...
sidekiq
%strong %button.btn-blank.btn-link.bold{ type: 'button', data: { toggle: 'modal', target: '#modal-peek-pg-queries' } }
%a.js-toggle-modal-peek-sql %span{ data: { defer_to: "#{view.defer_key}-duration" } }...
%span{ data: { defer_to: "#{view.defer_key}-duration" } }... \/
\/ %span{ data: { defer_to: "#{view.defer_key}-calls" } }...
%span{ data: { defer_to: "#{view.defer_key}-calls" } }...
#modal-peek-pg-queries.modal{ tabindex: -1 } #modal-peek-pg-queries.modal{ tabindex: -1 }
.modal-dialog.modal-full .modal-dialog.modal-full
.modal-content .modal-content
.modal-header .modal-header
%button.close.btn.btn-link.btn-sm{ type: 'button', data: { dismiss: 'modal' } } X %button.close{ type: 'button', data: { dismiss: 'modal' }, 'aria-label' => 'Close' }
%span{ 'aria-hidden' => 'true' }
&times;
%h4 %h4
SQL queries SQL queries
.modal-body{ data: { defer_to: "#{view.defer_key}-queries" } }... .modal-body{ data: { defer_to: "#{view.defer_key}-queries" } }...
...@@ -14,7 +14,7 @@ ...@@ -14,7 +14,7 @@
.checkbox .checkbox
= form.label :allow_maintainer_to_push do = form.label :allow_maintainer_to_push do
= form.check_box :allow_maintainer_to_push, disabled: !issuable.can_allow_maintainer_to_push?(current_user) = form.check_box :allow_maintainer_to_push, disabled: !issuable.can_allow_maintainer_to_push?(current_user)
= _('Allow edits from maintainers') = _('Allow edits from maintainers.')
= link_to 'About this feature', help_page_path('user/project/merge_requests/maintainer_access') = link_to 'About this feature', help_page_path('user/project/merge_requests/maintainer_access')
.help-block .help-block
= allow_maintainer_push_unavailable_reason(issuable) = allow_maintainer_push_unavailable_reason(issuable)
---
title: Fix generated URL when listing repoitories for import
merge_request: 17692
author:
type: fixed
---
title: lazy load diffs on merge request discussions
merge_request:
author:
type: performance
---
title: Update documentation to reflect current minimum required versions of node and
yarn
merge_request: 17706
author:
type: other
---
title: Add Gitaly call details to performance bar
merge_request:
author:
type: added
---
title: Fix broken loading state for close issue button
merge_request:
author:
type: fixed
...@@ -16,11 +16,11 @@ else ...@@ -16,11 +16,11 @@ else
end end
Peek.into PEEK_DB_VIEW Peek.into PEEK_DB_VIEW
Peek.into Peek::Views::Gitaly
Peek.into Peek::Views::Rblineprof
Peek.into Peek::Views::Redis Peek.into Peek::Views::Redis
Peek.into Peek::Views::Sidekiq Peek.into Peek::Views::Sidekiq
Peek.into Peek::Views::Rblineprof
Peek.into Peek::Views::GC Peek.into Peek::Views::GC
Peek.into Peek::Views::Gitaly
# rubocop:disable Naming/ClassAndModuleCamelCase # rubocop:disable Naming/ClassAndModuleCamelCase
class PEEK_DB_CLIENT class PEEK_DB_CLIENT
......
...@@ -11,10 +11,12 @@ It allows you to see (from left to right): ...@@ -11,10 +11,12 @@ It allows you to see (from left to right):
- the timing of the page (backend, frontend) - the timing of the page (backend, frontend)
- time taken and number of DB queries, click through for details of these queries - time taken and number of DB queries, click through for details of these queries
![SQL profiling using the Performance Bar](img/performance_bar_sql_queries.png) ![SQL profiling using the Performance Bar](img/performance_bar_sql_queries.png)
- time taken and number of calls to Redis - time taken and number of [Gitaly] calls, click through for details of these calls
- time taken and number of background jobs created by Sidekiq ![Gitaly profiling using the Performance Bar](img/performance_bar_gitaly_calls.png)
- profile of the code used to generate the page, line by line for either _all_, _app & lib_ , or _views_. In the profile view, the numbers in the left panel represent wall time, cpu time, and number of calls (based on [rblineprof](https://github.com/tmm1/rblineprof)). - profile of the code used to generate the page, line by line for either _all_, _app & lib_ , or _views_. In the profile view, the numbers in the left panel represent wall time, cpu time, and number of calls (based on [rblineprof](https://github.com/tmm1/rblineprof)).
![Line profiling using the Performance Bar](img/performance_bar_line_profiling.png) ![Line profiling using the Performance Bar](img/performance_bar_line_profiling.png)
- time taken and number of calls to Redis
- time taken and number of background jobs created by Sidekiq
- time taken and number of Ruby GC calls - time taken and number of Ruby GC calls
## Enable the Performance Bar via the Admin panel ## Enable the Performance Bar via the Admin panel
...@@ -39,3 +41,5 @@ You can toggle the Bar using the same shortcut. ...@@ -39,3 +41,5 @@ You can toggle the Bar using the same shortcut.
![GitLab Performance Bar Admin Settings](img/performance_bar_configuration_settings.png) ![GitLab Performance Bar Admin Settings](img/performance_bar_configuration_settings.png)
--- ---
[Gitaly]: ../../gitaly/index.md
...@@ -360,27 +360,15 @@ Instead place EE specs in the `ee/spec` folder. ...@@ -360,27 +360,15 @@ Instead place EE specs in the `ee/spec` folder.
## JavaScript code in `assets/javascripts/` ## JavaScript code in `assets/javascripts/`
To separate EE-specific JS-files we can also move the files into an `ee` folder. To separate EE-specific JS-files we should also move the files into an `ee` folder.
For example there can be an For example there can be an
`app/assets/javascripts/protected_branches/protected_branches_bundle.js` and an `app/assets/javascripts/protected_branches/protected_branches_bundle.js` and an
EE counterpart EE counterpart
`ee/app/assets/javascripts/protected_branches/protected_branches_bundle.js`. `ee/app/assets/javascripts/protected_branches/protected_branches_bundle.js`.
That way we can create a separate webpack bundle in `webpack.config.js`: See the frontend guide [performance section](./fe_guide/performance.md) for
information on managing page-specific javascript within EE.
```javascript
protected_branches: '~/protected_branches',
ee_protected_branches: 'ee/protected_branches/protected_branches_bundle.js',
```
With the separate bundle in place, we can decide which bundle to load inside the
view, using the `page_specific_javascript_bundle_tag` helper.
```haml
- content_for :page_specific_javascripts do
= page_specific_javascript_bundle_tag('protected_branches')
```
## SCSS code in `assets/stylesheets` ## SCSS code in `assets/stylesheets`
......
...@@ -14,8 +14,8 @@ support through [webpack][webpack]. ...@@ -14,8 +14,8 @@ support through [webpack][webpack].
We also utilize [webpack][webpack] to handle the bundling, minification, and We also utilize [webpack][webpack] to handle the bundling, minification, and
compression of our assets. compression of our assets.
Working with our frontend assets requires Node (v4.3 or greater) and Yarn Working with our frontend assets requires Node (v6.0 or greater) and Yarn
(v0.17 or greater). You can find information on how to install these on our (v1.2 or greater). You can find information on how to install these on our
[installation guide][install]. [installation guide][install].
[jQuery][jquery] is used throughout the application's JavaScript, with [jQuery][jquery] is used throughout the application's JavaScript, with
......
...@@ -23,7 +23,7 @@ controlled by the server. ...@@ -23,7 +23,7 @@ controlled by the server.
1. The backend code will most likely be using etags. You do not and should not check for status 1. The backend code will most likely be using etags. You do not and should not check for status
`304 Not Modified`. The browser will transform it for you. `304 Not Modified`. The browser will transform it for you.
### Lazy Loading ### Lazy Loading Images
To improve the time to first render we are using lazy loading for images. This works by setting To improve the time to first render we are using lazy loading for images. This works by setting
the actual image source on the `data-src` attribute. After the HTML is rendered and JavaScript is loaded, the actual image source on the `data-src` attribute. After the HTML is rendered and JavaScript is loaded,
...@@ -47,41 +47,103 @@ properties once, and handle the actual animation with transforms. ...@@ -47,41 +47,103 @@ properties once, and handle the actual animation with transforms.
## Reducing Asset Footprint ## Reducing Asset Footprint
### Page-specific JavaScript ### Universal code
Certain pages may require the use of a third party library, such as [d3][d3] for Code that is contained within `main.js` and `commons/index.js` are loaded and
the User Activity Calendar and [Chart.js][chartjs] for the Graphs pages. These run on _all_ pages. **DO NOT ADD** anything to these files unless it is truly
libraries increase the page size significantly, and impact load times due to needed _everywhere_. These bundles include ubiquitous libraries like `vue`,
bandwidth bottlenecks and the browser needing to parse more JavaScript. `axios`, and `jQuery`, as well as code for the main navigation and sidebar.
Where possible we should aim to remove modules from these bundles to reduce our
In cases where libraries are only used on a few specific pages, we use code footprint.
"page-specific JavaScript" to prevent the main `main.js` file from
becoming unnecessarily large. ### Page-specific JavaScript
Steps to split page-specific JavaScript from the main `main.js`:
1. Create a directory for the specific page(s), e.g. `graphs/`.
1. In that directory, create a `namespace_bundle.js` file, e.g. `graphs_bundle.js`.
1. Add the new "bundle" file to the list of entry files in `config/webpack.config.js`.
- For example: `graphs: './graphs/graphs_bundle.js',`.
1. Move code reliant on these libraries into the `graphs` directory.
1. In `graphs_bundle.js` add CommonJS `require('./path_to_some_component.js');` statements to load any other files in this directory. Make sure to use relative urls.
1. In the relevant views, add the scripts to the page with the following:
```haml
- content_for :page_specific_javascripts do
= webpack_bundle_tag 'lib_chart'
= webpack_bundle_tag 'graphs'
```
The above loads `chart.js` and `graphs_bundle.js` for this page only. `chart.js` Webpack has been configured to automatically generate entry point bundles based
is separated from the bundle file so it can be cached separately from the bundle on the file structure within `app/assets/javascripts/pages/*`. The directories
and reused for other pages that also rely on the library. For an example, see within the `pages` directory correspond to Rails controllers and actions. These
[this Haml file][page-specific-js-example]. auto-generated bundles will be automatically included on the corresponding
pages.
For example, if you were to visit [gitlab.com/gitlab-org/gitlab-ce/issues](https://gitlab.com/gitlab-org/gitlab-ce/issues),
you would be accessing the `app/controllers/projects/issues_controller.rb`
controller with the `index` action. If a corresponding file exists at
`pages/projects/issues/index/index.js`, it will be compiled into a webpack
bundle and included on the page.
> **Note:** Previously we had encouraged the use of
> `content_for :page_specific_javascripts` within haml files, along with
> manually generated webpack bundles. However under this new system you should
> not ever need to manually add an entry point to the `webpack.config.js` file.
> **Tip:**
> If you are unsure what controller and action corresponds to a given page, you
> can find this out by inspecting `document.body.dataset.page` within your
> browser's developer console while on any page within gitlab.
#### Important Considerations:
- **Keep Entry Points Lite:**
Page-specific javascript entry points should be as lite as possible. These
files are exempt from unit tests, and should be used primarily for
instantiation and dependency injection of classes and methods that live in
modules outside of the entry point script. Just import, read the DOM,
instantiate, and nothing else.
- **Entry Points May Be Asynchronous:**
_DO NOT ASSUME_ that the DOM has been fully loaded and available when an
entry point script is run. If you require that some code be run after the
DOM has loaded, you should attach an event handler to the `DOMContentLoaded`
event with:
```javascript
import initMyWidget from './my_widget';
document.addEventListener('DOMContentLoaded', () => {
initMyWidget();
});
```
- **Supporting Module Placement:**
- If a class or a module is _specific to a particular route_, try to locate
it close to the entry point it will be used. For instance, if
`my_widget.js` is only imported within `pages/widget/show/index.js`, you
should place the module at `pages/widget/show/my_widget.js` and import it
with a relative path (e.g. `import initMyWidget from './my_widget';`).
- If a class or module is _used by multiple routes_, place it within a
shared directory at the closest common parent directory for the entry
points that import it. For example, if `my_widget.js` is imported within
both `pages/widget/show/index.js` and `pages/widget/run/index.js`, then
place the module at `pages/widget/shared/my_widget.js` and import it with
a relative path if possible (e.g. `../shared/my_widget`).
- **Enterprise Edition Caveats:**
For GitLab Enterprise Edition, page-specific entry points will override their
Community Edition counterparts with the same name, so if
`ee/app/assets/javascripts/pages/foo/bar/index.js` exists, it will take
precedence over `app/assets/javascripts/pages/foo/bar/index.js`. If you want
to minimize duplicate code, you can import one entry point from the other.
This is not done automatically to allow for flexibility in overriding
functionality.
### Code Splitting ### Code Splitting
> *TODO* flesh out this section once webpack is ready for code-splitting For any code that does not need to be run immediately upon page load, (e.g.
modals, dropdowns, and other behaviors that can be lazy-loaded), you can split
your module into asynchronous chunks with dynamic import statements. These
imports return a Promise which will be resolved once the script has loaded:
```javascript
import(/* webpackChunkName: 'emoji' */ '~/emoji')
.then(/* do something */)
.catch(/* report error */)
```
Please try to use `webpackChunkName` when generating these dynamic imports as
it will provide a deterministic filename for the chunk which can then be cached
the browser across GitLab versions.
More information is available in [webpack's code splitting documentation](https://webpack.js.org/guides/code-splitting/#dynamic-imports).
### Minimizing page size ### Minimizing page size
...@@ -95,7 +157,8 @@ General tips: ...@@ -95,7 +157,8 @@ General tips:
- Prefer font formats with better compression, e.g. WOFF2 is better than WOFF, which is better than TTF. - Prefer font formats with better compression, e.g. WOFF2 is better than WOFF, which is better than TTF.
- Compress and minify assets wherever possible (For CSS/JS, Sprockets and webpack do this for us). - Compress and minify assets wherever possible (For CSS/JS, Sprockets and webpack do this for us).
- If some functionality can reasonably be achieved without adding extra libraries, avoid them. - If some functionality can reasonably be achieved without adding extra libraries, avoid them.
- Use page-specific JavaScript as described above to dynamically load libraries that are only needed on certain pages. - Use page-specific JavaScript as described above to load libraries that are only needed on certain pages.
- Use code-splitting dynamic imports wherever possible to lazy-load code that is not needed initially.
- [High Performance Animations][high-perf-animations] - [High Performance Animations][high-perf-animations]
------- -------
...@@ -112,8 +175,5 @@ General tips: ...@@ -112,8 +175,5 @@ General tips:
[pagespeed-insights]: https://developers.google.com/speed/pagespeed/insights/ [pagespeed-insights]: https://developers.google.com/speed/pagespeed/insights/
[google-devtools-profiling]: https://developers.google.com/web/tools/chrome-devtools/profile/?hl=en [google-devtools-profiling]: https://developers.google.com/web/tools/chrome-devtools/profile/?hl=en
[browser-diet]: https://browserdiet.com/ [browser-diet]: https://browserdiet.com/
[d3]: https://d3js.org/
[chartjs]: http://www.chartjs.org/
[page-specific-js-example]: https://gitlab.com/gitlab-org/gitlab-ce/blob/13bb9ed77f405c5f6ee4fdbc964ecf635c9a223f/app/views/projects/graphs/_head.html.haml#L6-8
[high-perf-animations]: https://www.html5rocks.com/en/tutorials/speed/high-performance-animations/ [high-perf-animations]: https://www.html5rocks.com/en/tutorials/speed/high-performance-animations/
[flip]: https://aerotwist.com/blog/flip-your-animations/ [flip]: https://aerotwist.com/blog/flip-your-animations/
# Security # Security
> TODO: Add content ## Avoid inline scripts and styles
Inline scripts and styles should be avoided in almost all cases. In an effort to protect users from [XSS vulnerabilities](https://en.wikipedia.org/wiki/Cross-site_scripting), we will be disabling inline scripts using Content Security Policy.
## Including external resources
External fonts, CSS, and JavaScript should never be used with the exception of Google Analytics and Piwik - and only when the instance has enabled it. Assets should always be hosted and served locally from the GitLab instance. Embedded resources via `iframes` should never be used except in certain circumstances such as with ReCaptcha, which cannot be used without an `iframe`.
## Resources for security testing
- [Mozilla's HTTP Observatory CLI](https://github.com/mozilla/http-observatory-cli)
- [Qualys SSL Labs Server Test](https://www.ssllabs.com/ssltest/analyze.html)
...@@ -162,13 +162,14 @@ page](https://golang.org/dl). ...@@ -162,13 +162,14 @@ page](https://golang.org/dl).
## 4. Node ## 4. Node
Since GitLab 8.17, GitLab requires the use of node >= v4.3.0 to compile Since GitLab 8.17, GitLab requires the use of Node to compile javascript
javascript assets, and yarn >= v0.17.0 to manage javascript dependencies. assets, and Yarn to manage javascript dependencies. The current minimum
In many distros the versions provided by the official package repositories requirements for these are node >= v6.0.0 and yarn >= v1.2.0. In many distros
are out of date, so we'll need to install through the following commands: the versions provided by the official package repositories are out of date, so
we'll need to install through the following commands:
# install node v7.x
curl --location https://deb.nodesource.com/setup_7.x | sudo bash - # install node v8.x
curl --location https://deb.nodesource.com/setup_8.x | sudo bash -
sudo apt-get install -y nodejs sudo apt-get install -y nodejs
curl --silent --show-error https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add - curl --silent --show-error https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
......
...@@ -56,8 +56,8 @@ sudo gem install bundler --no-ri --no-rdoc ...@@ -56,8 +56,8 @@ sudo gem install bundler --no-ri --no-rdoc
### 4. Update Node ### 4. Update Node
GitLab now runs [webpack](http://webpack.js.org) to compile frontend assets. GitLab utilizes [webpack](http://webpack.js.org) to compile frontend assets.
We require a minimum version of node v6.0.0. This requires a minimum version of node v6.0.0.
You can check which version you are running with `node -v`. If you are running You can check which version you are running with `node -v`. If you are running
a version older than `v6.0.0` you will need to update to a newer version. You a version older than `v6.0.0` you will need to update to a newer version. You
...@@ -66,8 +66,8 @@ from source at the nodejs.org website. ...@@ -66,8 +66,8 @@ from source at the nodejs.org website.
<https://nodejs.org/en/download/> <https://nodejs.org/en/download/>
Since 8.17, GitLab requires the use of yarn `>= v0.17.0` to manage GitLab also requires the use of yarn `>= v1.2.0` to manage JavaScript
JavaScript dependencies. dependencies.
```bash ```bash
curl --silent --show-error https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add - curl --silent --show-error https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
......
...@@ -3,7 +3,7 @@ require 'rails/generators' ...@@ -3,7 +3,7 @@ require 'rails/generators'
module Rails module Rails
class PostDeploymentMigrationGenerator < Rails::Generators::NamedBase class PostDeploymentMigrationGenerator < Rails::Generators::NamedBase
def create_migration_file def create_migration_file
timestamp = Time.now.strftime('%Y%m%d%H%I%S') timestamp = Time.now.strftime('%Y%m%d%H%M%S')
template "migration.rb", "db/post_migrate/#{timestamp}_#{file_name}.rb" template "migration.rb", "db/post_migrate/#{timestamp}_#{file_name}.rb"
end end
......
...@@ -4,7 +4,7 @@ module Gitlab ...@@ -4,7 +4,7 @@ module Gitlab
class Config class Config
class << self class << self
def options def options
Gitlab.config.omniauth.providers.find { |provider| provider.name == 'saml' } Gitlab::Auth::OAuth::Provider.config_for('saml')
end end
def groups def groups
......
...@@ -119,6 +119,9 @@ module Gitlab ...@@ -119,6 +119,9 @@ module Gitlab
# #
def self.call(storage, service, rpc, request, remote_storage: nil, timeout: nil) def self.call(storage, service, rpc, request, remote_storage: nil, timeout: nil)
start = Gitlab::Metrics::System.monotonic_time start = Gitlab::Metrics::System.monotonic_time
request_hash = request.is_a?(Google::Protobuf::MessageExts) ? request.to_h : {}
@current_call_id ||= SecureRandom.uuid
enforce_gitaly_request_limits(:call) enforce_gitaly_request_limits(:call)
kwargs = request_kwargs(storage, timeout, remote_storage: remote_storage) kwargs = request_kwargs(storage, timeout, remote_storage: remote_storage)
...@@ -135,6 +138,10 @@ module Gitlab ...@@ -135,6 +138,10 @@ module Gitlab
gitaly_controller_action_duration_seconds.observe( gitaly_controller_action_duration_seconds.observe(
current_transaction_labels.merge(gitaly_service: service.to_s, rpc: rpc.to_s), current_transaction_labels.merge(gitaly_service: service.to_s, rpc: rpc.to_s),
duration) duration)
add_call_details(id: @current_call_id, feature: service, duration: duration, request: request_hash)
@current_call_id = nil
end end
def self.handle_grpc_unavailable!(ex) def self.handle_grpc_unavailable!(ex)
...@@ -252,12 +259,16 @@ module Gitlab ...@@ -252,12 +259,16 @@ module Gitlab
feature_stack.unshift(feature) feature_stack.unshift(feature)
begin begin
start = Gitlab::Metrics::System.monotonic_time start = Gitlab::Metrics::System.monotonic_time
@current_call_id = SecureRandom.uuid
call_details = { id: @current_call_id }
yield is_enabled yield is_enabled
ensure ensure
total_time = Gitlab::Metrics::System.monotonic_time - start total_time = Gitlab::Metrics::System.monotonic_time - start
gitaly_migrate_call_duration_seconds.observe({ gitaly_enabled: is_enabled, feature: feature }, total_time) gitaly_migrate_call_duration_seconds.observe({ gitaly_enabled: is_enabled, feature: feature }, total_time)
feature_stack.shift feature_stack.shift
Thread.current[:gitaly_feature_stack] = nil if feature_stack.empty? Thread.current[:gitaly_feature_stack] = nil if feature_stack.empty?
add_call_details(call_details.merge(feature: feature, duration: total_time))
end end
end end
end end
...@@ -344,6 +355,22 @@ module Gitlab ...@@ -344,6 +355,22 @@ module Gitlab
end end
end end
def self.add_call_details(details)
id = details.delete(:id)
return unless id && RequestStore.active? && RequestStore.store[:peek_enabled]
RequestStore.store['gitaly_call_details'] ||= {}
RequestStore.store['gitaly_call_details'][id] ||= {}
RequestStore.store['gitaly_call_details'][id].merge!(details)
end
def self.list_call_details
return {} unless RequestStore.active? && RequestStore.store[:peek_enabled]
RequestStore.store['gitaly_call_details'] || {}
end
def self.expected_server_version def self.expected_server_version
path = Rails.root.join(SERVER_VERSION_FILE) path = Rails.root.join(SERVER_VERSION_FILE)
path.read.chomp path.read.chomp
......
...@@ -197,10 +197,7 @@ module Gitlab ...@@ -197,10 +197,7 @@ module Gitlab
end end
def github_omniauth_provider def github_omniauth_provider
@github_omniauth_provider ||= @github_omniauth_provider ||= Gitlab::Auth::OAuth::Provider.config_for('github').to_h
Gitlab.config.omniauth.providers
.find { |provider| provider.name == 'github' }
.to_h
end end
def rate_limit_counter def rate_limit_counter
......
...@@ -72,7 +72,7 @@ module Gitlab ...@@ -72,7 +72,7 @@ module Gitlab
end end
def config def config
Gitlab.config.omniauth.providers.find {|provider| provider.name == "gitlab"} Gitlab::Auth::OAuth::Provider.config_for('gitlab')
end end
def gitlab_options def gitlab_options
......
...@@ -83,7 +83,7 @@ module Gitlab ...@@ -83,7 +83,7 @@ module Gitlab
end end
def config def config
Gitlab.config.omniauth.providers.find { |provider| provider.name == "github" } Gitlab::Auth::OAuth::Provider.config_for('github')
end end
def github_options def github_options
......
...@@ -32,7 +32,7 @@ module GoogleApi ...@@ -32,7 +32,7 @@ module GoogleApi
private private
def config def config
Gitlab.config.omniauth.providers.find { |provider| provider.name == "google_oauth2" } Gitlab::Auth::OAuth::Provider.config_for('google_oauth2')
end end
def client def client
......
...@@ -10,11 +10,29 @@ module Peek ...@@ -10,11 +10,29 @@ module Peek
end end
def results def results
{ duration: formatted_duration, calls: calls } {
duration: formatted_duration,
calls: calls,
details: details
}
end end
private private
def details
::Gitlab::GitalyClient.list_call_details
.values
.sort { |a, b| b[:duration] <=> a[:duration] }
.map(&method(:format_call_details))
end
def format_call_details(call)
pretty_request = call[:request]&.reject { |k, v| v.blank? }.to_h.pretty_inspect
call.merge(duration: (call[:duration] * 1000).round(3),
request: pretty_request || {})
end
def formatted_duration def formatted_duration
ms = duration * 1000 ms = duration * 1000
if ms >= 1000 if ms >= 1000
......
...@@ -8,8 +8,8 @@ msgid "" ...@@ -8,8 +8,8 @@ msgid ""
msgstr "" msgstr ""
"Project-Id-Version: gitlab 1.0.0\n" "Project-Id-Version: gitlab 1.0.0\n"
"Report-Msgid-Bugs-To: \n" "Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2018-03-08 09:20+0100\n" "POT-Creation-Date: 2018-03-13 20:43+0100\n"
"PO-Revision-Date: 2018-03-08 09:20+0100\n" "PO-Revision-Date: 2018-03-13 20:43+0100\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n" "Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n" "Language: \n"
...@@ -118,6 +118,9 @@ msgstr "" ...@@ -118,6 +118,9 @@ msgstr ""
msgid "2FA enabled" msgid "2FA enabled"
msgstr "" msgstr ""
msgid "<strong>Removes</strong> source branch"
msgstr ""
msgid "A collection of graphs regarding Continuous Integration" msgid "A collection of graphs regarding Continuous Integration"
msgstr "" msgstr ""
...@@ -127,6 +130,9 @@ msgstr "" ...@@ -127,6 +130,9 @@ msgstr ""
msgid "A project is where you house your files (repository), plan your work (issues), and publish your documentation (wiki), %{among_other_things_link}." msgid "A project is where you house your files (repository), plan your work (issues), and publish your documentation (wiki), %{among_other_things_link}."
msgstr "" msgstr ""
msgid "A user with write access to the source branch selected this option"
msgstr ""
msgid "About auto deploy" msgid "About auto deploy"
msgstr "" msgstr ""
...@@ -241,7 +247,7 @@ msgstr "" ...@@ -241,7 +247,7 @@ msgstr ""
msgid "All features are enabled for blank projects, from templates, or when importing, but you can disable them afterward in the project settings." msgid "All features are enabled for blank projects, from templates, or when importing, but you can disable them afterward in the project settings."
msgstr "" msgstr ""
msgid "Allow edits from maintainers" msgid "Allow edits from maintainers."
msgstr "" msgstr ""
msgid "Allows you to add and manage Kubernetes clusters." msgid "Allows you to add and manage Kubernetes clusters."
...@@ -1396,6 +1402,9 @@ msgstr "" ...@@ -1396,6 +1402,9 @@ msgstr ""
msgid "Create file" msgid "Create file"
msgstr "" msgstr ""
msgid "Create group label"
msgstr ""
msgid "Create lists from labels. Issues with that label appear in that list." msgid "Create lists from labels. Issues with that label appear in that list."
msgstr "" msgstr ""
...@@ -1420,6 +1429,9 @@ msgstr "" ...@@ -1420,6 +1429,9 @@ msgstr ""
msgid "Create new..." msgid "Create new..."
msgstr "" msgstr ""
msgid "Create project label"
msgstr ""
msgid "CreateNewFork|Fork" msgid "CreateNewFork|Fork"
msgstr "" msgstr ""
...@@ -2387,9 +2399,15 @@ msgstr "" ...@@ -2387,9 +2399,15 @@ msgstr ""
msgid "Make everyone on your team more productive regardless of their location. GitLab Geo creates read-only mirrors of your GitLab instance so you can reduce the time it takes to clone and fetch large repos." msgid "Make everyone on your team more productive regardless of their location. GitLab Geo creates read-only mirrors of your GitLab instance so you can reduce the time it takes to clone and fetch large repos."
msgstr "" msgstr ""
msgid "Manage group labels"
msgstr ""
msgid "Manage labels" msgid "Manage labels"
msgstr "" msgstr ""
msgid "Manage project labels"
msgstr ""
msgid "Mar" msgid "Mar"
msgstr "" msgstr ""
...@@ -2905,9 +2923,15 @@ msgstr "" ...@@ -2905,9 +2923,15 @@ msgstr ""
msgid "Pipelines|Loading Pipelines" msgid "Pipelines|Loading Pipelines"
msgstr "" msgstr ""
msgid "Pipelines|Project cache successfully reset."
msgstr ""
msgid "Pipelines|Run Pipeline" msgid "Pipelines|Run Pipeline"
msgstr "" msgstr ""
msgid "Pipelines|Something went wrong while cleaning runners cache."
msgstr ""
msgid "Pipelines|There are currently no %{scope} pipelines." msgid "Pipelines|There are currently no %{scope} pipelines."
msgstr "" msgstr ""
...@@ -3040,9 +3064,6 @@ msgstr "" ...@@ -3040,9 +3064,6 @@ msgstr ""
msgid "Project avatar in repository: %{link}" msgid "Project avatar in repository: %{link}"
msgstr "" msgstr ""
msgid "Project cache successfully reset."
msgstr ""
msgid "Project details" msgid "Project details"
msgstr "" msgstr ""
...@@ -4178,7 +4199,7 @@ msgstr "" ...@@ -4178,7 +4199,7 @@ msgstr ""
msgid "Turn on Service Desk" msgid "Turn on Service Desk"
msgstr "" msgstr ""
msgid "Unable to reset project cache." msgid "Unable to load the diff."
msgstr "" msgstr ""
msgid "Unknown" msgid "Unknown"
...@@ -4247,12 +4268,18 @@ msgstr "" ...@@ -4247,12 +4268,18 @@ msgstr ""
msgid "View file @ " msgid "View file @ "
msgstr "" msgstr ""
msgid "View group labels"
msgstr ""
msgid "View labels" msgid "View labels"
msgstr "" msgstr ""
msgid "View open merge request" msgid "View open merge request"
msgstr "" msgstr ""
msgid "View project labels"
msgstr ""
msgid "View replaced file @ " msgid "View replaced file @ "
msgstr "" msgstr ""
......
...@@ -12,7 +12,7 @@ ...@@ -12,7 +12,7 @@
"webpack-prod": "NODE_ENV=production webpack --config config/webpack.config.js" "webpack-prod": "NODE_ENV=production webpack --config config/webpack.config.js"
}, },
"dependencies": { "dependencies": {
"@gitlab-org/gitlab-svgs": "^1.13.0", "@gitlab-org/gitlab-svgs": "^1.14.0",
"autosize": "^4.0.0", "autosize": "^4.0.0",
"axios": "^0.17.1", "axios": "^0.17.1",
"babel-core": "^6.26.0", "babel-core": "^6.26.0",
......
...@@ -27,25 +27,48 @@ describe ImportHelper do ...@@ -27,25 +27,48 @@ describe ImportHelper do
describe '#provider_project_link' do describe '#provider_project_link' do
context 'when provider is "github"' do context 'when provider is "github"' do
let(:github_server_url) { nil }
before do
setting = Settingslogic.new('name' => 'github')
setting['url'] = github_server_url if github_server_url
allow(Gitlab.config.omniauth).to receive(:providers).and_return([setting])
end
context 'when provider does not specify a custom URL' do context 'when provider does not specify a custom URL' do
it 'uses default GitHub URL' do it 'uses default GitHub URL' do
allow(Gitlab.config.omniauth).to receive(:providers)
.and_return([Settingslogic.new('name' => 'github')])
expect(helper.provider_project_link('github', 'octocat/Hello-World')) expect(helper.provider_project_link('github', 'octocat/Hello-World'))
.to include('href="https://github.com/octocat/Hello-World"') .to include('href="https://github.com/octocat/Hello-World"')
end end
end end
context 'when provider specify a custom URL' do context 'when provider specify a custom URL' do
let(:github_server_url) { 'https://github.company.com' }
it 'uses custom URL' do it 'uses custom URL' do
allow(Gitlab.config.omniauth).to receive(:providers) expect(helper.provider_project_link('github', 'octocat/Hello-World'))
.and_return([Settingslogic.new('name' => 'github', 'url' => 'https://github.company.com')]) .to include('href="https://github.company.com/octocat/Hello-World"')
end
end
context "when custom URL contains a '/' char at the end" do
let(:github_server_url) { 'https://github.company.com/' }
it "doesn't render double slash" do
expect(helper.provider_project_link('github', 'octocat/Hello-World')) expect(helper.provider_project_link('github', 'octocat/Hello-World'))
.to include('href="https://github.company.com/octocat/Hello-World"') .to include('href="https://github.company.com/octocat/Hello-World"')
end end
end end
context 'when provider is missing' do
it 'uses the default URL' do
allow(Gitlab.config.omniauth).to receive(:providers).and_return([])
expect(helper.provider_project_link('github', 'octocat/Hello-World'))
.to include('href="https://github.com/octocat/Hello-World"')
end
end
end end
context 'when provider is "gitea"' do context 'when provider is "gitea"' do
......
...@@ -200,6 +200,20 @@ describe('issue_comment_form component', () => { ...@@ -200,6 +200,20 @@ describe('issue_comment_form component', () => {
done(); done();
}); });
}); });
describe('when clicking close/reopen button', () => {
it('should disable button and show a loading spinner', (done) => {
const toggleStateButton = vm.$el.querySelector('.js-action-button');
toggleStateButton.click();
Vue.nextTick(() => {
expect(toggleStateButton.disabled).toEqual(true);
expect(toggleStateButton.querySelector('.js-loading-button-icon')).not.toBeNull();
done();
});
});
});
}); });
describe('issue is confidential', () => { describe('issue is confidential', () => {
......
...@@ -88,6 +88,7 @@ describe('Actions Notes Store', () => { ...@@ -88,6 +88,7 @@ describe('Actions Notes Store', () => {
store.dispatch('closeIssue', { notesData: { closeIssuePath: '' } }) store.dispatch('closeIssue', { notesData: { closeIssuePath: '' } })
.then(() => { .then(() => {
expect(store.state.noteableData.state).toEqual('closed'); expect(store.state.noteableData.state).toEqual('closed');
expect(store.state.isToggleStateButtonLoading).toEqual(false);
done(); done();
}) })
.catch(done.fail); .catch(done.fail);
...@@ -99,6 +100,7 @@ describe('Actions Notes Store', () => { ...@@ -99,6 +100,7 @@ describe('Actions Notes Store', () => {
store.dispatch('reopenIssue', { notesData: { reopenIssuePath: '' } }) store.dispatch('reopenIssue', { notesData: { reopenIssuePath: '' } })
.then(() => { .then(() => {
expect(store.state.noteableData.state).toEqual('reopened'); expect(store.state.noteableData.state).toEqual('reopened');
expect(store.state.isToggleStateButtonLoading).toEqual(false);
done(); done();
}) })
.catch(done.fail); .catch(done.fail);
...@@ -117,6 +119,20 @@ describe('Actions Notes Store', () => { ...@@ -117,6 +119,20 @@ describe('Actions Notes Store', () => {
}); });
}); });
describe('toggleStateButtonLoading', () => {
it('should set loading as true', (done) => {
testAction(actions.toggleStateButtonLoading, true, {}, [
{ type: 'TOGGLE_STATE_BUTTON_LOADING', payload: true },
], done);
});
it('should set loading as false', (done) => {
testAction(actions.toggleStateButtonLoading, false, {}, [
{ type: 'TOGGLE_STATE_BUTTON_LOADING', payload: false },
], done);
});
});
describe('toggleIssueLocalState', () => { describe('toggleIssueLocalState', () => {
it('sets issue state as closed', (done) => { it('sets issue state as closed', (done) => {
testAction(actions.toggleIssueLocalState, 'closed', {}, [ testAction(actions.toggleIssueLocalState, 'closed', {}, [
......
...@@ -228,4 +228,70 @@ describe('Notes Store mutations', () => { ...@@ -228,4 +228,70 @@ describe('Notes Store mutations', () => {
expect(state.notes[0].notes[0].note).toEqual('Foo'); expect(state.notes[0].notes[0].note).toEqual('Foo');
}); });
}); });
describe('CLOSE_ISSUE', () => {
it('should set issue as closed', () => {
const state = {
notes: [],
targetNoteHash: null,
lastFetchedAt: null,
isToggleStateButtonLoading: false,
notesData: {},
userData: {},
noteableData: {},
};
mutations.CLOSE_ISSUE(state);
expect(state.noteableData.state).toEqual('closed');
});
});
describe('REOPEN_ISSUE', () => {
it('should set issue as closed', () => {
const state = {
notes: [],
targetNoteHash: null,
lastFetchedAt: null,
isToggleStateButtonLoading: false,
notesData: {},
userData: {},
noteableData: {},
};
mutations.REOPEN_ISSUE(state);
expect(state.noteableData.state).toEqual('reopened');
});
});
describe('TOGGLE_STATE_BUTTON_LOADING', () => {
it('should set isToggleStateButtonLoading as true', () => {
const state = {
notes: [],
targetNoteHash: null,
lastFetchedAt: null,
isToggleStateButtonLoading: false,
notesData: {},
userData: {},
noteableData: {},
};
mutations.TOGGLE_STATE_BUTTON_LOADING(state, true);
expect(state.isToggleStateButtonLoading).toEqual(true);
});
it('should set isToggleStateButtonLoading as false', () => {
const state = {
notes: [],
targetNoteHash: null,
lastFetchedAt: null,
isToggleStateButtonLoading: true,
notesData: {},
userData: {},
noteableData: {},
};
mutations.TOGGLE_STATE_BUTTON_LOADING(state, false);
expect(state.isToggleStateButtonLoading).toEqual(false);
});
});
}); });
/* /*
* This is a modified version of https://github.com/peek/peek/blob/master/app/assets/javascripts/peek.js * this is a modified version of https://github.com/peek/peek/blob/master/app/assets/javascripts/peek.js
* *
* - Removed the dependency on jquery.tipsy * - Removed the dependency on jquery.tipsy
* - Removed the initializeTipsy and toggleBar functions * - Removed the initializeTipsy and toggleBar functions
* - Customized updatePerformanceBar to handle SQL queries report specificities * - Customized updatePerformanceBar to handle SQL query and Gitaly call lists
* - Changed /peek/results to /-/peek/results * - Changed /peek/results to /-/peek/results
* - Removed the keypress, pjax:end, page:change, and turbolinks:load handlers * - Removed the keypress, pjax:end, page:change, and turbolinks:load handlers
*/ */
(function($) { (function($) {
var fetchRequestResults, getRequestId, peekEnabled, updatePerformanceBar; var fetchRequestResults, getRequestId, peekEnabled, updatePerformanceBar, createTable, createTableRow;
getRequestId = function() { getRequestId = function() {
return $('#peek').data('requestId'); return $('#peek').data('requestId');
}; };
...@@ -16,39 +16,55 @@ ...@@ -16,39 +16,55 @@
return $('#peek').length; return $('#peek').length;
}; };
updatePerformanceBar = function(results) { updatePerformanceBar = function(results) {
var key, label, data, table, html, tr, duration_td, sql_td, strong;
Object.keys(results.data).forEach(function(key) { Object.keys(results.data).forEach(function(key) {
Object.keys(results.data[key]).forEach(function(label) { Object.keys(results.data[key]).forEach(function(label) {
data = results.data[key][label]; var data = results.data[key][label];
var table = createTable(key, label, data);
var target = $('[data-defer-to="' + key + '-' + label + '"]');
if (table) {
target.html(table);
} else {
target.text(data);
}
});
});
return $(document).trigger('peek:render', [getRequestId(), results]);
};
createTable = function(key, label, data) {
if (label !== 'queries' && label !== 'details') {
return;
}
if (label == 'queries') { var table = document.createElement('table');
table = document.createElement('table');
for (var i = 0; i < data.length; i += 1) { for (var i = 0; i < data.length; i += 1) {
tr = document.createElement('tr'); table.appendChild(createTableRow(data[i]));
duration_td = document.createElement('td'); }
sql_td = document.createElement('td');
strong = document.createElement('strong');
strong.append(data[i]['duration'] + 'ms'); table.className = 'table';
duration_td.appendChild(strong);
tr.appendChild(duration_td);
sql_td.appendChild(document.createTextNode(data[i]['sql'])); return table;
tr.appendChild(sql_td); };
createTableRow = function(row) {
var tr = document.createElement('tr');
var durationTd = document.createElement('td');
var strong = document.createElement('strong');
table.appendChild(tr); strong.append(row['duration'] + 'ms');
} durationTd.appendChild(strong);
tr.appendChild(durationTd);
table.className = 'table'; ['sql', 'feature', 'enabled', 'request'].forEach(function(key) {
$("[data-defer-to=" + key + "-" + label + "]").html(table); if (!row[key]) { return; }
} else {
$("[data-defer-to=" + key + "-" + label + "]").text(results.data[key][label]); var td = document.createElement('td');
}
}); td.appendChild(document.createTextNode(row[key]));
tr.appendChild(td);
}); });
return $(document).trigger('peek:render', [getRequestId(), results]);
return tr;
}; };
fetchRequestResults = function() { fetchRequestResults = function() {
return $.ajax('/-/peek/results', { return $.ajax('/-/peek/results', {
......
...@@ -54,9 +54,9 @@ ...@@ -54,9 +54,9 @@
lodash "^4.2.0" lodash "^4.2.0"
to-fast-properties "^2.0.0" to-fast-properties "^2.0.0"
"@gitlab-org/gitlab-svgs@^1.13.0": "@gitlab-org/gitlab-svgs@^1.14.0":
version "1.13.0" version "1.14.0"
resolved "https://registry.yarnpkg.com/@gitlab-org/gitlab-svgs/-/gitlab-svgs-1.13.0.tgz#9e856ef9fa7bbe49b2dce9789187a89e11311215" resolved "https://registry.yarnpkg.com/@gitlab-org/gitlab-svgs/-/gitlab-svgs-1.14.0.tgz#b4a5cca3106f33224c5486cf674ba3b70cee727e"
"@types/jquery@^2.0.40": "@types/jquery@^2.0.40":
version "2.0.48" version "2.0.48"
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment