Manual:Coding conventions/JavaScript/cs

Tato stránka popisuje kódovací konvence pro JavaScript v MediaWiki codebase. Viz také obecné konvence.

Odkazování
Jako náš nástroj pro kvalitu kódu používáme ESLint s přednastavením eslint-config-wikimedia pro kódování většiny našich stylů kódování a pravidel kvality kódu. Na stránce Integrations na eslint.org najdete mnoho textových editorů nebo IDE s pluginy, které poskytují živou zpětnou vazbu při psaní.



Konfigurace Linter
Chcete-li z analýzy vyloučit soubory nebo adresáře (např. knihovny třetích stran), můžete konfigurovat vzory ignorování v ESLint prostřednictvím souboru. Všimněte si, že  je ve výchozím nastavení vyloučen, takže většina repozitářů nemusí nastavovat žádná pravidla ignorování.

Každé repo potřebuje soubor  v kořenovém adresáři úložiště. Následuje příklad konfiguračního souboru ESLint:

Živé příklady viz .eslintrc.json v MediaWiki a VisualEditoru.

Nezapomeňte nastavit, abyste předešli nechtěnému "magickému dědění" konfigurací ESLint v nesouvisejících nadřazených adresářích, které jste vy nebo server CI mohli nastavit na disku (například mezi rozšířením MediaWiki a jádrem MediaWiki nebo mezi vaším projektovým adresářem a něčím v váš domovský adresář).

Přednastavení eslint-config-wikimedia poskytuje několik profilů, ze kterých si mohou projekty vybrat, jak uznají za vhodné, jako jsou různé jazykové příchutě nebo globální prostředí běhového prostředí. Například:


 * - pro kód prohlížeče a očekává podporu ES5
 * - pro kód prohlížeče, který používá ES6
 * - pro kód Node.js 10+ a očekává podporu ES2018
 * - mix pro testy QUnit

Měli byste očekávat použití více souborů  v repo pro nastavení různých environmentálních očekávání pro různé podadresáře. Tím je zajištěno, že nepoužijete náhodou metody  v kódu serveru, který očekáváte na serveru, nebo že v produkčním kódu neodkážete na QUnit. soubory v podadresářích automaticky dědí z konfigurace nadřazeného adresáře, takže musí obsahovat pouze věci, které jsou specifické pro daný adresář (example file).



Nepřetržitá integrace
Projektům se doporučuje, aby prosadily předávání ESLint tím, že do něj zahrnou svůj  skript pomocí příkazu "test" do. Více informací o tom najdete na Continuous integration/Entry points.

Pokud má váš projekt poměrně náročný testovací kanál, lze definovat skript  nebo dokonce   v , aby bylo snadné spouštět pouze ty z příkazového řádku během místního vývoje (abyste nemuseli otevírat každý soubor v editoru a/nebo čekat na CI).

Chcete-li odhalit další funkce příkazového řádku z ESLint (jako je lintování jednotlivých souborů mimo textový editor nebo použití funkce --fix), definujte "eslint" jako vlastní skript v package.json bez jakéhokoli argumentu. Poté jej můžete vyvolat z příkazového řádku následovně:

Mezery
Používáme následující konvence:


 * Odsazení s tabulátory.
 * Žádné mezery na konci.
 * Oddělení jednoho bloku logicky souvisejícího kódu od druhého pomocí prázdných řádků.
 * Jedna mezera na obou stranách binárních operátorů a operátorů přiřazení.
 * Klíčová slova následovaná " " (levá závorka) musí být oddělena jednou mezerou. To poskytuje vizuální rozlišení mezi klíčovými slovy a vyvoláním funkcí.
 * Mezi názvem funkce a levou závorkou seznamu argumentů by neměla být žádná mezera.
 * Uvnitř závorek (jako jsou příkazy if, volání funkcí a seznamy argumentů) by měla být jedna mezera.
 * Nepoužívejte operátory, jako by to byly funkce (například,  ,  ,  ,  , ..).

