Commit 8c3bdc85 authored by Filipa Lacerda's avatar Filipa Lacerda Committed by Alfredo Sumaran

Creates Frontend Style guide

parent 3574963b
......@@ -82,7 +82,7 @@ If a contributor is no longer actively working on a submitted merge request
we can decide that the merge request will be finished by one of our
[Merge request coaches][team] or close the merge request. We make this decision
based on how important the change is for our product vision. If a Merge request
coach is going to finish the merge request we assign the
coach is going to finish the merge request we assign the
~"coach will finish" label.
## Helping others
......@@ -479,8 +479,7 @@ merge request:
1. [Rails](
1. [Newlines styleguide][newlines-styleguide]
1. [Testing](doc/development/
1. [JavaScript (ES6)](
1. [JavaScript (ES5)](
1. [JavaScript styleguide][js-styleguide]
1. [SCSS styleguide][scss-styleguide]
1. [Shell commands](doc/development/ created by GitLab
contributors to enhance security
......@@ -549,7 +548,8 @@ available at [](http://contributor
[changelog]: doc/development/ "Generate a changelog entry"
[doc-styleguide]: doc/development/ "Documentation styleguide"
[scss-styleguide]: doc/development/ "SCSS styleguide"
[js-styleguide]: doc/development/fe_guide/ "JavaScript styleguide"
[scss-styleguide]: doc/development/fe_guide/ "SCSS styleguide"
[newlines-styleguide]: doc/development/ "Newlines styleguide"
[UX Guide for GitLab]:
[license-finder-doc]: doc/development/
title: Adds Frontend Styleguide to documentation
merge_request: 9961
......@@ -15,7 +15,7 @@
- [SQL Migration Style Guide]( for creating safe SQL migrations
- [Testing standards and style guidelines](
- [UX guide](ux_guide/ for building GitLab with existing CSS styles and elements
- [Frontend guidelines](
- [Frontend guidelines](fe_guide/
- [SQL guidelines]( for working with SQL queries
- [Sidekiq guidelines]( for working with Sidekiq workers
- [`Gemfile` guidelines](
# Accessibility
## Resources
[Chrome Accessibility Developer Tools][chrome-accessibility-developer-tools]
are useful for testing for potential accessibility problems in GitLab.
Accessibility best-practices and more in-depth information is available on
[the Audit Rules page][audit-rules] for the Chrome Accessibility Developer Tools.
# Architecture
When you are developing a new feature that requires architectural design, or if
you are changing the fundamental design of an existing feature, make sure it is
discussed with one of the Frontend Architecture Experts.
A Frontend Architect is an expert who makes high-level Frontend design decisions
and decides on technical standards, including coding standards and frameworks.
Architectural decisions should be accessible to everyone, so please document
them in the relevant Merge Request discussion or by updating our documentation
when appropriate.
You can find the Frontend Architecture experts on the [team page][team-page].
## Examples
You can find documentation about the desired architecture for a new feature
built with Vue.js [here][vue-section].
# Design Patterns
## Singletons
When exactly one object is needed for a given task, prefer to define it as a
`class` rather than as an object literal. Prefer also to explicitly restrict
instantiation, unless flexibility is important (e.g. for testing).
// bad
const MyThing = {
prop1: 'hello',
method1: () => {}
export default MyThing;
// good
class MyThing {
constructor() {
this.prop1 = 'hello';
method1() {}
export default new MyThing();
// best
export default class MyThing {
constructor() {
if (!this.prototype.singleton) {
this.prototype.singleton = this;
return this.prototype.singleton;
init() {
this.prop1 = 'hello';
method1() {}
## Manipulating the DOM in a JS Class
When writing a class that needs to manipulate the DOM guarantee a container option is provided.
This is useful when we need that class to be instantiated more than once in the same page.
class Foo {
constructor() {
new Foo();
class Foo {
constructor(opts) {
document.querySelector(`${opts.container} .bar`);
new Foo({ container: '.my-element' });
You can find an example of the above in this [class][container-class-example];
# Frontend Development Guidelines
This document describes various guidelines to ensure consistency and quality
across GitLab's frontend team.
## Overview
GitLab is built on top of [Ruby on Rails][rails] using [Haml][haml] with
[Hamlit][hamlit]. Be wary of [the limitations that come with using
Hamlit][hamlit-limits]. We also use [SCSS][scss] and plain JavaScript with
modern ECMAScript standards supported through [Babel][babel] and ES module
support through [webpack][webpack].
We also utilize [webpack][webpack] to handle the bundling, minification, and
compression of our assets.
Working with our frontend assets requires Node (v4.3 or greater) and Yarn
(v0.17 or greater). You can find information on how to install these on our
[installation guide][install].
[jQuery][jquery] is used throughout the application's JavaScript, with
[Vue.js][vue] for particularly advanced, dynamic elements.
### Browser Support
For our currently-supported browsers, see our [requirements][requirements].
## [Architecture](
How we go about making fundamental design decisions in GitLab's frontend team
or make changes to our frontend development guidelines.
## [Testing](
How we write frontend tests, run the GitLab test suite, and debug test related
## [Design Patterns](
Common JavaScript design patterns in GitLab's codebase.
## [Vue.js Best Practices](
Vue specific design patterns and practices.
## Style Guides
### [JavaScript Style Guide](
We use eslint to enforce our JavaScript style guides. Our guide is based on
the excellent [Airbnb][airbnb-js-style-guide] style guide with a few small
### [SCSS Style Guide](
Our SCSS conventions which are enforced through [scss-lint][scss-lint].
## [Performance](
Best practices for monitoring and maximizing frontend performance.
## [Security](
Frontend security practices.
## [Accessibility](
Our accessibility standards and resources.
[install]: ../../install/
[requirements]: ../../install/
# Performance
## Best Practices
### Realtime Components
When writing code for realtime features we have to keep a couple of things in mind:
1. Do not overload the server with requests.
1. It should feel realtime.
Thus, we must strike a balance between sending requests and the feeling of realtime.
Use the following rules when creating realtime solutions.
1. The server will tell you how much to poll by sending `Poll-Interval` in the header.
Use that as your polling interval. This way it is easy for system administrators to change the
polling rate.
A `Poll-Interval: -1` means you should disable polling, and this must be implemented.
1. A response with HTTP status `4XX` or `5XX` should disable polling as well.
1. Use a common library for polling.
1. Poll on active tabs only. Use a common library to find out which tab currently has eyes on it.
Please use [Focus]( Specifically [Eyeballs Detector](
1. Use regular polling intervals, do not use backoff polling, or jitter, as the interval will be
controlled by the server.
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.
## Reducing Asset Footprint
### Page-specific JavaScript
Certain pages may require the use of a third party library, such as [d3][d3] for
the User Activity Calendar and [Chart.js][chartjs] for the Graphs pages. These
libraries increase the page size significantly, and impact load times due to
bandwidth bottlenecks and the browser needing to parse more JavaScript.
In cases where libraries are only used on a few specific pages, we use
"page-specific JavaScript" to prevent the main `main.js` file from
becoming unnecessarily large.
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:
- content_for :page_specific_javascripts do
= page_specific_javascript_bundle_tag('lib_chart')
= page_specific_javascript_bundle_tag('graphs')
The above loads `chart.js` and `graphs_bundle.js` for this page only. `chart.js`
is separated from the bundle file so it can be cached separately from the bundle
and reused for other pages that also rely on the library. For an example, see
[this Haml file][page-specific-js-example].
### Code Splitting
> *TODO* flesh out this section once webpack is ready for code-splitting
### Minimizing page size
A smaller page size means the page loads faster (especially important on mobile
and poor connections), the page is parsed more quickly by the browser, and less
data is used for users with capped data plans.
General tips:
- Don't add new fonts.
- 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).
- 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.
## Additional Resources
- [WebPage Test][web-page-test] for testing site loading time and size.
- [Google PageSpeed Insights][pagespeed-insights] grades web pages and provides feedback to improve the page.
- [Profiling with Chrome DevTools][google-devtools-profiling]
- [Browser Diet][browser-diet] is a community-built guide that catalogues practical tips for improving web page performance.
# Security
### Resources
[Mozilla’s HTTP Observatory CLI][observatory-cli] and the
[Qualys SSL Labs Server Test][qualys-ssl] are good resources for finding
potential problems and ensuring compliance with security best practices.
<!-- Uncomment these sections when CSP/SRI are implemented.
### Content Security Policy (CSP)
Content Security Policy is a web standard that intends to mitigate certain
forms of Cross-Site Scripting (XSS) as well as data injection.
Content Security Policy rules should be taken into consideration when
implementing new features, especially those that may rely on connection with
external services.
GitLab's CSP is used for the following:
- Blocking plugins like Flash and Silverlight from running at all on our pages.
- Blocking the use of scripts and stylesheets downloaded from external sources.
- Upgrading `http` requests to `https` when possible.
- Preventing `iframe` elements from loading in most contexts.
Some exceptions include:
- Scripts from Google Analytics and Piwik if either is enabled.
- Connecting with GitHub, Bitbucket,, etc. to allow project importing.
- Connecting with Google, Twitter, GitHub, etc. to allow OAuth authentication.
We use [the Secure Headers gem][secure_headers] to enable Content
Security Policy headers in the GitLab Rails app.
Some resources on implementing Content Security Policy:
- [MDN Article on CSP][mdn-csp]
- [GitHub’s CSP Journey on the GitHub Engineering Blog][github-eng-csp]
- The Dropbox Engineering Blog's series on CSP: [1][dropbox-csp-1], [2][dropbox-csp-2], [3][dropbox-csp-3], [4][dropbox-csp-4]
### Subresource Integrity (SRI)
Subresource Integrity prevents malicious assets from being provided by a CDN by
guaranteeing that the asset downloaded is identical to the asset the server
is expecting.
The Rails app generates a unique hash of the asset, which is used as the
asset's `integrity` attribute. The browser generates the hash of the asset
on-load and will reject the asset if the hashes do not match.
All CSS and JavaScript assets should use Subresource Integrity.
Some resources on implementing Subresource Integrity:
- [MDN Article on SRI][mdn-sri]
- [Subresource Integrity on the GitHub Engineering Blog][github-eng-sri]
### 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`.
### Avoiding inline scripts and styles
In order to protect users from [XSS vulnerabilities][xss], we will disable
inline scripts in the future using Content Security Policy.
While inline scripts can be useful, they're also a security concern. If
user-supplied content is unintentionally left un-sanitized, malicious users can
inject scripts into the web app.
Inline styles should be avoided in almost all cases, they should only be used
when no alternatives can be found. This allows reusability of styles as well as
# Style guides and linting
See the relevant style guides for our guidelines and for information on linting:
## JavaScript
We defer to [Airbnb][airbnb-js-style-guide] on most style-related
conventions and enforce them with eslint.
See [our current .eslintrc][eslintrc] for specific rules and patterns.
### Common
#### ESlint
- **Never** disable eslint rules unless you have a good reason. You may see a lot of legacy files with `/* eslint-disable some-rule, some-other-rule */` at the top, but legacy files are a special case. Any time you develop a new feature or refactor an existing one, you should abide by the eslint rules.
- **Never Ever EVER** disable eslint globally for a file
// bad
/* eslint-disable */
// better
/* eslint-disable some-rule, some-other-rule */
// best
// nothing :)
- If you do need to disable a rule for a single violation, try to do it as locally as possible
// bad
/* eslint-disable no-new */
import Foo from 'foo';
new Foo();
// better
import Foo from 'foo';
// eslint-disable-next-line no-new
new Foo();
- When they are needed _always_ place ESlint directive comment blocks on the first line of a script, followed by any global declarations, then a blank newline prior to any imports or code.
// bad
/* global Foo */
/* eslint-disable no-new */
import Bar from './bar';
// good
/* eslint-disable no-new */
/* global Foo */
import Bar from './bar';
- **Never** disable the `no-undef` rule. Declare globals with `/* global Foo */` instead.
- When declaring multiple globals, always use one `/* global [name] */` line per variable.
// bad
/* globals Flash, Cookies, jQuery */
// good
/* global Flash */
/* global Cookies */
/* global jQuery */
#### Modules, Imports, and Exports
- Use ES module syntax to import modules
// bad
// good
import Foo from 'foo';
// bad
module.exports = Foo;
// good
export default Foo;
- Relative paths
Unless you are writing a test, always reference other scripts using relative paths instead of `~`
In **app/assets/javascripts**:
// bad
import Foo from '~/foo'
// good
import Foo from '../foo';
In **spec/javascripts**:
// bad
import Foo from '../../app/assets/javascripts/foo'
// good
import Foo from '~/foo';
- Avoid using IIFE. Although we have a lot of examples of files which wrap their contents in IIFEs (immediately-invoked function expressions), this is no longer necessary after the transition from Sprockets to webpack. Do not use them anymore and feel free to remove them when refactoring legacy code.
- Avoid adding to the global namespace.
// bad
window.MyClass = class { /* ... */ };
// good
export default class MyClass { /* ... */ }
- Side effects are forbidden in any script which contains exports
// bad
export default class MyClass { /* ... */ }
document.addEventListener("DOMContentLoaded", function(event) {
new MyClass();
#### Data Mutation and Pure functions
- Strive to write many small pure functions, and minimize where mutations occur.
// bad
const values = {foo: 1};
function impureFunction(items) {
const bar = 1; = items.a * bar + 2;
return items.a;
const c = impureFunction(values);
// good
var values = {foo: 1};
function pureFunction (foo) {
var bar = 1;
foo = foo * bar + 2;
return foo;
var c = pureFunction(;
- Avoid constructors with side-effects
#### Parse Strings into Numbers
- `parseInt()` is preferable over `Number()` or `+`
// bad
+'10' // 10
// good
Number('10') // 10
// better
parseInt('10', 10);
### Vue.js
#### Basic Rules
- Only include one Vue.js component per file.
- Export components as plain objects:
export default {
template: `<h1>I'm a component</h1>
#### Naming
- **Extensions**: Use `.vue` extension for Vue components.
- **Reference Naming**: Use PascalCase for Vue components and camelCase for their instances:
// bad
import cardBoard from 'cardBoard';
// good
import CardBoard from 'cardBoard'
// bad
components: {
CardBoard: CardBoard
// good
components: {
cardBoard: CardBoard
- **Props Naming**: Avoid using DOM component prop names.
// bad
<component class="btn">
// good
<component cssClass="btn">
#### Alignment
- Follow these alignment styles for the template method:
// bad
<component v-if="bar"
param="baz" />
// good
// if props fit in one line then keep it on the same line
<component bar="bar" />
#### Quotes
- Always use double quotes `"` inside templates and single quotes `'` for all other JS.
// bad
template: `
<button :class='style'>Button</button>
// good
template: `
<button :class="style">Button</button>
#### Props
- Props should be declared as an object
// bad
props: ['foo']
// good
props: {
foo: {
type: String,
required: false,
default: 'bar'
- Required key should always be provided when declaring a prop
// bad
props: {
foo: {
type: String,
// good
props: {
foo: {
type: String,