category: framework-contributing
{@link framework/guides/contributing/development-environment CKEditor 5 development environment} has ESLint enabled both as a pre-commit hook and on CI. This means that code style issues are detected automatically. Additionally, .editorconfig files are present in every repository to automatically adjust your IDEs settings (if it is configured to read them).
Here comes a quick summary of these rules.
LF for line endings. Never use CRLF.
The recommended maximum line length is 120 characters. It cannot exceed 140 characters.
No trailing spaces. Empty lines should not contain any spaces.
Whitespace inside parenthesis and before and after operators:
function foo( a, b, c, d, e ) {
if ( a > b ) {
c = ( d + e ) * 2;
}
}
foo( bar() );
No whitespace for an empty parenthesis:
const a = () => {
// Statements...
};
a();
No whitespace before colon and semicolon:
let a, b;
a( 1, 2, 3 );
for ( const i = 0; i < 100; i++ ) {
// Statements...
}
Indentation with tab, for both code and comments. Never use spaces.
If you want to have the code readable, set tab to 4 spaces in your IDE.
class Bar {
a() {
while ( b in a ) {
if ( b == c ) {
// Statements...
}
}
}
}
Multiple lines condition. Use one tab for each line:
if (
some != really.complex &&
condition || with &&
( multiple == lines )
) {
// Statements...
}
while (
some != really.complex &&
condition || with &&
( multiple == lines )
) {
// Statements...
}
We do our best to avoid complex conditions. As a rule of thumb, we first recommend finding a way to move the complexity out of the condition, for example, to a separate function with early returns for each "sentence" in such a condition.
However, overdoing things is not good as well and sometimes such a condition can be perfectly readable (which is the ultimate goal here).
Braces start at the same line as the head statement and end aligned with it:
function a() {
// Statements...
}
if ( a ) {
// Statements...
} else if ( b ) {
// Statements...
} else {
// Statements...
}
try {
// Statements...
} catch ( e ) {
// Statements...
}
The code should read like a book, so put blank lines between "paragraphs" of code. This is an open and contextual rule, but some recommendations would be to separate the following sections:
if(), for() and similar blocks,return statements,Example:
class Foo extends Plugin {
constructor( editor ) {
super( editor );
/**
* Some documentation...
*/
this.foo = new Foo();
/**
* Some documentation...
*/
this.isBar = false;
}
method( bar ) {
const editor = this.editor;
const selection = editor.model.document.selection;
for ( const range of selection.getRanges() ) {
const position = range.start;
if ( !position ) {
return false;
}
// At this stage this and this need to happen.
// We considered doing this differently, but it has its shortcomings.
// Refer to the tests and issue #3456 to learn more.
const result = editor.model.checkSomething( position );
if ( result ) {
return true;
}
}
return true;
}
performAlgorithm() {
// 1. Do things A and B.
this.a();
this.b();
// 2. Check C.
if ( c() ) {
d();
}
// 3. Check whether we are fine.
const areWeFine = 1 || 2 || 3;
this.check( areWeFine );
// 4. Finalize.
this.finalize( areWeFine );
return areWeFine;
}
}
Whenever there is a multi-line function call:
Examples:
const myObj = new MyClass(
'Some long parameters',
'To make this',
'Multi line'
);
fooBar(
() => {
// Statements...
}
);
fooBar(
new MyClass(
'Some long parameters',
'To make this',
'Multi line'
)
);
fooBar(
'A very long string',
() => {
// ... some kind
// ... of a
// ... callback
},
5,
new MyClass(
'It looks well',
paramA,
paramB,
new ShortClass( 2, 3, 5 ),
'Even when nested'
)
);
Note that the examples above are just showcasing how such function calls can be structured. However, it is best to avoid them.
It is generally recommended to avoid having functions that accept more than 3 arguments. Instead, it is better to wrap them in an object so all parameters can be named.
It is also recommended to split such long statements into multiple shorter ones, for example, by extracting some longer parameters to separate variables.
Use single quotes:
const a = 'I\'m an example for quotes';
Long strings can be concatenated with plus (+):
const html =
'Line 1\n' +
'Line 2\n' +
'Line 3';
or template strings can be used (note that the 2nd and 3rd line will be indented in this case):
const html =
`Line 1
Line 2
Line 3`;
Strings of HTML should use indentation for readability:
const html =
`<p>
<span>${ a }</span>
</p>`;
Block comments (/** ... */) are used for documentation only. Asterisks are aligned with space:
/**
* Documentation for the following method.
*
* @returns {Object} Something.
*/
someMethod() {
// Statements...
}
All other comments use line comments (//):
// A comment about the following statement.
foo();
// Multiple line comments
// go through several
// line comments as well.
Comments related to tickets or issues should not describe the whole issue fully. A short description should be used instead, together with the ticket number in parenthesis:
// Do this otherwise because of a Safari bug. (#123)
foo();
CKEditor 5 development environment uses ESLint and stylelint.
A couple of useful links:
eslint-config-ckeditor5).stylelint-config-ckeditor5).
Avoid using automatic code formatters on existing code. It is fine to automatically format code that you are editing, but you should not be changing the formatting of the code that is already written to not pollute your PRs. You should also not rely solely on automatic corrections.
Each class property (including methods, symbols, getters or setters) can be public, protected or private. The default visibility is public, so you should not document that a property is public — there is no need to do this.
Additional rules apply to private properties:
// comments should be used and using @private is not necessary.this[ Symbol( 'symbolName' ) ]) should be documented as @property {Type} _symbolName.Example:
class Foo {
/**
* The constructor (public, as its visibility isn't defined).
*/
constructor() {
/**
* Public property.
*/
this.foo = 1;
/**
* Protected property.
*
* @protected
*/
this._bar = 1;
/**
* @private
* @property {Number} _bom
*/
this[ Symbol( 'bom' ) ] = 1;
}
/**
* @private
*/
_somePrivateMethod() {}
}
// Some private helper.
//
// @returns {Number}
function doSomething() {
return 1;
}
The table below shows the accessibility of properties:
| Class | Package | Subclass | World | |
|---|---|---|---|---|
@public |
yes | yes | yes | yes |
@protected |
yes | yes | yes | no |
@private |
yes | no | no | no |
(yes – accessible, no – not accessible)
For instance, a protected property is accessible from its own class in which it was defined, from its whole package, and from its subclasses (even if they are not in the same package).
Protected properties and methods are often used for testability. Since tests are located in the same package as the code, they can access these properties.
You can use ES6 getters to simplify class API:
class Position {
// ...
get offset() {
return this.path[ this.path.length - 1 ];
}
}
A getter should feel like a natural property. There are several recommendations to follow when creating getters:
foo.bar == foo.bar is true). It is OK to create a new instance for the first call and cache it if it is possible.Within class definition the methods and properties should be ordered as follows:
The order within each group is left for the implementor.
There are some special rules and tips for tests.
describe() in a test file. Do not allow any globals, especially hooks (beforeEach(), after(), etc.) outside the outermost describe().The outermost describe() calls should create meaningful groups, so when all tests are run together a failing TC can be identified within the code base. For example:
describe( 'Editor', () => {
describe( 'constructor()', () => {
it( ... );
} );
// ...
} );
Using titles like "utils" is not fine as there are multiple utils in the entire project. "Table utils" would be better.
Test descriptions (it()) should be written like documentation (what you do and what should happen), e.g. "the foo dialog closes when the X button is clicked". Also, "...case 1", "...case 2" in test descriptions are not helpful.
Avoid test descriptions like "does not crash when two ranges get merged" — instead explain what is actually expected to happen. For instance: "leaves 1 range when two ranges get merged".
Most often, using words like "correctly", "works fine" is a code smell. Thing about the requirements — when writing them you do not say that feature X should "work fine". You document how it should work.
Ideally, it should be possible to recreate an algorithm just by reading the test descriptions.
Avoid covering multiple cases under one it(). It is OK to have multiple assertions in one test, but not to test e.g. how method foo() works when it is called with 1, then with 2, then 3, etc. There should be a separate test for each case.
Every test should clean after itself, including destroying all editors and removing all elements that have been added.
it().We aim at having 100% coverage of all distinctive scenarios. Covering 100% branches in the code is not the goal here — it is a byproduct of covering real scenarios.
Think about this — when you fix a bug by adding a parameter to an existing function call you do not affect code coverage (that line was called anyway). However, you had a bug, meaning that your test suite did not cover it. Therefore, a test must be created for that code change.
It should be expect( x ).to.equal( y ). NOT: .expect( x ).to.be.equal( y )
Variables, functions, namespaces, parameters and all undocumented cases must be named in lowerCamelCase:
let a;
let myLongNamedVariable = true;
function foo() {}
function longNamedFunction( example, longNamedParameter ) {}
Classes must be named in UpperCamelCase:
class MyClass() {}
const a = new MyClass();
Mixins must be named in UpperCamelCase, postfixed with "Mixin":
const SomeMixin = {
method1: ...,
method2: ...
};
Global namespacing variables must be named in ALLCAPS:
const CKEDITOR_TRANSLATIONS = {};
Private properties and methods are prefixed with an underscore:
CKEDITOR._counter;
something._doInternalTask();
Methods and functions are almost always verbs or actions:
// Good
execute();
this.getNextNumber()
// Bad
this.editable();
this.status();
Properties and variables are almost always nouns:
const editor = this.editor;
this.name;
this.editable;
Boolean properties and variables are always prefixed by an auxiliary verb:
this.isDirty;
this.hasChildren;
this.canObserve;
this.mustRefresh;
For local variables commonly accepted short versions for long names are fine:
const attr, doc, el, fn, deps, err, id, args, uid, evt, env;
The following are the only short versions accepted for property names:
this.lang;
this.config;
this.id;
this.env;
Acronyms and, partially, proper names are naturally written in uppercase. This may stand against code style rules described above — especially when there is a need to include an acronym or a proper name in a variable or class name. In such case, one should follow the following rules:
let domError.class DomError.function getDomError().let ckeditorError.class CKEditorError.function getCKEditorError().However, two-letter acronyms and proper names (if originally written uppercase) should be uppercase. So e.g. getUI (not getUi).
Two most frequently used acronyms which cause problems:
* **DOM** – It should be e.g. `getDomNode()`,
* **HTML** – It should be e.g. `toHtml()`.
CSS class naming pattern is based on BEM methodology and code style. All names are in lowercase with an optional dash (-) between the words.
Top–level building blocks begin with a mandatory ck- prefix:
.ck-dialog
.ck-toolbar
.ck-dropdown-menu
Elements belonging to the block namespace are delimited by double underscore (__):
.ck-dialog__header
.ck-toolbar__group
.ck-dropdown-menu__button-collapser
Modifiers are delimited by a single underscore (_). Key-value modifiers
follow the block-or-element_key_value naming pattern:
/* Block modifier */
.ck-dialog_hidden
/* Element modifier */
.ck-toolbar__group_collapsed
/* Block modifier as key_value */
.ck-dropdown-menu_theme_some-theme
In HTML:
<div class="ck-reset_all ck-dialog ck-dialog_theme_lark ck-dialog_visible">
<div class="ck-dialog__top ck-dialog__top_small">
<h1 class="ck-dialog__top-title">Title of the dialog</h1>
...
</div>
...
</div>
HTML ID attribute naming pattern follows CSS classes naming guidelines. Each ID must begin with the ck- prefix and consist of dash–separated (-) words in lowercase:
<div id="ck">...</div>
<div id="ck-unique-div">...</div>
<div id="ck-a-very-long-unique-identifier">...</div>
File and directory names must follow a standard that makes their syntax easy to predict:
-) (kebab-case).
DataProcessor class is defined in the dataprocessor.js file.mutations-in-multi-root-editors.js..html extension.ckeditor.jstools.jseditor.jsdataprocessor.jsbuild-all.js and build-min.jstest-core-style-system.htmlWidely used standard files do not obey the above rules:
README.md, LICENSE.md, CONTRIBUTING.md, CHANGES.md.gitignore and all standard "dot-files"node_modules