Tyto a další aspekty našeho průvodce stylem jsou vynuceny pomocí ESLint.



Délka řádku
Řádky by neměly být delší než 80–100 znaků. Pokud se příkaz nevejde na jeden řádek, rozdělte příkaz na více řádků. Pokračování prohlášení by mělo být odsazeno o jednu úroveň navíc.

Volání funkcí a objekty by měly být buď na jednom řádku, nebo rozděleny na více řádků s jedním řádkem pro každý segment. Vyvarujte se zavírání volání funkce nebo objektu v jiném odsazení, než je jeho otevření.

Structure
In a nutshell:

Closure
If a module bundle can't or otherwise isn't yet registered using package files, then its individual JavaScript files should have a file-level closure around its code. This gives the code its own scope, and avoids leakage of variables from or to other files, including in debug mode, and in a way that is understood by static analysis. This pattern is known as an immediately-invoked function expression (or "iffy" ).

For package files this is not needed, as their are executed as a "module" file rather than a "script" file, which naturally have their own local scope. ESLint should also be configured accordingly (set, like in this example).

Declarations
Variables must be declared before use. Each assignment must be on its own line. Variables may be declared near or at their first assignment.

If combining multiple  assignments in one statement, then declarations that don't assign a value should be listed before assignments. The subsequent lines should be indented another level.

Functions should be declared before use. In the function body, function declarations should go after variable declarations and before any main statements.

Comments
Comments should be on their own line and go over the code they describe.

Within a comment, the opening syntax (e.g. slash-slash, or slash-star) should be separated from the text by a single space, and the text should start with a capital letter. If the comment is a valid sentence, then a full stop should be placed at the end of it.

Use line comments within functions and other code blocks (including for multi-line comments).

Use block comments only for documentation blocks. This helps maintain consistent formatting for inline comments (e.g. not some as blocks and some as multi-line comments, or having to convert from one to the other). It also avoids confusing documentation engines. It also makes it easy to disable parts of the code during development by simply moving the end-comment notation a few lines down, without being short-circuited by an inline block comment.

Be liberal with comments and don't fear file size because of it. All code is automatically minified by ResourceLoader before being shipped.

Documentation comments

 * Text in free-form blocks should be sentence case (e.g. description of methods, parameters, return values etc.)
 * Start sentences with a capital letter.
 * Continue sentences belonging to an annotation on the next line, indented with one additional space.

Generated documentation

 * We are currently moving from JSDuck to JSDoc, as the former is unmaintained.

The below will be updated once JSDoc is adopted in MediaWiki core.

