LocalFocus Widget API

Build on top of LocalFocus visualisations


localfocusapi.js Source on Github

Version 1.1





Introduction


Users can create visualisations with LocalFocus and embed them via iframes. At LocalFocus we call these iframes widgets. The Widget API is an extra javascript layer for developers to do things like event handling, interacting and manipulating. The Widget API is not a full-blown library to create charts, but helps you to create extra functionalities.

This script, code examples and documentation are licenced under MIT Licence.

Getting started

Download the latest localfocusapi.js and include the script in your webpage:

                    
<script src="path-to-the-script/localfocusapi.js"></script>
                    
                

Append ?api=1 to the widget's links to force widgets to listen to commands:

                    
<iframe class="localfocusvisual" scrolling="no" frameborder="0" style="width:100%;height:550px;overflow:hidden" src="https://localfocus2.appspot.com/551a9626918b3?api=1"></iframe>
                    
                




1. Listen

Use case: create a loading spinner

This example demonstrates a loading spinner. Widgets send signals to your webpage about their current state. This example listens to the "ready" signal with the widgetObject.on() function. It then hides the spinner and fades in the chart.

Tip: also try the "loaded" and "click" events

The code
                    
                

2. Control

Use case: create custom interaction buttons

LocalFocus visualisations can have interactive options. Use the widgetObject.activate() function to activate an item from the dropdown menu. Want to create your own interaction buttons? With the noui=1 parameter you can hide the chart's default dropdown menu.

The code
                    
                

3. Read dataStore

Use case: generate custom interaction buttons

In the previous example we hard-coded the "apple" and "pear" buttons. But what if you created a new widget that also includes "lemons"? It would not add an extra button.

In this example we will generate buttons according to the widget's "dataStore". We will retrieve the dataStore with widgetObject.getDataStore() and loop over the interactive items (in this example the provinces in The Netherlands) to create buttons.

The code
                    
                

4. Write dataStore

Use case: change color scheme to match brand

Sometimes you want to publish the same widget on two sites, but the websites have different color schemes. In this example we changed the color scheme.

How? We retrieved the widget's dataStore with widgetObject.getDataStore(), changed the main color scheme, and pushed the changes with widgetObject.setDataStore().

The code
                    
                


5. Connect

Use case: create a simple dashboard

Let's create a mini dashboard. You can force widgets to listen to each other with the dashboard=master and dashboard=slave parameters. A click on the map will select that municipality in the pie chart. A bonus: with the dashboard=master set you can catch click events. You could use this to change titles and texts or to create your own pop-ups.

The code
                    
                




In depth


Link parameters

You can (and must) append parameters to the iframe links:

api=1 (required! This activates the Widget API) It forces the widget to listen to API commands.
noui=1 Disable the widget's default interaction panel. Now you can create your custom control panel.
wait=1 The widget loads all resources (scripts, DataStore and fonts) and then waits for your call. It will only generate the chart when you resume withwidgetObject.resume(). This is convenient when you want to manipulate the DataStore before the chart is painted. This prevents painting twice.
dashboard=master Widget is master. The widget catches click events. You can listen to these events with widgetObject.on("click"). Master widgets also activate interactive items in slave widgets.
dashboard=slave Widgets is slave. The widget listens to click events in master widgets.




The LocalFocusAPI Object

With the LocalFocusAPI you can select iframes that contain LocalFocus widgets. It will return one or more widgetObjects.

LocalFocusAPI.select(selector)

Select one widget that you want to control. Returns a convenient widgetObject.

Arguments

  • selector: element or string. When string, it is a string containing one or more CSS selectors separated by commas. It returns only the first matched element wrapped with a new widgetObject.

Returns

A new object widgetObject

                            
// Select first iframe and activate '2015'
LocalFocusAPI.select('iframe').activate('2015');

// Select by iframe element and activate '2015'
var element = document.getElementById('#mywidget');
LocalFocusAPI.select(element).activate('2015');
                            
                        

