Class: UWA.Widget

UWA/Widget. UWA.Widget

new UWA.Widget()

The Widget object provides abstract methods to create and manipulate UWA application instances, this object is typically instanciated by UWA.Environment as the widget variable in a widget execution scope.

Note on events dispatching: Events will start to be dispatched to the widget only after the "onLoad" event has being dispatched first.

Available Events
Event Description
onLoad Triggered when the widget is launched.
onRefresh Triggered when the widget is refreshed (manually or programmatically).
onResize Triggered when the widget is resized (manually or programmatically).
onKeyboardAction Triggered when a key is pressed within the widget's area.
onSearch Triggered when a search is performed from within the platform.
onResetSearch Triggered when a search is reseted from within the platform.
onUpdateIcon Triggered when the widget's icon is modified.
onUpdateTitle Triggered when the widget's title is modified.
onUpdateCounter Triggered when the widget's counter is modified.
onUpdatePreferences Triggered when a widget's preference is added.
onEdit Triggered when edition of preferences begin.
endEdit Triggered when edition of preferences ending.
onOpenURL Open an url into a new environment browser window.
Properties:
Name Type Description
id String

Unique identifier of the widget. The value depends on the execution environment: the Environment registration handler sets this property.

environment UWA.Environment

Reference to the execution environment. The Environment registration handler sets this property. Instance of the Environment class.

title String

Widget's title. The title of the widget. It is set by the <setTitle> method.

icon String

Widget's icon url. The icon of the widget. It is set by the <setIcon> method.

body UWA.Element

Widget's body. The main HTML element of the widget. Value is null until the <widget> is fully registered in the Environment. Should not be used before <launch> or <onLoad> are fired.

data Object

Stores widget's data. This property can be modified by the <setValue> method, and accessed by the <getValue> method.

events Object

Stores widget's events.

plugins Array

Stores widget's plugins. The array is initially empty. It is initialised by the <setPlugins> method.

preferences Array.<Object>

widget's preferences. The array is initially empty. It is initialised by the <setPreferences> method.

metas Object

Stores widget's metas. The object is initially empty. It is initialised by the <setMetas> method.

elements Object

Instances of UI <UWA.Element> of the widget.

lang String

The preferred language as defined by the Environment (e.g "en" or "en_US").

locale String

The preferred locale as defined by the Environment (e.g "us" or "fr").

dir String

The preferred language direction as defined by the Environment. This property is set by the <setDir> method.

readOnly Boolean

true if the widget is currently read only for the viewer. Default to false.

isEdit Boolean

true if the widget is currently display the preference form.

counter Number | Boolean

The count of unread items in the widget. This property is set by the <setCounter> method.

counterType String

The count type of unread items in the widget. This property is set by the <setCounter> method.

Mixes In

  • UWA.Class.Options
  • UWA.Class.Timed
  • UWA.Class.Events
  • UWA.Class.Debug

Index

Methods

onLoad()

Triggered when the widget is launched. This event MUST be declared in any widget, in order for any of the widget's JavaScript code to be executed. Implementations MUST trigger this event once the application is done loading.

onRefresh()

Triggered when the widget is refreshed (manually or programmatically). Implementations SHOULD trigger this event when preferences values are updated. If this event is not declared, the <UWA.Widget.onLoad> event will be triggered instead.

onResize()

Triggered when the widget is resized (manually or programmatically). Implementations SHOULD trigger this event when the size of the application container is resized (for instance, when the user resizes the containing column, or changes the number of columns on the page).

onKeyboardAction(key)

Triggered when a key is pressed within the widget's area. Implementations may first require the user to click within the widget's area in order to limit the interaction to that widget only. Implementations SHOULD pass the key-code as first argument of the event.

Parameters
Name Type Description
key String

The pressed key's code

onSearch(query)

Triggered when a search is performed from within the platform.

Implementing platforms that feature a search form MAY trigger this event, with the search query as first argument, so that the widget may use it to further perform a search with its own data, if such a thing is possible.

Parameters
Name Type Description
query String

The search query

onResetSearch()

Triggered when a search is reseted from within the platform.

Implementing platforms that feature a search form MAY trigger this event, so that the widget may use it to further reset the last search, if such a thing is possible.

onUpdateIcon(url)

