Back

Web Sketchpad sQuery API

Version 4.8.0

 

Web Sketchpad sQuery API

Contents

Introduction

The sQuery API is a flexible client-side javascript API that permits Web Sketchpad host pages to control the behavior and appearance of Web Sketchpad sketches. It is designed to be reminiscent of the popular javascript library, jquery.

SQuery provides a selector-based query facility. JQuery's query facility operates on the HTML DOM. sQuery's operates on the Web Sketchpad constraint hierarchy. Selectors make it possible to precisely control Web Sketchpad without requiring detailed knowledge of the sketch construction. A number of operations may be invoked on selection results. These operations may be chained.

SQuery has an event registration mechanism. This permits calling pages to choose to be notified of important user interactions with the sketch.

Finally, SQuery provides a set of global operations. These do not require selectors. In fact, selectors are ignored. They concern the entire sketch, not any particular sketch object.

Document Object

The Document object is the top-level object that manages the sketch canvas, and all pages within.

getSketch()
Returns the current sketch being displayed.
sQuery
This property is the sQuery selector for the current page. Every time there is a page switch this property updates to point to the selector for the new page.

sQuery Selectors

The sQuery entry point is a property of the Document object. Generally, the sQuery method is invoked with a selector, and the sQuery object that is returned includes a selection set, the GObjects in the current sketch that satisfy the query. The sQuery object includes all the methods to operate on the selection set as if it were a Javascript array like any other javascript array. In addition, the sQuery object includes a number of additional methods to facilitate operating on elements of the selection set.

If you have loaded your sketchpad document with WSP Runner, then the document object can be accessed in the StartCurrentPage.WSP Document Event API, or in the data-document DOM attribute.