LocalFocusAPI.selectAll(selector,handler)

Select multiple widgets that you want to control.

Arguments

  • selector: string. Containing one or more CSS selectors separated by commas.
  • handler: function. Each matched element is wrapped with a new widgetObject and is passed as this

Returns

Null

                            
LocalFocusAPI.selectAll('.localfocusvisual',function(){
    this.activate(label);
});
                            
                        

LocalFocusAPI.allowOrigin(origin)

When you use this function, LocalFocusAPI will only listen to widgets from allowed origins.

Arguments

  • origin: string. An allowed origin.

Returns

Self

                            
LocalFocusAPI.allowOrigin('https://localfocus2.appspot.com');
                            
                        

LocalFocusAPI.oldBrowser()

Run to check for an old browser.

Arguments

None

Returns

Boolean. True when it is an old browser.

                            
if(LocalFocusAPI.oldBrowser()){
    // Do something to fall back on
} else {
    // Do something nice with the API
}
                            
                        




A widgetObject Object

Commands specific widgets using the widgetObject object. LocalFocusAPI passes you these objects with its select and selectAll method.

widgetObject.on(event, handler)

Catch events that this widget emits. The event "loaded" is emitted when the widget finishes loading scripts, DataStore and fonts. "ready" is emitted when it finishes painting the chart. "click" is emitted by widgets with the dashboard=master parameter when a chart element is clicked by a user.

Arguments

  • event: string. It can be "loaded", "ready" or "click".
  • handler: function. In the case of "click", the clicked item will be passed as the first argument. In all cases, the current widgetObject will be passed as this

Returns

Current widgetObject

                            
// Get a widgetObject
var widgetObject = LocalFocusAPI.select("iframe");

// Wait for a widget to be loaded and activate "2014"
widgetObject.on('loaded',function(){
    this.activate("2014");
});

// Wait for widget to be ready and activate "2015"
widgetObject.on('ready',function(){
    this.activate("2015");
});

// Watch for user click events
widgetObject.on('click',function(item){
    console.log(item);
});
                            
                        

widgetObject.activate(label)

Charts can have interactive features. This is a dropdown with a list of labels which users can select. To activate one of the labels using the API, use this method.

Arguments

  • label: string. Must correspond with the label of the interactive feature, case-sensitive.

Returns

Current widgetObject

                            
// Get a widgetObject
var widgetObject = LocalFocusAPI.select("iframe");

// Wait for a widget to be loaded and activate "2014"
widgetObject.on('loaded',function(){
    this.activate("2014");
});
                            
                        

widgetObject.getDataStore(handler)

widgetObject.getDataStore(options, handler)

Get the DataStore from a widget.

Arguments

  • handler: function. The DataStore will be passed as the first argument. The current widgetObject will be passed as this
  • options (optional): object. Set {'records': true} to include records.

Returns

Current widgetObject

                            
// Get a widgetObject
var widgetObject = LocalFocusAPI.select("iframe");

// Wait for widget to be loaded 
widgetObject.on('loaded',function(){
    // Get DataStore from this widget
    this.getDataStore(function(DataStore){
        // Show me the DataStore
        console.log(DataStore);
    });

    this.getDataStore({records: true}, function(DataStore){
        // Show me the DataStore, with records
        console.log(DataStore);
    });
});
                            
                        

widgetObject.setDataStore(DataStore)

Set the DataStore to a widget.

Arguments

  • DataStore: object. This is the DataStore you recieved and manipulated from widgetObject.getDataStore().

Returns

Current widgetObject

                            
// Get a widgetObject
var widgetObject = LocalFocusAPI.select("iframe");

// Wait for widget to be loaded 
widgetObject.on('loaded',function(){
    // Get DataStore from this widget
    this.getDataStore(function(DataStore){
        // Change chart type to "pie"
        DataStore.settings.activeChart = "pie";
        this.setDataStore(DataStore);
    });
});
                            
                        