Use JSDuck to build documentation (see https://doc.wikimedia.org).

JSDuck is pre-installed in Fresh environments and in WMF CI. To install it in custom developer environment, use to install it from RubyGems. See the upstream guide for more information.

To generate the documentation, the standard entry point  should be used, as defined in.

Configure JSDuck in your project via a  file. See JSDuck configuration, or check examples.

Tags
We use the following annotations. They should be used in the order as they are described here, for consistency. See the JSDuck documentation for how these work.


 * @abstract
 * @private
 * @ignore
 * @static
 * @class Name (name is optional, engine will guess name from context)
 * @singleton
 * @extends ClassName
 * @mixins ClassName
 * @constructor
 * @inheritable
 * @member
 * @method name (name is optional, guessed)
 * @property name (name is optional, guessed)
 * @inheritdoc
 * @deprecated
 * @param {Type} name Optional text.
 * @return {Type} Optional text.
 * @chainable
 * @throws {Type}
 * @cfg {Type} [name="default value"] (used when a configuration object is passed to the class constructor, use one for each property and don't include those of parent constructors)

Types
Primitive types and special values: boolean, number, string, undefined, null.

Built-in classes: Object, Array, Function, Date, RegExp, Error.

Equality

 * Use strict equality operators ( and  ) instead of (loose) equality (  and  ). The latter does type coercion.
 * No Yoda conditionals.

Type checks

 * string:
 * number:
 * boolean:
 * Function:
 * null:
 * object:
 * Plain Object:
 * Array:
 * HTMLElement:
 * undefined:
 * Local variables:
 * Properties:
 * Global variables:

Strings
Use single quotes instead of double quotes for string literals. Remember there are no "magic quotes" in JavaScript i.e.  and   work everywhere.

To extract part of a string, use the  method for consistency. Avoid the, or   methods which are redundant, easily mistaken, and may have unexpected side effects.

Exporting
Use globals exposed by the browser (such as document, location, navigator) directly and not as properties of the window object. This improves confidence in code through static analysis and may also power other IDE features. In addition to browser globals, the only globals that are safe to use are,   and.

Avoid creating new global variables. Avoid modifying globals not "owned" by your code. For example, built-in globals such as String or Object must not be extended with additional utility methods, and similarly functionality relating to OOjs or jQuery, should not be assigned to those globals.

To publicly expose functionality for re-use, use  from Package files, and/or assign properties within the   hierarchy, e.g..

Note that configuration variables exposed by MediaWiki must be accessed via. For backward compatibility with legacy user scripts and gadgets, many -prefixed configuration keys are still defined as global varables as well, but these are deprecated. (See T72470.)

Environment
Modifying built-in protypes such as  is considered harmful. This is not supported in MediaWiki code, and doing so will likely result in breakage of unrelated features.

Naming
All variables must be named using CamelCase starting with a lowercase letter, or use all caps (with underscores for separation) if the variable represents some kind of constant value.

All functions must be named using CamelCase, generally starting with a lowercase letter unless the function is a class constructor, in which case it must start with an uppercase letter. Method functions are preferred to start with verb, e.g.  instead of "foo".

Acronyms
Names with acronyms in them should treat the acronym as a normal word and only uppercase the first letter as-needed. This applies to two-letter abbreviations as well, such as. For example,  as opposed to "getHTMLAPISource".

jQuery
Distinguish DOM nodes from jQuery objects by prefixing variables with a dollar sign if they will hold a jQuery object, e.g. . This helps reduce mistakes where conditions use incorrect conditional checks, such as   instead of. Where DOM methods often return null (which is falsey), jQuery methods return an empty collection object (which, like native arrays and other objects in JavaScript, are truthly).

npm
When publishing a standalone project to npmjs.org, consider publishing it under the  namespace. Note that some standalone projects, that are aimed at use outside the Wikimedia community and have a sufficiently unique name, currently use an unnamespaced package name (e.g. "oojs" and "visualeditor"). T239742

Creating elements
To create a plain element, use the simple syntax in the jQuery constructor:

When creating elements based on the tag name from a variable (which may contain arbitrary html):

Only use when you need to parse HTML (as opposed to creating a plain element).

Collections
Different types of collections sometimes look similar but have different behaviour and should be treated as such. This confusion is mostly caused by the fact that arrays in JavaScript look a lot like arrays in other languages, but are in fact just an extension of Object. We use the following conventions:

Avoid using a  loop to iterate over an array (as opposed to a plain object), because    will result in many unexpected behaviours, including: keys as strings, unstable iteration order, indexes may skip gaps, iteration may include other non-numerical properties.

Storage
Keys in localStorage and/or sessionStorage should be accessed via  or.

Keys
Keys should start with  and use camel case and/or hyphens. Do not use underscores or other separators. Examples of real keys:



Beware that contrary to cookies via mw.cookie, there is no wiki prefix or cookie prefix added by default. If values must vary by wiki, you must manually include  as part of the key.

Values
Values must be strings. Beware that attempting to store other value types will silently cast to a string (e.g.  would become  ).

Space is limited. Use short and concise values over object structures where possible. A few example:


 * For boolean state (true/false, expanded/collapsed) use "1" or "0".
 * For values that are always numbers, store them as-is and cast with  on the way out (avoid  ).
 * For values that are always strings, store them as-is.
 * For lists of software-defined values, consider comma-separated or pipe-separated strings to reduce space and processing cost.
 * For lists of values that may be user-generated or are otherwise complex in nature, use JSON.

Eviction strategy
Remember that Local storage does not have any eviction strategy by default. Therefore the following should be avoided:


 * Avoid using user-generated input as part of a key name.
 * Avoid keys containing identifiers for user-generated entities (e.g. user names, category names, page ids, or other user-provided or system-provided variables).
 * In general avoid approaches that involve creating a potentially large number of storage keys.

For example, if a feature needs to store state about a variable entity (e.g. current page), it might make sense to use a single key for this feature as a whole and to limit the stored information only to the last few iterations (LRU). The slight increase in retrieval cost (the whole key, instead of separate smaller ones) is considered worth it, as otherwise the number of keys would grow uncontrollably.

Even if the keys are not dependent on user-input, you may still want to use a single key for your feature because otherwise past versions of your software will have stored data that you can't clean up. By using a single key you can roundtrip it in a way that naturally doesn't persist unknown sub properties.

Use of a tracking key is also an anti-pattern and does not avoid the above issues, as this would leak due to race conditions in HTML5 web storage being shared and non-atomic between multiple open browser tabs.

When feature's use of Local storage is to be removed, be sure to implement an eviction strategy first to clean up old values. Typically mw.requestIdleCallback is used to gracefully look for the key and remove it. See T121646 for a more scalable approach.

Personal information
Avoid storing personal information in Local storage as it remains when a user logs out or closes their browser. Use Session storage instead. See T179752.

Asynchronous code
Asynchronous code should follow, and be compatible with, the Promise standard.

When you define an asynchronous method for other code to call, you may internally construct the returned thenable object either using $.Deferred or native Promise. Remember to depend on the  polyfill if using Promise (this polyfill is automatically skipped and excluded from your module bundle in modern browsers).

When you call an asynchronous method, use only standard Promise-compatible methods such as  and. Avoid using jQuery-specific methods like  or , which could stop working without warning if the method you are calling internally transitions from $.Deferred to native Promise.

Note that there are also subtle legacy behaviours in the "done" and "fail" callbacks. Pay close attention when migrating existing code from  to   as doing so may cause the code to stop working correctly. Specifically, the "done" and "fail" callbacks invoke your callback synchronously if the Deferred was already settled by the time you attach your callback. This means your callback may be invoked before the attaching statement is finished running.

For example:

Reuse ResourceLoader modules
Don't reinvent the wheel. Much JavaScript functionality and MediaWiki-related utilities ship with MediaWiki core that are stable and you can (literally) depend on them. See ResourceLoader/Core modules before rolling your own code.

Pitfalls
Read more:
 * Be careful to preserve compatibility with left-to-right and right-to-left languages (i.e.  or  ), especially when styling text containers. Putting those declarations in CSS file will allow them to be automatically flipped for RTL-languages by CSSJanus in ResourceLoader.
 * Use  and   appropriately.
 * jQuery#attr, jQuery API
 * Attributes and custom properties, javascript.info
 * Consistently quote attribute selector values:  instead of   (jqbug 8229).
 * As of jQuery 1.4 the jQuery constructor has a new feature that allows passing an object as second argument, like . Don't use this. It makes code harder to follow, fails on attributes (such as 'size') that are also methods, and is unstable due to this mixing of jQuery methods with element attributes. A future jQuery method or plugin called "title" might convert an element into a heading, which means the title attribute can also no longer be set through this method. Be explicit and call ,  ,   etc. directly.

Use CSS for styling many elements
Don't apply styling to lots of elements at once; this has poor performance. Instead use a common parent's class (or add one) and apply CSS in a  or   file. Thanks to ResourceLoader, this will all be loaded in the same HTTP request, so there's no performance penalty for having a separate CSS file. Do not set CSS into inline "style" attributes, don't insert "style" elements from JS either.