Don't go overboard with <code>bind</code>, however. If you find yourself writing deep nested .bind()ed functions only to access outer state, consider using a lexical closure instead. (As a bonus, lexical closures can be statically checked for misspellings by the validator; field accesses through <code>this</code> cannot).

Don't go overboard with <code>bind</code>, however. If you find yourself writing deep nested .bind()ed functions only to access outer state, consider using a lexical closure instead. (As a bonus, lexical closures can be statically checked for misspellings by the validator; field accesses through <code>this</code> cannot).

-->

-->

+

+

== Classes ==

+

=== Writing a class ===

+

The Orion approach to writing "classes" is fairly straightforward. It doesn't require any fancy libraries, just constructor functions and prototypes:

+

function Duck(name) {

+

this.name = name;

+

}

+

Duck.prototype.greet = function() {

+

console.log("Quack quack, my name is " + this.name);

+

};

+

+

The <code>mixin()</code> function from the <code>orion/objects</code> module can make your code more compact when you have a lot of properties to add to the prototype. Using <code>mixin</code>, the above example would look like:

+

function Duck(name) {

+

this.name = name;

+

}

+

objects.mixin(Duck.prototype, {

+

greet: function() {

+

console.log("Quack quack, I'm a duck named " + this.name);

+

}

+

//, more properties here...

+

});

+

+

=== Subclassing ===

+

To extend a class and add additional properties, we use a pattern similar to the code shown below. The subclass's constructor explicitly invokes the superclass's constructor to perform the usual <code>Duck</code> initialization, and then performs some extra initialization specific to the subclass. Note how <code>Object.create</code> is used to set up the desired prototype chain.

In older code, you may see <code>new</code> used to extend the superclass's prototype. This is an abuse of constructors, and creates a bogus instance of the superclass just to achieve the desired side effect of setting the prototype. Always use <code>Object.create</code> instead. If you have to support non-ES5 browsers, write a [http://www.room51.co.uk/js/beget.html beget utility].

+

+

&#x2718; Don't use <code>new</code> to extend a superclass's prototype object.

+

SeaDuck.prototype = new Duck();

+

+

==== Overriding methods ====

+

To override a method, we just add a method to the subclass's prototype having the same name as the superclass method:

+

// overrides Duck.protoype.greet

+

SeaDuck.prototype.greet = function() {

+

console.log("Avast, I'm a sea duck named " + this.name);

+

};

+

JavaScript's prototypal inheritance also allows you to override methods on a per-instance basis, rather than per-class (although readers familiar with Java-style class models may find this surprising).

+

+

To invoke the superclass's implementation of an overridden method (the equivalent of the Java <code>super</code> keyword), you need to explicitly call it using <code>SuperConstructor.prototype.methodName.call(this);</code>:

In most cases it's convenient to use <code>orion/xhr</code>, which wraps the browser's native XMLHttpRequest into a promise. The xhr API is [https://orionhub.org/jsdoc/symbols/orion.xhr.html documented here].

In most cases it's convenient to use <code>orion/xhr</code>, which wraps the browser's native XMLHttpRequest into a promise. The xhr API is [https://orionhub.org/jsdoc/symbols/orion.xhr.html documented here].

−

xhr("GET", "/index.html").then(

+

define["orion/xhr"], function(xhr) {

−

function(xhrResult) {

+

xhr("GET", "/index.html").then(

−

console.log("Got response: " + xhrResult.response);

+

function(xhrResult) {

−

},

+

console.log("Got response: " + xhrResult.response);

−

function(xhrResult) {

+

},

−

console.log("An error occurred: " + xhrResult.error);

+

function(xhrResult) {

−

});

+

console.log("An error occurred: " + xhrResult.error);

+

});

+

});

== URLs ==

== URLs ==

Line 291:

Line 360:

Consider also using the <code>orion/URITemplate</code> module, which implements the [http://tools.ietf.org/html/rfc6570 URI Template spec].

Consider also using the <code>orion/URITemplate</code> module, which implements the [http://tools.ietf.org/html/rfc6570 URI Template spec].

−

== Library Objects ==

−

API library objects all fall under the 'orion' namespace. For example a library object for managing bookmarks might be called <tt>orion.Bookmarks</tt>.

== Services ==

== Services ==

Line 305:

Line 372:

== JS Documentation ==

== JS Documentation ==

−

All JavaScript API uses [http://code.google.com/p/jsdoc-toolkit/ JSDoc] syntax. Orion code is written as self-contained AMD modules that don't expose global objects. So rather than tagging the actual objects with documentation, we tend to use JSDoc tags to construct virtual "classes" corresponding to a module's exported API. These virtual tags can appear almost anywhere in the source code, but it's best to keep them close to the functions that they they represent.

+

All JavaScript API uses [http://code.google.com/p/jsdoc-toolkit/ JSDoc] syntax. Orion code is written as self-contained AMD modules that don't expose global objects. So rather than tagging the actual objects with documentation, we tend to use JSDoc tags to construct virtual "classes" corresponding to a module's exported API. These virtual tags can appear almost anywhere in the source code, but it's best to keep them close to the functions that they represent.

The principal doc tags used are:

The principal doc tags used are:

−

; @param

+

; [http://code.google.com/p/jsdoc-toolkit/wiki/TagParam @param]

: Documentation of method parameters. See [http://code.google.com/p/jsdoc-toolkit/wiki/TagParam TagParam] in the jsdoc wiki for further details.

: Documentation of method parameters. See [http://code.google.com/p/jsdoc-toolkit/wiki/TagParam TagParam] in the jsdoc wiki for further details.

−

; @name

+

; [http://code.google.com/p/jsdoc-toolkit/wiki/TagName @name]

: For specifying class names. The class name should match the RequireJS module name.

: For specifying class names. The class name should match the RequireJS module name.

−

; @lends

+

; [http://code.google.com/p/jsdoc-toolkit/wiki/TagLends @lends]

: For specifying what class a prototype contributes to

: For specifying what class a prototype contributes to

−

; @class

+

; [http://code.google.com/p/jsdoc-toolkit/wiki/TagClass @class]

: Indicates that this comment represents a class definition. The text of the @class tag becomes the class description.

: Indicates that this comment represents a class definition. The text of the @class tag becomes the class description.

: A detailed description of what this class, function, or field does. The first sentence will be used as a one-line summary of the class constructor. If @description is not given explicitly, the header of the comment is used.

: A detailed description of what this class, function, or field does. The first sentence will be used as a one-line summary of the class constructor. If @description is not given explicitly, the header of the comment is used.

−

References:

+

See also the complete [http://code.google.com/p/jsdoc-toolkit/wiki/TagReference JSDoc tag reference].

Because JavaScript's prototypal inheritance doesn't quite fit the class-oriented model of JSDoc, there's a few different approaches for documenting methods, depending on how your "class" is built. The general pattern for a method uses the tags:

Because JavaScript's prototypal inheritance doesn't quite fit the class-oriented model of JSDoc, there's a few different approaches for documenting methods, depending on how your "class" is built. The general pattern for a method uses the tags:

−

; @name

+

; [http://code.google.com/p/jsdoc-toolkit/wiki/TagName @name]

: Gives name of this method. This can be fully-qualified (in which case <code>.</code> indicates static membership, and <code>#</code> indicates instance membership).

: Gives name of this method. This can be fully-qualified (in which case <code>.</code> indicates static membership, and <code>#</code> indicates instance membership).

−

; @function

+

; [http://code.google.com/p/jsdoc-toolkit/wiki/TagFunction @function]

: Tells JSDoc we're documenting a function (otherwise it will assume a field).

: Tells JSDoc we're documenting a function (otherwise it will assume a field).

If you're using the <code>@methodOf/memberOf</code> style instead, add the tag <code>@static</code> to achieve the same effect.

+

JSDoc also has a <code>@static</code> tag, but you probably won't need it.

===== Types =====

===== Types =====

−

Any type known to the JSDoc parser can appear inside the curly braces of a <code>@param</code> or <code>@return</code> tag. A type can be a fully-qualified class name, or a global JavaScript object like Boolean, String, Function and so on. The Orion source generally uses the capitalized object wrapper names to refer to primitive types: for example we say <code>String</code> rather than <code>string</code>, <code>Boolean</code> rather than <code>boolean</code>, and so on.

+

One helpful feature of JSDoc is ''types'', which can appear inside the curly braces of a <code>@param</code> or <code>@return</code> tag, and a few other places as well. When the JSDoc parser recognizes a reference to a type, it turns it into a clickable hyperlink in the HTML documentation, which is very nice.

+

+

A type can be a fully-qualified class name, or a global JavaScript object like Boolean, String, Function, etc. The Orion source generally uses the capitalized object wrapper names to refer to primitive types: for example we say <code>String</code> rather than <code>string</code>, <code>Boolean</code> rather than <code>boolean</code>, and so on.

+

+

JSDoc also understands array types: append <code>[]</code> after the name of any type to indicate that it's an array.

+

/**

+

* @param <b>{orion.Promise[]}</b> promises

+

*/

+

+

To indicate that a param or return type takes one of a set of types, join the types with a <code>|</code>:

+

/**

+

* @param <b>{String|Element}</b> elementOrDomId

+

*/

+

+

When a type can be "anything", we represent it as <code>{Object}</code>.

==== Fields ====

==== Fields ====

+

+

== JSLint ==

+

While most validation problems raised by JSLint are helpful, there are some situations where they need to be ignored. In these cases, add a <code>/*jslint ... */</code> comment block near the top of your code that turns off the problems. A sample jslint block might look like:

+

/*jslint forin:true regexp:false sub:true*/

+

Here's a list of common warnings and how to deal with them:

+

+

; <code>["foo"]</code> is better written in dot notation.

+

: This warning is raised when code uses the <code>[]</code> operator to access a constant property name. It's good practice to use the <code>.</code> operator instead. When changing the code is unfeasible (for example, when dealing with output from the [[Orion/Internationalization#String_Xtrnalizr|Orion string externalization plugin]]), use <code>sub:true</code> to disable this warning.

+

+

; Bad line breaking before {something}

+

: Use <code>laxbreak:true</code> to disable this warning. Be very careful breaking around a <code>return</code> statement, however: JavaScript's [http://en.wikipedia.org/wiki/JavaScript_syntax#Whitespace_and_semicolons semicolon insertion] can produce unexpected results.

+

+

; Insecure <code>'^'</code>.

+

: This warning is raised on regular expressions that use a negated character set like <code>[^A-Z]</code>. Use <code>regexp:false</code> to disable the warning.

+

+

; The body of a <code>for in</code> should be wrapped in an if statement to filter unwanted properties from the prototype

+

: While this is generally good advice, sometimes an unfiltered loop is desirable. Use <code>forin:true</code> to disable this warning.

+

+

; Statement body should be inside <code>'{ }'</code> braces.

+

: JSLint raises this warning when you write a block-style statement (like <code>if</code>, <code>else</code>, <code>for</code>, <code>while</code>) without enclosing the statements inside the block in curly braces <code>{ }</code>. There's no way to disable this warning, so it's best to just add the curly braces and carry on.

+

+

; '{variable}' is already defined.

+

: This warning is raised when you define the same variable more than once within a function. Usually this results from a misunderstanding of [https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/block JavaScript's scoping rules]. In JavaScript, <code>var</code> is scoped to the enclosing function, '''not''' the enclosing block. When two blocks define the same variable, it is redundant and may mislead readers as to the underlying language semantics. To eliminate this warning (and make your code clearer), move the variable definition outside the blocks.

+

+

&#x2718; Don't redefine a variable inside a block:

+

if (condition) {

+

var x = 'foo';

+

} else {

+

var x = 'bar'; // 'x' is already defined

+

}

+

+

&#x2714; Define the variable outside the block instead:

+

var x;

+

if (condition) {

+

x = 'foo';

+

} else {

+

x = 'bar';

+

}

+

+

It's OK to define a variable inside a block if the variable is not referenced anywhere else in the function.

= HTML =

= HTML =

Line 432:

Line 552:

== HTML Fragments and Templates ==

== HTML Fragments and Templates ==

−

When writing a visual component, it's often convenient to define a fragment of HTML that serves as the component's template. Orion provides a shim for the draft [https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/templates/index.html HTML Templates API] that helps you use templates in an efficient way.

+

When writing a visual component, it's often convenient to define a fragment of HTML that serves as the component's template. There are several ways to go about this. This section discusses when you might want to use the different approaches, and what our long term direction is.

−

When using a template, you typically want to clone the node structure described by the template and insert it into your document. Document fragments are also defined by simply defining a text HTML string, either in a Java file, or in an HTML file that is referenced via requirejs text! modules. There are several different ways to get from an HTML description of UI to a node. You can use template.cloneNode(), range.createContextualFragment(htmlString), or innerHTML. (Which do we recommend and when?) Regardless of technique, ensure that strings from plug-ins (such as message strings) are not included in the template. They must be inserted via DOM API so that plugins cannot attach arbitrary HTML to the page.

+

=== Where is the fragment defined? ===

+

A fragment is a little chunk of HTML that describes a component. There are a few choices in the mechanics of where a fragment is defined.

+

* A fragment could be defined in js code as a string. Consider this snippet from the dialog prototype:

An advantage of this approach when using Orion to edit fragments is keeping the fragment close to the JavaScript code that is manipulating it or making assumptions about its structure. This is, of course, a tooling issue (not having split editors, or popping up references, etc.) The disadvantage is the noise created by concatenation, $NON-NLS markings, etc. This kind of code also tempts the developer to directly concatenate NLS message strings into the content, and that is a security risk (described later).

−

NLS message strings can be bound to a template using the <tt>processTextNodes</tt> function in 'orion/webui/littlelib'. This allows you to refer to the strings in your template using variables, and DOM API will be used later to bind your string to your HTML. For example, here is the html for the orion page footer. Note the use of the ${variable} syntax in the text.

+

* A fragment can be defined in an HTML file that is brought into the JavaScript module via a requirejs <tt>text!</tt> module. For example, the common page footer is defined in a footer.html file like this:

* A fragment can also be defined inside a template element. Orion provides a shim for the draft [https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/templates/index.html HTML Templates API] that lets you define <tt>template</tt> elements. Templates are a promising approach for the following reasons:

+

** if you use the fragment many times on a page, using a template means it will be parsed only once.

+

** once parsed, you can make common, dynamic modifications to the template (binding variable values, etc.) only once.

+

** the DOM structure behind a template is not associated with the document until a node is actually cloned. This means that if the template references network resources (such as an image URL), there will be no attempt to download the image until the template is actually cloned into a node and placed in the document.

+

+

If we used a template for the footer fragment, it would look like this instead. (Using a template for a footer that appears once is not necessarily a good idea, but this is shown to illustrate the difference in approach:)

The example above assumes that we have a requirejs plugin for parsing html files and building a template element. ([https://bugs.eclipse.org/bugs/show_bug.cgi?id=395402 Bug 395402]). Until we have such a plugin, the template would have to be marked up in the page itself.

+

+

=== Inserting text fragments ===

+

As mentioned above, a template element is preferred for fragments repeated many times, or to delay/reduce the network traffic associated with associating a fragment with a document. However, our tooling for letting library modules bring in templates is not complete here. If you are using text fragments in library modules, or you have a "one-off" fragment, it is reasonable to insert the fragment into the DOM without using a template element. Suppose you have a text fragment you want to insert into the document. (You could have created this text fragment in the JavaScript as a string or imported as a <tt>text!myFragment</tt> module. It doesn't matter.)

+

+

To get it into the document you have several approaches:

+

==== innerHTML ====

+

If you have a node that is exclusive to the fragment, you can use the <tt>innerHTML</tt> of the node. The original footer example showed this.

Of course, if there were any other nodes inside the footer DOM node, they would be removed.

+

+

==== createContextualFragment ====

+

Another approach, useful when you are adding a fragment to a parent and don't want to remove other child nodes, is to create a contextual fragment and then add it into the DOM as you would any other node. For example, this code adds a banner fragment as the first child of the document body.

Often, you'll want to bind some data to a fragment. For example, you might want to describe some text using its i18n/NLS message key name, which comes from a plug-in. Or perhaps the text in the template depends on some JSON property on the server. Regardless of how you created your fragment, you'll need to ensure that these strings are not bound directly as text in a fragment. They should be inserted as text nodes in the DOM. This restriction is necessary so that plugins or other external sources cannot insert arbitrary HTML into the page.

+

+

Do not concatenate variable strings into a fragment and insert into the document. Instead, a data binding approach should be used to refer to the values by their key. Strings can be bound to a fragment using the <tt>processTextNodes</tt> function in 'orion/webui/littlelib'. This utility allows you to refer to the strings in your template using variables, and DOM API will be used later to bind your string to the text node in the HTML. You may have noticed in the Orion footer example, we use ${variable} syntax in the markup. The user of such a fragment is responsible for providing the correct data binding object for processing the DOM elements.

This data binding approach can be used for any object, not just NLS message objects. When the DOM tree text nodes are processed, any nodes that have the ${variable} syntax will be considered to describe a property name. The text nodes containing the variables will be replaced with nodes containing matching property value found in the bound object. If no matching property is found, the original text remains.

JavaScript

Compatibility

In general, Orion's JavaScript code is targeted toward modern JS runtimes. This means you can (and should) use ECMAScript 5 features like Object.keys, Array.prototype.forEach, and so on. ECMAScript 6 features should not be used, as they are not yet widely supported.

Some of Orion's client bundles may have more strict requirements about what features are allowed. For example, the Orion Editor supports older browsers like Internet Explorer 8, and thus has to avoid most ES5 features (even Array.prototype.indexOf is not allowed in IE8).

If your code depends on globals (eg. define, require, jQuery) or browser objects (eg. document, setTimeout), they should be explicitly listed in a /*global */ section near the top of the file. This allows them to be statically checked for misspellings by the validator. At minimum, you should have /*global define*/.

* Shims are an exception to the "no globals" rule. See URL-shim.js for an example.

Internal data

All member variables starting with an underscore ('_') or having the @private jsdoc tag, are internal and should not be referenced by clients. Such variables are subject to change or removal at any time.

Arrays

Testing if a value is an array

Looping through elements

✘ Don't use a loop variable. It is more prone to typing errors, and hinders refactoring by polluting the containing function's scope with i.

for (var i=0; i < array.length; i++) {
// ...
}

Having said that, a typical for loop will perform faster than the forEach function. Performance-critical code may need to use for, but it's best to use forEach until you've demonstrated that it's too slow for your needs.

Determining if every element satisfies a condition

Removing elements that satisfy a condition

Objects

Testing equality

In comparisons, always use the strict equality === and strict inequality !== operators. This makes your code's intent clear to other readers. While the nonstrict equality == may seem like a nice shortcut, it performs type conversions that can be surprising.

✘ For example, a nonstrict comparison against null doesn't behave like you might expect:

if (value == null) {
console.log("value is null... or is it?");
// do stuff with value
}

Since undefined == null, the above code allows value to be undefined and pass the if-test, which may cause problems later on.

But why not just compare against undefined? Well, undefined is actually a reference to the global window.undefined property, not a primitive value. (Older JS engines would actually allow undefined to be overwritten, although ES5 has thankfully prevented that.) Because undefined is a legal variable name, it makes your code vulnerable to accidental lexical closures if someone else has foolishly created an in-scope variable named undefined:

Subclassing

To extend a class and add additional properties, we use a pattern similar to the code shown below. The subclass's constructor explicitly invokes the superclass's constructor to perform the usual Duck initialization, and then performs some extra initialization specific to the subclass. Note how Object.create is used to set up the desired prototype chain.

In older code, you may see new used to extend the superclass's prototype. This is an abuse of constructors, and creates a bogus instance of the superclass just to achieve the desired side effect of setting the prototype. Always use Object.create instead. If you have to support non-ES5 browsers, write a beget utility.

✘ Don't use new to extend a superclass's prototype object.

SeaDuck.prototype = new Duck();

Overriding methods

To override a method, we just add a method to the subclass's prototype having the same name as the superclass method:

JavaScript's prototypal inheritance also allows you to override methods on a per-instance basis, rather than per-class (although readers familiar with Java-style class models may find this surprising).

To invoke the superclass's implementation of an overridden method (the equivalent of the Java super keyword), you need to explicitly call it using SuperConstructor.prototype.methodName.call(this);:

While the code may appear correct, in many JS runtimes map[key] will return a reference to the map's prototype object when key equals the nonstandard property name __proto__. This will again give false positives. Rather than try to work around the __proto__ special case, it's best to avoid the [] operator entirely and use hasOwnProperty.

Writing an event emitter

Use the orion/EventTarget mixin to inject event behavior into an object. After calling attach(), your object implements the EventTarget DOM3 interface, and can dispatch events to listeners.

URLs

Orion provides a shim for the W3C URL API. Load the shim in your module, and then call the window.URL constructor. You should always use the URL methods, rather than concatenate and encode strings by yourself.

Consider also using the orion/URITemplate module, which implements the URI Template spec.

Services

The DOM location of service objects is not defined. All services must be accessed via the service registry using the service's symbolic id. While concrete service implementations may be found in the DOM, such object names are not API and are subject to change at any time. Service symbolic ids follow the Reverse DNS naming convention (like Java packages).

JSON

Server requests and responses are represented by default as JSON objects. Object member names use title case ("Name", "ChildrenLocation", etc).

JS Documentation

All JavaScript API uses JSDoc syntax. Orion code is written as self-contained AMD modules that don't expose global objects. So rather than tagging the actual objects with documentation, we tend to use JSDoc tags to construct virtual "classes" corresponding to a module's exported API. These virtual tags can appear almost anywhere in the source code, but it's best to keep them close to the functions that they represent.

A detailed description of what this class, function, or field does. The first sentence will be used as a one-line summary of the class constructor. If @description is not given explicitly, the header of the comment is used.

Documenting a class

JSDoc doesn't distinguish between class documentation and constructor documentation: they both go into a single comment block. So to document a class, we have a comment containing @name, @class, and @description tags, plus all the normal method tags (@param and so on).

Methods

Because JavaScript's prototypal inheritance doesn't quite fit the class-oriented model of JSDoc, there's a few different approaches for documenting methods, depending on how your "class" is built. The general pattern for a method uses the tags:

Prototype method (mixin lends)

This is for when your class mixes in (or directly uses) an object literal for its prototype. We tag the object with @lends, causing JSDoc to add all the literal's fields into the class prototype. Our method docs can then omit the @function and @name tags, because JSDoc already knows the containing class and the type of member.

function ServiceTracker() {
// ...
}
ServiceTracker.prototype = /** @lends orion.MyClass.prototype */ {
/**
* Called to customize a service object being added to this ServiceTracker.
* @param {orion.serviceregistry.ServiceReference} serviceRef The reference to the service being added.
* @returns {Object} The service object to be tracked for the given service reference.
*/
addingService: function(serviceRef) {
// ...
}
//, Additional prototype methods can go here.
};

Prototype method (assignment)

When assigning methods directly to our class's prototype, JSDoc falls over somewhat, and can't infer the containment or the member type. So we need to explicitly place each method into the class using @name, and function-ify it with @function:

function ServiceTracker() {
}
/**
* Called to customize a service object being added to this ServiceTracker.
* @name orion.ServiceTracker#addingService
* @function
* @param {orion.serviceregistry.ServiceReference} serviceRef The reference to the service being added.
* @returns {Object} The service object to be tracked for the given service reference.
*/
ServiceTracker.prototype.addingService = function(serviceRef) {
// ...
};

Static methods

To indicate that a method is static, make it a member of the class itself, rather than the class's prototype:

Types

One helpful feature of JSDoc is types, which can appear inside the curly braces of a @param or @return tag, and a few other places as well. When the JSDoc parser recognizes a reference to a type, it turns it into a clickable hyperlink in the HTML documentation, which is very nice.

A type can be a fully-qualified class name, or a global JavaScript object like Boolean, String, Function, etc. The Orion source generally uses the capitalized object wrapper names to refer to primitive types: for example we say String rather than string, Boolean rather than boolean, and so on.

JSDoc also understands array types: append [] after the name of any type to indicate that it's an array.

/**
* @param {orion.Promise[]} promises
*/

To indicate that a param or return type takes one of a set of types, join the types with a |:

/**
* @param {String|Element} elementOrDomId
*/

When a type can be "anything", we represent it as {Object}.

Fields

JSLint

While most validation problems raised by JSLint are helpful, there are some situations where they need to be ignored. In these cases, add a /*jslint ... */ comment block near the top of your code that turns off the problems. A sample jslint block might look like:

/*jslint forin:true regexp:false sub:true*/

Here's a list of common warnings and how to deal with them:

["foo"] is better written in dot notation.

This warning is raised when code uses the [] operator to access a constant property name. It's good practice to use the . operator instead. When changing the code is unfeasible (for example, when dealing with output from the Orion string externalization plugin), use sub:true to disable this warning.

Bad line breaking before {something}

Use laxbreak:true to disable this warning. Be very careful breaking around a return statement, however: JavaScript's semicolon insertion can produce unexpected results.

Insecure '^'.

This warning is raised on regular expressions that use a negated character set like [^A-Z]. Use regexp:false to disable the warning.

The body of a for in should be wrapped in an if statement to filter unwanted properties from the prototype

While this is generally good advice, sometimes an unfiltered loop is desirable. Use forin:true to disable this warning.

Statement body should be inside '{ }' braces.

JSLint raises this warning when you write a block-style statement (like if, else, for, while) without enclosing the statements inside the block in curly braces { }. There's no way to disable this warning, so it's best to just add the curly braces and carry on.

'{variable}' is already defined.

This warning is raised when you define the same variable more than once within a function. Usually this results from a misunderstanding of JavaScript's scoping rules. In JavaScript, var is scoped to the enclosing function, not the enclosing block. When two blocks define the same variable, it is redundant and may mislead readers as to the underlying language semantics. To eliminate this warning (and make your code clearer), move the variable definition outside the blocks.

It's OK to define a variable inside a block if the variable is not referenced anywhere else in the function.

HTML

None of the HTML in Orion is API. The existence and contents of any HTML file is subject to change at any time. If you see something in Orion's HTML files that you need in your application, make your own copy.

HTML Fragments and Templates

When writing a visual component, it's often convenient to define a fragment of HTML that serves as the component's template. There are several ways to go about this. This section discusses when you might want to use the different approaches, and what our long term direction is.

Where is the fragment defined?

A fragment is a little chunk of HTML that describes a component. There are a few choices in the mechanics of where a fragment is defined.

A fragment could be defined in js code as a string. Consider this snippet from the dialog prototype:

An advantage of this approach when using Orion to edit fragments is keeping the fragment close to the JavaScript code that is manipulating it or making assumptions about its structure. This is, of course, a tooling issue (not having split editors, or popping up references, etc.) The disadvantage is the noise created by concatenation, $NON-NLS markings, etc. This kind of code also tempts the developer to directly concatenate NLS message strings into the content, and that is a security risk (described later).

A fragment can be defined in an HTML file that is brought into the JavaScript module via a requirejs text! module. For example, the common page footer is defined in a footer.html file like this:

A fragment can also be defined inside a template element. Orion provides a shim for the draft HTML Templates API that lets you define template elements. Templates are a promising approach for the following reasons:

if you use the fragment many times on a page, using a template means it will be parsed only once.

once parsed, you can make common, dynamic modifications to the template (binding variable values, etc.) only once.

the DOM structure behind a template is not associated with the document until a node is actually cloned. This means that if the template references network resources (such as an image URL), there will be no attempt to download the image until the template is actually cloned into a node and placed in the document.

If we used a template for the footer fragment, it would look like this instead. (Using a template for a footer that appears once is not necessarily a good idea, but this is shown to illustrate the difference in approach:)

The example above assumes that we have a requirejs plugin for parsing html files and building a template element. (Bug 395402). Until we have such a plugin, the template would have to be marked up in the page itself.

Inserting text fragments

As mentioned above, a template element is preferred for fragments repeated many times, or to delay/reduce the network traffic associated with associating a fragment with a document. However, our tooling for letting library modules bring in templates is not complete here. If you are using text fragments in library modules, or you have a "one-off" fragment, it is reasonable to insert the fragment into the DOM without using a template element. Suppose you have a text fragment you want to insert into the document. (You could have created this text fragment in the JavaScript as a string or imported as a text!myFragment module. It doesn't matter.)

To get it into the document you have several approaches:

innerHTML

If you have a node that is exclusive to the fragment, you can use the innerHTML of the node. The original footer example showed this.

Of course, if there were any other nodes inside the footer DOM node, they would be removed.

createContextualFragment

Another approach, useful when you are adding a fragment to a parent and don't want to remove other child nodes, is to create a contextual fragment and then add it into the DOM as you would any other node. For example, this code adds a banner fragment as the first child of the document body.

Security and Data Binding

Often, you'll want to bind some data to a fragment. For example, you might want to describe some text using its i18n/NLS message key name, which comes from a plug-in. Or perhaps the text in the template depends on some JSON property on the server. Regardless of how you created your fragment, you'll need to ensure that these strings are not bound directly as text in a fragment. They should be inserted as text nodes in the DOM. This restriction is necessary so that plugins or other external sources cannot insert arbitrary HTML into the page.

Do not concatenate variable strings into a fragment and insert into the document. Instead, a data binding approach should be used to refer to the values by their key. Strings can be bound to a fragment using the processTextNodes function in 'orion/webui/littlelib'. This utility allows you to refer to the strings in your template using variables, and DOM API will be used later to bind your string to the text node in the HTML. You may have noticed in the Orion footer example, we use ${variable} syntax in the markup. The user of such a fragment is responsible for providing the correct data binding object for processing the DOM elements.

This data binding approach can be used for any object, not just NLS message objects. When the DOM tree text nodes are processed, any nodes that have the ${variable} syntax will be considered to describe a property name. The text nodes containing the variables will be replaced with nodes containing matching property value found in the bound object. If no matching property is found, the original text remains.

CSS

We use the Orion editor to author .css files. Orion provides a built-in CSSLint validator which flags potential problems in your stylesheets.

CSS file structure

For each Orion page {page}.html, there is generally an associated {page}.css file in the same folder. The page CSS is for that page only, and should not be reused. Any reusable styling for common visual components should go in the bundles/org.eclipse.orion.client.ui/web/css/ folder.

Any stylesheets required by your page CSS should be loaded using @import. These @imports can be inlined by a CSS optimizer like RequireJS's. Do not @import external stylesheets (http://...), as those cannot be inlined.

Style tips

Use DOM structure selectors with caution

CSS provides a number of powerful selectors that act upon the DOM structure, like the type, descendent, and child selectors.

While these can be helpful, their overuse produces a page whose style is brittle and tightly coupled to the DOM structure, such that simple refactorings (adding a wrapper DIV around child elements, for example) completely break the page.

✘ A rule with many DOM selectors is brittle:

.mytable > div > div > label > span {
font-weight: bold;
}

✔ Something like this is better:

.mytable span.emphasis {
font-weight: bold;
}

Don't use unqualified tag selectors

The type selector matches any element with the given HTML tag name. In complex pages, these are prone to matching too much. They also hinder refactoring, as your stylesheet cannot safely be made reusable, and a reader of either the HTML or CSS has a difficult time determining just which elements you intend to match. Instead, consider a class selector.

✘ Don't use selectors that match an entire class name:

div {
background-color: red;
}

✔ Instead, create a class selector that targets only the elements you want:

div.myclass {
background-color: red;
}

The html and body elements are exceptions.

Avoid the ID selector

While necessary in the DOM, IDs should be avoided in stylesheets. IDs are the DOM equivalent of singletons, and targeting them prevents your styles from being reused on other elements. IDs should be regarded as an internal property of the HTML (or JavaScript), not an exported symbol to be styled. Instead of an ID, apply a class name to the DOM element you're trying to style, and use a class selector.

✘ Instead of this:

#content-title {
text-shadow: white 0 1px 2px;
}

✔ …Use a class:

.content-title {
text-shadow: white 0 1px 2px;
}

Java

Java code on the server follows the standard Eclipse Naming Conventions. The project short name is 'orion', so all server bundles and packages start with org.eclipse.orion.

Provisional API packages use the x-internal or x-friends manifest attribute, and do not have internal as a segment in the package name. Use of PDE API tools is highly recommended to ensure you are using supported API.

/*******************************************************************************
* Copyright (c) <date> <contributor name> and others.
* All rights reserved. This program and the accompanying materials are made
* available under the terms of the Eclipse Public License v1.0
* (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution
* License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html).
*
* Contributors: <contributor name> - initial API and implementation
******************************************************************************/