widgetObject.getDownload(format, callback)

Get a link to a downloadable image or spreadsheet. This can only be used on widget that are loaded and ready.

Arguments

  • format: string. Use 'png', 'pdf' or 'csv'
  • callback: function. An object will be passed as the first argument, with a hyperlink to the image or spreadsheet. The current widgetObject will be passed as this

Returns

Current widgetObject

                            
// Get a widgetObject
var widgetObject = LocalFocusAPI.select("iframe");

// Wait for widget to be ready 
widgetObject.on('ready',function(){
    // Generate a PNG image
    this.getDownload('png', function(data){
        // Show me the hyperlink
        console.log(data.url);
        // Open link
        window.open(data.url, '_blank');
    });
});
                            
                        

widgetObject.element()

Get the iframe element.

Arguments

None

Returns

iframe element

                            
// Get a widgetObject
var widgetObject = LocalFocusAPI.select("iframe");

// Get the iframe element
widgetObject.element();
                            
                        

widgetObject.wait()

Stop repainting the chart. This is usefull when you want to manipulate things without repainting the chart.

Arguments

None

Returns

Current widgetObject

                            
// Get a widgetObject
var widgetObject = LocalFocusAPI.select("iframe");

// Stop repainting the chart
widgetObject.wait();
                            
                        

widgetObject.resume()

Start repainting the chart.

Arguments

None

Returns

Current widgetObject

                            
// Get a widgetObject
var widgetObject = LocalFocusAPI.select("iframe");

// Start repainting the chart
widgetObject.resume();
                            
                        




A DataStore Object

Each widget has an internal DataStore. Widgets respond to changes in this DataStore. Use widgetObject.getDataStore(callback) and widgetObject.setDataStore(DataStore) to get and set DataStores.

DataStore.groups

This is an array of objects. It represents the dataset dimensions.

It is safe and sometimes usefull to change array order. The order defines how each dimension is used in a chart. For example, the first group (DataStore.groups[0]) is the legend in column charts and line charts.

Read-only properties:

group.key: Number. The unique key for this group.

Writable properties:

group.label: String. The label for this group.

                            
// Change label of a dimension
DataStore.groups[0].label = "Locations";

// Transpose (swap legend and horizontal axis)
var tmp = DataStore.groups[0];
DataStore.groups[0] = DataStore.groups[1];
DataStore.groups[1] = tmp;

                            
                        

DataStore.items

This is an array of objects. It represents the dataset items. Each item belongs to a group.

Read-only properties:

item.key: Number. A unique key for this item.

item.group: Number. Item belongs to group when: group.key = item.group.

Writable properties:

item.label: String. The label for this item.

item.color: String. A hexadecimal color.

item.active: Boolean. Activate or deactivate an item. Warning: do not activate items that where originally deactivated.

                            
// Get all legend items
var legendGroup = DataStore.groups[0];
for (var i = 0; i < DataStore.items.length; i++) {
    var item = DataStore.items[i];
    if(item.group === legendGroup.key && item.active){
        console.log('Visible in the legend', item.label);
    }
};

// Change item color to grey
DataStore.items[0].color = "#444";

                            
                        

DataStore.settings

This is an objects. It holds various settings.

Writable properties:

settings.activeChart: String. The current chart type. Possible values: bar, column, stacked, line, pie, polygon, grid, map.

settings.title: String. Widget's title

settings.description: String. Widget's description

                            
// Change chart type to "pie"
DataStore.settings.activeChart = "pie";
                            
                        

DataStore.styling

This is an objects. It holds various styling settings.

Writable properties:

All properties are writable. Go and experiment :)

                            
// Change background color
DataStore.styling.svg.style.background.fill = "#FF6666";
// Change domain background color
DataStore.styling.domain.style.fill = "#050202";
// Change general font color
DataStore.styling.svg.style.root.fill = "#FFFFFF";