sQuery selectors have a simplified css-style selector syntax. Selectors are either the global selector or kind selector, modified by any number of class, attribute, or id selection modifiers. Modifiers constrain the set of selected objects. For example, document.sQuery('Point[color="rgb(255,0,0)"]) selects all the red points in the sketch. If the selector is missing, like CSS, the global selector is assumed.

The Global Selector
The global selector selects all the gobjects in the sketch. As with CSS, the global selecter is a single asterisk ("*"). For example, document.sQuery("*"); selects all GObjects.
The Label Selection Modifier
The label selection modifer selects all objects with a given label. The call document.sQuery('[label="Drag Me"]'); will select object(s) with the label "Drag Me". The label must be an exact match; there is no provision for wildcards or partial matches. (The label selection modifier is an instance of the Attribute Selection Modifier described below.)
The ID Selection Modifier
Every GObject has a unique ID in Web Sketchpad. This modifier constrains the selection to the GObject matching the given ID. As with CSS, id selectors are distinguished by an initial hash character. For example, document.sQuery('#13'); selects the GObject with the id of '13', if any. As in this example, GObject ID values generated by the WSP Exporter are strings of digits, but WSP documents from other sources may use alphabetic or alphanumeric strings. (No matter the source, each GObject's ID must be unique.)
The Kind Selector
All gobjects have a "kind". Kinds classify GObjects by their geometric nature. Kind selectors are simply the name of the kind. Case is significant. For a list of kinds, see Web Sketchpad Exchange Format. For example, document.sQuery('Point'); selects all points in the sketch.
The Class Selection Modifier
A sketch author can assign a class property to any gobject. This selection modifier constrains the selection to the gobjects that have the name class assigned. As with CSS, class selectors are distinguished by an initial period character. For example, document.sQuery('.myclass'); selects all gobjects in the sketch with the 'myClass' class. A class property may name multiple classes, separated by spaces. Please note that the ability to assign a class is not yet supported through Desktop Sketchpad. Classes need to be assigned by editing the JSON exchange formatted documents.
The Attribute Selection Modifier
The attribute selection modifer constrains the selection set based on the presence of an object property with a given value. Again, the syntax follows CSS, but is at this time, quite limited as compared to css capabilities. The WSP attribute selectors can only compare for strict equality based on string representation. Attribute names must match the name of a model property or a style sub-property, dotted syntax is understood. For example, given a Point object, the 'color' attribute will refer to the style color property. So will the 'style.color' property. The call, document.sQuery('[color="red"]'); will select objects defined to be 'red' in color, but not those defined with their color as 'rgb(255,0,0)'.
Selector Grouping
Any selectors may be combined in a selection string. As with CSS selectors, they are selected by commas. The resulting set is the union of the selected sets. For example, document.sQuery('#A,Straight'); selects the GObject identified as "A" and all objects of the "Straight" kind.

GObject Manipulation

This section describes operations that can be performed on selection lists returned by the sQuery() call. Generally these operations return an sQuery selection, so the operations can be chained.

Generally, any attribute documented in the file format can be accessed. It is in general only safe to change GObject style attributes. In addition, certain other attributes are accessible. More convienient API's are planned, but meanwhile:

attr(name)
Returns the value of the named attribute for the first member of the selection set. For example, document.sQuery("#A").attr("color") will return the color of the GObject identified as "A".
attr(name, value)
Sets the named attribute to the value for each member of the selection set. For example, document.sQuery("Point").attr("color", "white") will set the color of all points to white.
each(fn)
Calls a function on each member of the selection set. The function will be passed the index of the gobject in the set and the gobject itself, and "this" will be set to the gobject. For example, document.sQuery("Circle").each( function(ix, gobj){ GSP.log(gobj.id); }); will log the gobject ids of the members of the selection set.
hide()
Hides each member of the selection set. For example, document.sQuery("Straight").hide();
hideLabel()
Hides the label of each member of the selection set. For example, document.sQuery("Point").hideLabel();
log()
Writes a log entry describing the state of each member of the selection set. The log entry takes the form of a JSON object. For example, document.sQuery("#A,#B").log();
parents()
Returns a new selection set containing the parents of the members of the current selection set. For example, document.sQuery("#square1").parents().hide(); will hide all the parents of the object, square1.
press()
Toggles the state of any action buttons in the selection set. In active buttons are activated. Active buttons are halted. For example, document.sQuery("#btn1").press();
show()
Makes visible each member of the selection set. For example, document.sQuery("Straight").show();
showLabel()
Makes the label visible each member of the selection set if there is a label defined for GObject kind. For example, document.sQuery("Polygon").showLabel();
value()
Returns the geometric value of the first element of the matched set. The type of the value depends on the nature of the element. Parameters have a value which is a Number. Points have a value which is an {'x': x, 'y': y} object. document.sQuery("#1").value();
value(v)
Set the geometric value of each element of the matched set. The type of the v depends on the nature of the element. Parameters require a value which is a Number. Points require a value which is an {'x': x, 'y': y} object. document.sQuery("#1").value(1.3);

sQuery Events

Event Object

Each Event generated by sQuery has a standard set of properties.

type
A string value representing the type of event.
timeStamp
Time value of Event creation. Useful mainly for debugging.
targetMap
A map where the keys are the full set of target id's that handler is interested in. The values are [true|false] depending on whether the given key id did in fact trigger the event.
target
When the targetMap contains exactly one id, the target field will be set to the GObject in the sketch with that id.

Event Types

update
An update event is sent whenever the defining geometry of an object is recalculated, either because of direct manipulation (e.g. a user drag), or because of an update to the objects that define the given objects geometry (the parents of the object). Note that this is not the same as a change to the objects geometry: for example, if a point C on the segment AB is coincident to B, and you drag A, then C does not change position - but an update event for C will still be sent.

Event Handler Attachment

Selection lists returned by the sQuery() call can be monitored for events. Event handlers can be bound on each object of the list. Additionally, one event handler can be bound to the group of objects taken as a whole. In this case, the event object will contain information about which specific GObject's triggered the event.

on(events, handler(eventObject))
events
One or more space-separated event types
handler(eventObject)
A function that is called when the event is triggered.
For example, document.sQuery("#1, #2").on("update", function(e) { alert("A GObject was updated!")}); will produce an alert when the geometry of #1 changes, and an alert when the geometry of #2 changes.
off(events, handler(eventObject))
events
One or more space-separated event types
handler(eventObject)
A function that is called when the event is triggered.
The events and their handler must be the same as those previously passed to on().
onGroup(events, handler(eventObject))
events
One or more space-separated event types
handler(eventObject)
A function that is called when the event is triggered.
For example, document.sQuery("#1, #2").onGroup("update", function(e) { alert("One or more GOBjects where updated!")}); will produce one alert when either of #1 or #2 changes.
offGroup(events, handler(eventObject))
events
One or more space-separated event types
handler(eventObject)
A function that is called when the event is triggered.
The events and their handler must be the same as those previously passed to onGroup().

Global Methods

The sQuery interface can be used for certain global operations affecting the sketch as a whole.

stopMotions()
Stops any animations or motions that may be active. For example: document.sQuery().stopMotions();
eraseTraces()
Erase any traces that may have been drawn. For example: document.sQuery().eraseTraces();
getResource(iMapName, iKey)
Returns the specified resource. For example: document.sQuery().getResource('pictures', 0);
prefs()
Returns the preferences object. This object contains global parameters governing the appearance or behavior of the sketch, including global property defaults. This object should be considered read-only.
getSketchJSON()
Returns a description of the state of the current sketch as a string in the JSON-based Web Sketchpad Interchange Format. This description will differ from the JSON used to initialize the sketch's original instance in that it will reflect any subsequent user interactions with the sketch. The returned string may be stored and used to instantiate a new Web Sketchpad instance at some later time [1]. The objects in this new instance will correspond in position and appear to those of the current sketch at the moment the method was invoked.
For example, jsonDoc = document.sQuery().getSketchJSON(); The JSON string referenced by jsonDoc may now be saved to a server or other persistent storage. To recreate the sketch display in an html element with id "my-sketch" on this or another web page, load the saved json string as jsonDoc and instantiate the sketch using the 'sourceDocument' protocol: var el = $('#my-sketch');
el.data ('sourceDocument', jsonDoc);
el.WSP("loadSketch");
el.removeData ('sourceDocument'); // jsonDoc is no longer needed

Footnotes

[1] When using a pre-release version of Web Sketchpad be aware the Interchange Format is subject to change, and that long-term compatibility of stored pre-release-format data is not guaranteed.