gitlab-org--gitlab-foss/doc/development/frontend.md
Jacob Schatz da57eb39cd Merge branch 'google-singletons-are' into 'master'
Decide on and document a convention for singletons

> The singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. 

The simplest implementation uses an object literal to contain the logic.

```javascript
gl.MyThing = {
  prop1: 'hello',
  method1: () => {}
};
```
A live example of this is [GfmAutoComplete](172aab108b/app/assets/javascripts/gfm_auto_complete.js.es6)

Another approach makes use of ES6 `class` syntax.
```javascript
let singleton;

class MyThing {
  constructor() {
    if (!singleton) {
       singleton = this;
       singleton.init();
     }
      return singleton;
  }

  init() {
    this.prop1 = 'hello';
  }

  method1() {}
}

gl.MyThing = MyThing;
```
A live example of this is [Sidebar](https://gitlab.com/gitlab-org/gitlab-ce/blob/master/app/assets/javascripts/sidebar.js.es6)

Another functional approach to define Singleton using `Javascript Revealing Module Pattern` is like below
```javascript
/**
  *  1. It instantiates only a single object
  *  2. It is safe – it keeps the reference to the singleton inside a variable, which lives inside a lexical closure, so it is not accessible by the outside world
  *  3. It allows privacy – you can define all private methods of your singleton inside the lexical closure of the first module pattern
  *  4. No this keyword trap (no wrong context referring)
  *  5. No use of new keyword
  *  6. Easy to write test code
  */
//
const Singleton = (function () {
  // Instance stores a reference to the Singleton
  var instance;
  function init() {
    // Singleton
    // Private methods and variables
    function privateMethod(){
        console.log( "I am private" );
    }
    var privateVariable = "Im also private";
    var privateRandomNumber = Math.random();
    return {
      // Public methods and variables
      publicMethod: function () {
        console.log( "The public can see me!" );
      },
      publicProperty: "I am also public",
      getRandomNumber: function() {
        return privateRandomNumber;
      }
    };
  };
  return {
    // Get the Singleton instance if one exists
    // or create one if it doesn't
    getInstance: function () {
      if ( !instance ) {
        instance = init();
      }
      return instance;
    }
  };
})();

const singletonObj = Singleton.getInstance()

```

## Are there points in the code the reviewer needs to double check?

## What does this MR do? 

Creates a space for discussion and contribution for interested devs.

## Why was this MR needed?

## Screenshots (if relevant)

## Does this MR meet the acceptance criteria?

- [x] [Documentation created/updated](https://gitlab.com/gitlab-org/gitlab-ce/blob/master/doc/development/doc_styleguide.md)
- [x] All builds are passing
(http://docs.gitlab.com/ce/development/merge_request_performance_guidelines.html)
- [x] Conform by the [style guides](https://gitlab.com/gitlab-org/gitlab-ce/blob/master/CONTRIBUTING.md#style-guides)
- [x] [Squashed related commits together](https://git-scm.com/book/en/Git-Tools-Rewriting-History#Squashing-Commits)

## What are the relevant issue numbers?

See merge request !6620
2016-11-17 19:48:46 +00:00

12 KiB
Raw Blame History

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 using Haml with Hamlit. Be wary of the limitations that come with using Hamlit. We also use SCSS and plain JavaScript with ES6 by way of Babel.

The asset pipeline is Sprockets, which handles the concatenation, minification, and compression of our assets.

jQuery is used throughout the application's JavaScript, with Vue.js for particularly advanced, dynamic elements.

Vue

For more complex frontend features, we recommend using Vue.js. It shares some ideas with React.js as well as Angular.

To get started with Vue, read through their documentation.

Performance

Resources

Page-specific JavaScript

Certain pages may require the use of a third party library, such as d3 for the User Activity Calendar and Chart.js 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 application.js file from becoming unnecessarily large.

Steps to split page-specific JavaScript from the main application.js:

  1. Create a directory for the specific page(s), e.g. graphs/.
  2. In that directory, create a namespace_bundle.js file, e.g. graphs_bundle.js.
  3. In graphs_bundle.js add the line //= require_tree ., this adds all other files in the directory to the bundle.
  4. Add any necessary libraries to app/assets/javascripts/lib/, all files directly descendant from this directory will be precompiled as separate assets, in this case chart.js would be added.
  5. Add the new "bundle" file to the list of precompiled assets in config/application.rb.
  • For example: config.assets.precompile << "graphs/graphs_bundle.js".
  1. Move code reliant on these libraries into the graphs directory.
  2. In the relevant views, add the scripts to the page with the following:
- content_for :page_specific_javascripts do
  = page_specific_javascript_tag('lib/chart.js')
  = page_specific_javascript_tag('graphs/graphs_bundle.js')

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.

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 does 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.

Accessibility

Resources

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 for the Chrome Accessibility Developer Tools.

Security

Resources

Mozillas HTTP Observatory CLI and the Qualys SSL Labs Server Test are good resources for finding potential problems and ensuring compliance with security best practices.

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, 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 readability.

Style guides and linting

See the relevant style guides for our guidelines and for information on linting:

Testing

Feature tests need to be written for all new features. Regression tests also need to be written for all bug fixes to prevent them from occurring again in the future.

See the Testing Standards and Style Guidelines for more information.

Running frontend tests

rake teaspoon runs the frontend-only (JavaScript) tests. It consists of two subtasks:

  • rake teaspoon:fixtures (re-)generates fixtures
  • rake teaspoon:tests actually executes the tests

As long as the fixtures don't change, rake teaspoon:tests is sufficient (and saves you some time).

If you need to debug your tests and/or application code while they're running, navigate to localhost:3000/teaspoon in your browser, open DevTools, and run tests for individual files by clicking on them. This is also much faster than setting up and running tests from the command line.

Please note: Not all of the frontend fixtures are generated. Some are still static files. These will not be touched by rake teaspoon:fixtures.

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

gl.MyThing = {
  prop1: 'hello',
  method1: () => {}
};

// good

class MyThing {
  constructor() {
    this.prop1 = 'hello';
  }
  method1() {}
}

gl.MyThing = new MyThing();

// best

let singleton;

class MyThing {
  constructor() {
    if (!singleton) {
      singleton = this;
      singleton.init();
    }
      return singleton;
  }

  init() {
    this.prop1 = 'hello';
  }

  method1() {}
}

gl.MyThing = MyThing;

Supported browsers

For our currently-supported browsers, see our requirements.

Gotchas

Phantom.JS (used by Teaspoon & Rspec) chokes, returning vague JavaScript errors

If you see very generic JavaScript errors (e.g. jQuery is undefined) being thrown in tests, but can't reproduce them manually, you may have included ES6-style JavaScript in files that don't have the .js.es6 file extension. Either use ES5-friendly JavaScript or rename the file you're working in (git mv <file.js> <file.js.es6>).

Similar errors will be thrown if you're using any of the array methods introduced in ES6 whether or not you've updated the file extension.