Triggered when the widget's icon is modified. Implementations MUST trigger it when widget.setIcon() is used. Implementations MAY also trigger for internal reasons.

Parameters
Name Type Description
url String

The url of the icon. The URL should include the protocol (http://)

onUpdateTitle(title)

Triggered when the widget's title is modified. Implementations MUST trigger it when widget.setTitle() is used. Implementations MAY also trigger for internal reasons.

Parameters
Name Type Description
title String

The title of the widget. Can contain HTML code

onUpdateCounter(count, type)

Triggered when the widget's counter is modified. Implementations MUST trigger it when widget.setCounter() is used. Implementations MAY also trigger for internal reasons.

Parameters
Name Type Argument Description
count Number | Boolean | String

The number of results or status for the current search/unread items

type String <optional>

The number of results type (e.g 'search').

onUpdatePreferences(preferences)

Triggered when a widget's preference is added. Implementations SHOULD trigger this event when a preferences is added (manually or programmatically).

Parameters
Name Type Description
preferences Array

An Array of preferences in their JSON serialization

onEdit()

Triggered when edition of preferences begin.

endEdit()

Triggered when edition of preferences ending.

onOpenURL(url) → {Boolean}

Open an url into a new environment browser window.

Behavior differ between execution environments: - open the page in an iframe on the same screen - open the page in a new window/tab - open the page in a new browser window (desktop widgets)

Parameters
Name Type Description
url String

The url to open in a new window

Returns

true if it successfully opens the url (according to the subprotocol)

Notes: Implementation can differ between environments.

Type
Boolean

onViewRequest(view)

Try to change the widget view. This event can be triggered from the widget by <UWA.Widget.requestView>.

Parameters
Name Type Description
view Object

view parameters. It needs to have at least one field 'type' indicating the view name. Other properties are optional and passed to the view.

onViewChange(view)

Triggered when the view changed.

Parameters
Name Type Description
view Object

view parameters, like for <onViewRequest>

onViewError(view)

Triggered when the view fails to change.

Parameters
Name Type Description
view Object

view parameters, like for <onViewRequest>, with one additional parameter 'error' representing the error message.

launch(data, readOnly) → {Boolean}

Launch the widget : call <initPlugins> and <initPreferences> then dispatch <event> "beforeLoad", "onLoad" and "afterLoad".

Internal or advanced use only.

Parameters
Name Type Description
data Object

Widget's data values

readOnly Boolean

Default to false. True if the widget is currently read only for the viewer

Returns

true if launch succeed else false.

Type
Boolean

destroy()

Destroy the elements and its children of widget. Remove all events and remove the elements from the dom. Clear all Delayeds and Periodicals timers.

setOptions(options)

Set options of this instance. Passing an 'events' field will automatically add those events.

Parameters
Name Type Description
options Object

Options hash

setAutoRefresh(delay)

Sets the auto-refresh interval for the widget. The widget must have a "onRefresh" method to work properly.

Example
widget.setAutoRefresh(20); // Set the auto-refresh interval to 20 minutes
Parameters
Name Type Description
delay Number

The refresh delay, in minutes

setCounter(count, type)

Sets the number of results or status for the current search/unread items.

Parameters
Name Type Argument Description
count Integer | Boolean | String

The number of results or status for the current search/unread items

type String <optional>

The number of results type (e.g 'search').

Returns

Nothing, but updates the title with the result count, if greater or equal to zero.

getTitle() → {String}

Get the title of the Widget.

Returns

The title of the widget. HTML tags are stripped.

Type
String

setTitle(title, url) → {String}

Sets the title of the Widget.

Implementation can differ between environments.

Parameters
Name Type Description
title String

The title of the widget. Can contain HTML code

url String

The link of the title.

Returns

New <title> property value.

Example
widget.setTitle('Netvibes Blog');
// OR
widget.setTitle('<a href="http://blog.netvibes.com/">Netvibes Blog</a>');
Type
String

setIcon(url, search) → {String}

Sets the icon for the Widget.

Implementation can differ between environments.

Example
widget.setIcon("http://www.example.com/favicon.ico");
// OR
widget.setIcon("http://www.example.com", `true`);
Parameters
Name Type Description
url String

The url of the icon. The URL should include the protocol (http://)

search Boolean

If true, try to autodiscover the icon for the given url.

Returns

New <icon> property value.

Type
String

setMenu(item)

Add or update a menu item to widget's chrome.

Examples

Add a settings menu item

widget.setMenu(
    name: 'edit/settings',
    icon: 'settings',
    label: 'Settings',
    onExecute: 'onMenuSettings'
);
widget.addEvent('onMenuSettings', function () {
    // Menu item clicked
});

Asynchronous submenu creation

widget.setMenu({
    name: 'edit',
    onShow: 'onShowMenu'
});

widget.setMenu({
    name: 'edit/date',
    label: 'Loading...'
});

widget.addEvent('onShowMenu', function (menu) {
    widget.setMenu({
        name: 'edit/date',
        label: UWADate.strftime(new Date(), '%x')
    });
});
Parameters
Name Type Description
item Object

Menu item descriptor

Properties
Name Type Description
name String

The identifier of the menu item. It can contains a slash to be in a submenu (example: 'edit/preferences').

icon String

An icon name, a character (unicode...) or an image URL

label String

The text displayed on the menu item

className String

A class name to be added to the menu item

getMenu(name) → {Object}

Get a menu item by its name.

Example
var menu = widget.getMenu('options/share');
Parameters
Name Type Description
name String

Menu identifier

Returns

Menu item descriptor.

Type
Object

removeMenu(name)

Remove a menu item by its name.

Example
var menu = widget.removeMenu('options/share');
Parameters
Name Type Description
name String

Menu identifier

setDir(dir) → {String}

The preferred language direction.

Parameters
Name Type Description
dir String

Language direction ('rtl' or 'ltr')

Returns

New <dir> property value.

Type
String
See:

setMetas(metas) → {Object}

Set the metas of the widget.

Internal or advanced use only.

Parameters
Name Type Description
metas Object

Metas hash or a name/value pair

Returns

New <metas> property value.

Type
Object

setBody(content)

Replace the content of the widget body by another.

Content parameter could be:

  • a String, considered as XHTML
  • a DOM Element
  • an Object used to create an DOM element by using the 'tag' field as tag and other fields as properties
  • an Array of Objects used to create multiple DOM elements
Examples
  • Insert an element using Object syntax
widget.setBody({
   tag: 'a',
   href: 'http://www.example.com',
   text: 'My Link',
   styles: {
       color: 'red'
   },
   event: {
      click: function (event) {
           // My Click Handler
           UWA.Event.stop(event);
      }
   }
});

Will rendering:

<a style="color: red;" href="http://www.example.com">My Link</a>
  • Insert elements using Array syntax
widget.setBody([
   {
       tag: 'div',
       'class': 'myHeader'
   },
   {
       tag: 'div',
       'class': 'myContent',
       html: [
           {
               tag: 'a',
               text: 'My Link',
               styles: {
                   color: 'red'
               },
               event: {
                   click: function (event) {
                       // My Click Handler
                       UWA.Event.stop(event);
                  }
               }

           }
       ]
   },
   {
       tag: 'div',
       'class': 'myFooter'
   },
]);

Will rendering:

<div class="myHeader"></div>
<div class="myContent">
   <a>My Link</a>
</div>
<div class="myFooter"></div>
  • Using String considered as XHTML (bad practice)
    widget.setBody('<a href="http://www.example.com">My Link</a>');
Parameters
Name Type Description
content String | Object | Array

The content to set to the widget body

Returns

Nothing.

addBody(content)

Add content to current widget body.

Example
See  method.
Parameters
Name Type Description
content String | Object | Array

The content to add to the widget body. Content parameter could be:

  • a String, considered as XHTML
  • a DOM Element
  • an Object used to create an DOM element by using the 'tag' field as tag and other fields as properties
  • an Array of Objects used to create multiple DOM elements
Returns

Nothing.

getElements(selector) → {Array}

Alias to UWA.Element.getElements on Widget body.

Parameters
Name Type Description
selector String

TODO

Returns

Elements into an Array or an empty Array.

Type
Array

getElement(selector) → {Element}

Alias to <UWA.Element.getElement> on Widget <body>.

Parameters
Name Type Description
selector String

TODO

Returns

Matched Element or undefined if not found.

Type
Element

createElement(tagName, options) → {Element}

Creates a new element according to the provided "tagName":

  • if options is not defined, works like document.createElement(tagName)
  • if options is defined, works like JS frameworks DOM builders (mootools/prototype) - new Element(tagName, options)
Example
var div = widget.createElement('div');
// OR
var input = widget.createElement('input', {
   "type": "submit",
   "value": "Update"
});
Parameters
Name Type Description
tagName String

The HTML tag name of the element to create

options Object

Will be set on the newly-created element using Element#setAttributes

Returns

The created element.

Type
Element

setStyle(style)

Set the stylesheet of the widget with the given CSS rules.

Internal or advanced use only.

Parameters
Name Type Description
style String

The style rule to apply to the widget elements

mutate(url, preferences)

Mutate a widget into another widget.

Parameters
Name Type Description
url String

Widget new url

preferences Object

Widget preferences

getUrl() → {String}

Get current Widget UWA url.

Returns

UWA url of the current widget.

Type
String

addStar()

Star Widget into Environment if available.

getViewportDimensions() → {Object}

Finds the computed width and height of widget possible max height and width and returns them as key/value pairs of an object.

Example
var viewport = widget.getViewportDimensions();
widget.body.setStyles({
   height: viewport.height + 'px',
   width: viewport.width + 'px'
});
Returns

Object with "with, "height" properties.

Type
Object

setPlugins(schema)

Sets plugins schema of the widget. Replaces previous plugins.

Example
widget.setPlugins([
   {"name":"Auth", params: [{"name": "paramName", "value": "paramValue"}]},
   {"name":"GoogleAnalytics", params: [{"name": "paramName", "value": "paramValue"}]},
]);
Parameters
Name Type Description
schema Array

An Array of plugins in their JSON serialization

initPlugins()

Initializes plugins of the widget.

initPreferences()

Initializes preferences of the widget. The method gets values from the environment. If values do not exist in the environment, it sets them to their default values. This method is likely internaly fired by the <launch> method of the Widget.

hasPreferences() → {Boolean}

Check if Widget has visible preferences and not in <readOnly> mode.

Returns

true if has visible preferences.

Type
Boolean

getPreference(name) → {Object}

Get a preference with its name.

Parameters
Name Type Description
name String

The name of the preference

Returns

A preference in its JSON serialization with it's current value.

Example

If you have this preference defined in XML

<widget:preference name="limit" type="range" label="Number of items to display" defaultValue="5" step="1" min="1" max="25" />

You can get its javascript representation with the following code widget.getPreference("limit")

That will return the following JSON Object:

{
   name: "limit",
   type: "range",
   label: "Number of items to display",
   defaultValue: "",
   step: "1",
   min: "1",
   max: "25",
   value: "5"
}
Type
Object

hasPreference() → {Boolean}

Check if Widget has preferences its name.

Returns

true if has preferences that match the given name.

Type
Boolean

addPreference()

Adds a single preference to the existing preferences of the widget. Replace the previous preference if preference of the same name is already defined.

Example
widget.addPreference({
   name: "paging",
   type: "boolean",
   label: "Enable pagination",
   defaultValue: "`false`"
});
Parameters
Type Description
Object

A preference in its JSON serialization.

setPreferences(schema)

Sets preferences schema, replaces previous preferences schema.

Example
widget.setPreferences([
   {name: "paging", type: "boolean", label: "Enable pagination", defaultValue: "`false`"},
   {name: "offset", type: "hidden", defaultValue: "0"}
]);
Parameters
Name Type Description
schema Array

An Array of preferences in their JSON serialization

mergePreferences(schema)

Add preferences to the widget if preferences of the same name are not already defined.

Parameters
Name Type Description
schema Array

An Array of preferences in their JSON serialization

getPreferences() → {Object}

Gets preferences schema of the widget.

Returns

Preferences schema with current values for each preference.

Type
Object

getValue(name) → {Void}

Gets the value of the given preference.

Notes about the returned value:

  • If no default value is provided by the corresponding widget:preference XML tag then this method will return undefined.

  • The type depends on what you have stored inside it.

Parameters
Name Type Description
name String

The name of the preference we want the value of

Returns

The current value of the given preference.

Type
Void

getInt(name) → {Number}

Gets the Integer value of the given preference.

It is particularly advised to use getInt when a preference is of type range.

Parameters
Name Type Description
name String

The name of the preference we want the value of

Returns

The current value of the preference, converted as integer.

Type
Number

getBool(name) → {Boolean}

Gets the Boolean value of the given preference.

It is particularly advised to use getBool when a preference is of type boolean.

Parameters
Name Type Description
name String

The name of the preference we want the value of.

Returns

The current value of the preference, converted as boolean.

Type
Boolean

setValue(name, value) → {String}

Sets the value of the given preference.

Example
widget.setValue("nbItems", 5);
Parameters
Name Type Description
name String

The name of the preference we want to set.

value String

The value of the preference.

Returns

The value of the preference we set.

Type
String

setValues(values)

Sets the values of the given preferences.

Example
widget.setValues({
   'nbItems': 5,
   'title', "MyTitle"
});
Parameters
Name Type Description
values Object

The preferences indexed by name value we want to set.

deleteValue(name)

Delete value of the given preference.

Parameters
Name Type Description
name String

The name of the preference we want the value of

toggleEdit()

Trigger "endEdit" or "onEdit" depending the isEdit state.

dispatchEvent(name, args, bind, dispatched) → {Object}

Executes the listeners method associated with the given event name.

Internal or advanced use only.

Parameters
Name Type Description
name String

The event name (e.g. "onUpdateTitle");

args Array

Array of parameters that should be passed to each listener

bind Object

Context on which listener will be executed (object that should represent the this variable inside listener function)

dispatched Object

Indicate that the environment has dispatched the event already

Returns

Current <UWA.Widget> instance for more fluent interface and calls the listeners associated with the given event name.

Type
Object

addEvent(name, listener, bind, priority) → {Object}

Add a listener associated with the given event name.

Example
// Example to add a listener on the onLoad event:
 widget.addEvent("onLoad", function (eventName) {
      widget.setBody("Widget loaded !");
 });
Parameters
Name Type Description
name String

The event name (e.g. "onUpdateTitle");

listener Function

listener function that will be executed when event is triggered.

bind Object

(optional) Context on which listener will be executed (object that should represent the this variable inside listener function). If left undefined, the context on which listener will be executed will be the one passed to <dispatchEvent>, which defaults to this widget.

priority Number

(optional) The priority level of the listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0)

Returns

Current <UWA.Widget> instance for more fluent interface

Type
Object

addEventOnce(name, listener, bind, priority) → {Object}

Add a listener associated with the given event name. Once the event is fired, the listener will be removed. This is handy for saying "the next time that X happens, do this".

Example
// Example to add a listener on the onLoad event:
 widget.addEvent("onLoad", function (eventName) {
      widget.setBody("Widget loaded !");
 });
Parameters
Name Type Description
name String

The event name (e.g. "onUpdateTitle");

listener Function

listener function that will be executed when event is triggered.

bind Object

(optional) Context on which listener will be executed (object that should represent the this variable inside listener function). If left undefined, the context on which listener will be executed will be the one passed to <dispatchEvent>, which defaults to this widget.

priority Number

(optional) The priority level of the listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0)

Returns

Current <UWA.Widget> instance for more fluent interface

Type
Object

getView() → {Object}

Get the current view parameters.

Example
widget.onResize = function () {
 if (widget.getView().type === 'maximized') {
   resizeLargeLayout();
 } else {
   resizeNormalLayout();
 }
};
Returns

The current view. This is an object with at least the 'type' property indicating the view type. Other properties are the view options.

Type
Object

getAvailableViews()

Parses and return the availableViews meta data. This value indicates which views this widget is handling, so the environment can safely change the widget view to another available view at any time.

Example

Declaring availableViews meta in the widget code

<meta name="availableViews" content='maximized {"chrome": `false`}; fullscreen' />

Implementing a 'maximize' button in the widget header (enviroment side)

var maximizeView = UWA.Array.detect(widget.getAvailableViews(), function (view) {
 return view.type === 'maximized';
});

if (maximizeView) {
 widgetHeader.addContent({
   tag: 'span',
   text: 'maximize',
   events: {
     click: function () {
       environment.dispatchEvent('onViewRequest', maximizeView);
     }
   }
 });
}