Classes

NextSurface API consists of classes which can be divided in categories such as values objects, stateful objects, built-in objects, and abstract objects. Value objects are immutable and safe to share. Stateful objects have mutable state and must be shared carefully (however JavaScript is single threaded so we don't need to worry about concurrency). Built-in objects are singleton and they can't be instantiated, but there is one global instance available. Abstract objects can't be instantiated directly, instead they are created using factory methods.

Data Objects

Color

Color represents a value in the RGBA color space.

PropertyTypeRead-OnlyDescription
redNumberyesValue of red component
greenNumberyesValue of green component
blueNumberyesValue of blue component
alphaNumberyesValue of alpha component
FunctionsInputOutputDescription
toString()StringReturn representation of color as string
ConstructorArgumentsDescription
new Color(red, green, blue, alpha)Number
Number
Number
Number
Constructor with four color components

Some examples:

// Solid red
var color = new Color(1,0,0,1);
console.log(color);

// Transparent blue
var color = new Color(0,0,1,0.5);
component.backgroundColor = color;
    

Cursor

Cursor represents a point on the screen where the user is interacting.

PropertyTypeRead-OnlyDescription
xNumberyesX coordinate on window space
yNumberyesY coordinate on window space
idNumberyesUnique identifier
pathPathyesPath representing sequence of coordinates since cursor has been created
isTouchBooleanyesTrue when cursor represents a touch event
isScrollBooleanyesTrue when cursor represents a scroll event
FunctionsInputOutputDescription
toString()StringReturn representation of cursor as string

Some examples:

var gestureRecognizer = runtime.createGestureRecognizer("generic");

gestureRecognizer.onDidAddCursor = function(cursor, component) {
    console.log("Cursor added in component " + component.identifier);
    console.log("Cursor coordinates are (" + cursor.x + "," + cursor.y + ")");
};

gestureRecognizer.onDidRemoveCursor = function(cursor, component) {
    console.log("Cursor removed in component " + component.identifier);
    console.log("Cursor coordinates are (" + cursor.x + "," + cursor.y + ")");
};

gestureRecognizer.onDidUpdateCursor = function(cursor, component) {
    console.log("Cursor updated in component " + component.identifier);
    console.log("Cursor coordinates are (" + cursor.x + "," + cursor.y + ")");
};

component.setGestureRecognizer(gestureRecognizer);
    

Data

Data represents an opaque data structure which only the runtime can access or modify.

FunctionsInputOutputDescription
toText()StringReturn representation of data as string using the default encoding UTF-8
toText(encoding)StringStringReturn representation of data as string using the given encoding.
Encoding must be UTF-8, ASCII, ISO-8859-1 (Latin 1), or ISO-8859-2 (Latin 2)
toString()StringReturn representation of data as string
ConstructorArgumentsDescription
new Data(text)StringConstructor with text and default encoding UTF-8
new Data(text, encoding)String
String
Constructor with text and encoding.
Encoding must be UTF-8, ASCII, ISO-8859-1 (Latin 1), or ISO-8859-2 (Latin 2)

Some examples:

var url = new URL("file://" + runtime.resourcesPath + "/some-image.png");

var data = runtime.createComponentDataFromURL(url);

console.log(data.toString());

component.loadData(data);

var data = new Data("example", "ASCII");

console.log(data.toText("ASCII"));
    

GestureEvent

GestureEvent represents an event produced by a gesture recognizer.

PropertyTypeRead-OnlyDescription
centerXNumberyesX coordinate of center
centerYNumberyesY coordinate of center
translationXNumberyesAmount of translation on X axis
translationYNumberyesAmount of translation on Y axis
scaleXNumberyesAmount of scaling on X axis
scaleYNumberyesAmount of scaling on Y axis
rotationNumberyesAmount of rotation on Z axis in radiants
countNumberyesNumber of cursors associated with event
maskNumberyesBit mask representing event's state:
- Bit 0 is 1 when event translation in not 0
- Bit 1 is 1 when event scaling is not 1
- Bit 2 is 1 when event rotation in not 0
- Bit 3 is 1 when event cursors is greather than 0
FunctionInputOutputDescription
toString()StringReturn representation of event as string

Some examples:

var gestureRecognizer = runtime.createGestureRecognizer("smart");

gestureRecognizer.onDidUpdateGesture = function (event, component) {
    console.log("Center is " + event.centerX + "," +  event.centerY);
    console.log("Translation is " + event.translationX + "," +  event.translationY);
    console.log("Scale is " + event.scaleX + "," +  event.scaleY);
    console.log("Rotation is " + event.rotation);
    console.log("Cursors count is " + event.count);
    console.log("Mask is " + event.mask);
}

component.setGestureRecognizer(gestureRecognizer);
    

HttpHeader

HttpHeader represents a HTTP header.

PropertyTypeRead-OnlyDescription
nameStringyesName
valueStringyesValue
FunctionInputOutputDescription
toString()StringReturn representation of header as string
ConstructorArgumentsDescription
new HttpHeader(name, value)String
String
Constructor with name and value

Some examples:

var getRequest = new HttpRequestBuilder()
    .withHeader(new HttpHeader("Accept-Encoding", "gzip"))
    .withHeader(new HttpHeader("Accept", "text/html; charset=UTF-8"))
    .withURL("https://nextbreakpoint.com")
    .build();

httpClient.sendRequest(getRequest);
    

HttpRequest

HttpRequest represents a HTTP request.

PropertyTypeRead-OnlyDescription
urlStringyesTarget URL
methodStringyesMethod to use.
Valid values are GET, POST, PUT, DELETE, and OPTIONS
bodyDatayesBody as opache data
headersHttpHeader[]yesArray of headers
FunctionInputOutputDescription
toString()StringReturn representation of request as string

Some examples:

var httpClient = new HttpClient();

httpClient.onDidCompleteRequest = function(request, response) {
    console.log("Request url: " + request.url);
    console.log("Request method: " + response.method);
    console.log("Request headers: ");
    printArray(request.headers);
    console.log("Response code: " + response.statusCode);
    console.log("Response encoding: " + response.encoding);
    console.log("Response headers: ");
    printArray(response.headers);
    console.log("Response body: ");
    printArray(response.data.toText("UTF-8"));
};

httpClient.onDidFailRequest = function(request) {
    console.log("Request failed");
};

var getRequest = new HttpRequestBuilder()
    .withMethod("GET")
    .withHeader("Accept-Encoding", "gzip")
    .withHeader("Accept", "text/html; charset=UTF-8")
    .withURL("https://nextbreakpoint.com")
    .build();

httpClient.sendRequest(getRequest);

var postRequest = new HttpRequestBuilder()
    .withMethod("POST")
    .withHeader("Content-Type", "application/json")
    .withHeader("Accept", "application/json; charset=UTF-8")
    .withURL("http://somehost")
    .withBody("{\"product\":\"NextSurface\"}")
    .build();

httpClient.sendRequest(postRequest);
    

HttpResponse

HttpResponse represents a HTTP response.

PropertyTypeRead-OnlyDescription
statusCodeNumberyesResponse status code
encodingDatayesResponse encoding name
dataDatayesReceived data as opache data
headersHttpHeader[]yesArray of headers
FunctionInputOutputDescription
toString()StringReturn representation of response as string

Some examples:

var httpClient = new HttpClient();

httpClient.onDidCompleteRequest = function(request, response) {
    console.log("Request url: " + request.url);
    console.log("Request method: " + response.method);
    console.log("Request headers: ");
    printArray(request.headers);
    console.log("Response code: " + response.statusCode);
    console.log("Response encoding: " + response.encoding);
    console.log("Response headers: ");
    printArray(response.headers);
    console.log("Response body: ");
    printArray(response.data.toText("UTF-8"));
};

httpClient.onDidFailRequest = function(request) {
    console.log("Request failed");
};

var getRequest = new HttpRequestBuilder()
    .withMethod("GET")
    .withHeader("Accept-Encoding", "gzip")
    .withHeader("Accept", "text/html; charset=UTF-8")
    .withURL("https://nextbreakpoint.com")
    .build();

httpClient.sendRequest(getRequest);
    

KeyboardEvent

KeyboardEvent represents an event produced by a keyboard component.

PropertyTypeRead-OnlyDescription
textStringyesText associated with event.
Please note some events might not have a text
codeStringyesInternal code for key.
See table of internal codes below
keyCodeNumberyesSystem key code associated with event.
Please note some events might not have a key code.
See table of system key codes below
FunctionInputOutputDescription
toString()StringReturn representation of event as string

System key codes:

Key codeValue
VK_00x30
VK_10x31
VK_20x32
VK_30x33
VK_40x34
VK_50x35
VK_60x36
VK_70x37
VK_80x38
VK_90x39
VK_A0x41
VK_B0x42
VK_C0x43
VK_D0x44
VK_E0x45
VK_F0x46
VK_G0x47
VK_H0x48
VK_I0x49
VK_J0x4A
VK_K0x4B
VK_L0x4C
VK_M0x4D
VK_N0x4E
VK_O0x4F
VK_P0x50
VK_Q0x51
VK_R0x52
VK_S0x53
VK_T0x54
VK_U0x55
VK_V0x56
VK_W0x57
VK_X0x58
VK_Y0x59
VK_Z0x5A
VK_DIVIDE0x6F
VK_MULTIPLY0x6A
VK_ADD0x6B
VK_SUBTRACT0x6D
VK_SPACE0x20
VK_BACK0x08
VK_RETURN0x0D
VK_UNKNOWN0x07

Internal codes:

CodeValue
Text0
Return10
Space11
Backspace12
Up20
Down21
Left22
Right23
Switch30
None40

Some examples:

var keyboardComponent = runtime.createComponent("keyboard", new Rect(0, 0, 900, 300));

keyboardComponent.onKeyDown = function(event) {
    console.log("Key down " + event.toString());
};

keyboardComponent.onKeyUp = function(event) {
    console.log("Key up " + event.toString());
};
    

LayoutConstraint

LayoutConstraint represents a constraint for a component managed by a layout manager.

PropertyTypeRead-OnlyDescription
leftMeasureyesLeft margin
rightMeasureyesRight margin
topMeasureyesTop margin
bottomMeasureyesBottom margin
widthMeasureyesPreferred width
heightMeasureyesPreferred height
minimumWidthSizeyesMinimum width
minimumHeightSizeyesMinimum height
maximumWidthSizeyesMaximum width
maximumHeightSizeyesMaximum height
anchorLeftPointyesAnchor left
anchorTopPointyesAnchor top
autoscaleBooleanyesApply translation and scale of container
FunctionInputOutputDescription
withMargins(top, right, bottom, left)Measure
Measure
Measure
Measure
LayoutConstraintCreate copy with given margins top, right, bottom, left
withMargins(top, right, bottom, left)String
String
String
String
LayoutConstraintCreate copy with given margins top, right, bottom, left
withSize(width, height)Measure
Measure
LayoutConstraintCreate copy with given width and height
withSize(width, height)String
String
LayoutConstraintCreate copy with given width and height
withMinimumSize(width, height)Measure
Measure
LayoutConstraintCreate copy with given minimum width and height
withMinimumSize(width, height)String
String
LayoutConstraintCreate copy with given minimum width and height
withMaximumSize(width, height)Measure
Measure
LayoutConstraintCreate copy with given maximum width and height
withMaximumSize(width, height)String
String
LayoutConstraintCreate copy with given maximum width and height
withAnchor(left, top)Measure
Measure
LayoutConstraintCreate copy with given anchor left and top
withAnchor(left, top)String
String
LayoutConstraintCreate copy with given anchor left and top
withAutoscale(enable)BooleanLayoutConstraintCreate copy with given autoscale
toString()StringReturn representation of constraint as string
ConstructorArgumentsDescription
new LayoutConstraint()Constructor without arguments. The new constraint has no measure attributes and autoscale is disabled

Some examples:

var constraint = new LayoutConstraint().withSize(new Measure("50.0", "%"), new Measure("50.0", "%"));

console.log(constraint.toString());

var constraint = new LayoutConstraint().withSize("50.0%", "50.0%");

console.log(constraint.toString());

var constraint = new LayoutConstraint().withSize(null, "50.0%").withMargins("10%", null, "10%", null);

console.log(constraint.toString());

var constraint = new LayoutConstraint().withMargins("10%", "10%", "10%", "10%");

console.log(constraint.toString());

var constraint = new LayoutConstraint().withMinimumSize("0.1f", "0.1f").withMaximumSize("1f", "1f");

console.log(constraint.toString());
    

Measure

Measure represents a length measurement which can be converted to pixels.

PropertyTypeRead-OnlyDescription
valueNumberyesValue of the measure
unitStringyesUnit of the measure
FunctionsInputOutputDescription
toString()StringReturn representation of measure as string
ConstructorArgumentsDescription
new Measure(value)NumberConstructor with default unit px
new Measure(value, unit)Number
String
Constructor with value and unit.
Valid units are px, %, and f

Some examples:

// Dimension as pixels (default type)
var size = new Measure(10);

// Dimension as pixels
var size = new Measure(10,"px");

// Dimension as percentage
var width = new Measure(50,"%");

// Dimension as decimal number
var width = new Measure(0.5,"f");
    

PathAttributes

PathAttributes represents attributes of a path.

PropertyTypeRead-OnlyDescription
centerPointyesCenter
scaleSizeyesScale
rotationNumberyesRotation in radiants
lineWidthNumberyesLine width
strokeColorColoryesStroke color
FunctionInputOutputDescription
toString()StringReturn representation of attributes as string
ConstructorArgumentsDescription
new PathAttributes(center, scale, rotation, lineWidth, strokeColor)Point
Size
Number
Number
Color
Constructor with all attributes

Some examples:

var attributes = new PathAttributes(new Point(0,0), new Size(10,10), 0, 0.1, new Color(1,0,0,1));

console.log(attributes);

console.log(attributes.strokeColor);
    

Point

Point represents Cartesian coordinates.

PropertyTypeRead-OnlyDescription
xNumberyesX coordinate
yNumberyesY coordinate
FunctionInputOutputDescription
toString()StringReturn representation of point as string
ConstructorArgumentsDescription
new Point(x, y)Number
Number
Constructor with coordinates

Some examples:

var point = new Point(10.1,20.2);

console.log("Coordinates are (" + point.x + "," + point.y + ")");
    

Rect

Rect represents a rectangle.

PropertyTypeRead-OnlyDescription
xNumberyesX coordinate of left bottom corner
yNumberyesY coordinate of left bottom corner
widthNumberyesWidth or rectangle
heightNumberyesHeight or rectangle
FunctionInputOutputDescription
toString()StringReturn representation of rect as string
ConstructorArgumentsDescription
new Rect(x, y, width, height)Number
Number
Number
Number
Constructor with arguments as numbers

Some examples:

var rectangle = new Rect(0,0,100,200);

console.log("Position is " + rectangle.x + "," + rectangle.y);
console.log("Dimension is " + rectangle.width + "," + rectangle.height);
    

Size

Size represents a dimension.

PropertyTypeRead-OnlyDescription
widthNumberyesWidth as number
heightNumberyesHeight as number
FunctionInputOutputDescription
toString()StringReturn representation of size as string
ConstructorArgumentsDescription
new Size(width, height)Number
Number
Constructor with arguments as numbers

Some examples:

var size = new Size(100,200);

console.log("Dimension is " + size.width + "," + size.height);
    

Transform

Transform represents a vectorial transformation.

PropertyTypeRead-OnlyDescription
xNumberyesX coordinate
yNumberyesY coordinate
scaleXNumberyesX scale
scaleYNumberyesY scale
rotationNumberyesRotation in radians
speedNumberyesTransformation animation speed.
Must be a number between 0 and 1
FunctionInputOutputDescription
translateBy(x, y)Number
Number
TransformCreate new transform composing translation
scaleBy(x, y)Number
Number
TransformCreate new transform composing scale
rotateBy(a)NumberTransformCreate new transform composing rotation
withTranslation(x, y)Number
Number
TransformCreate new transform replacing translation
withScale(x, y)Number
Number
TransformCreate new transform replacing scale
withRotation(a)NumberTransformCreate new transform replacing rotation
withSpeed(s)NumberTransformCreate new transform replacing speed
toString()StringReturn representation of transform as string
ConstructorArgumentsDescription
new Transform(tx, ty, sx, sy, a, s)Number
Number
Number
Number
Number
Number
Constructor with arguments as numbers

Some examples:

var transform = new Transform(10.1,20.2,1,1,0,0.5);

console.log("Translation is " + transform.x + "," + transform.y);
console.log("Scale is " + transform.scaleX + "," + transform.scaleY);
console.log("Rotation is " + transform.rotation);
console.log("Animation speed is " + transform.speed);
    

URL

URL represents a url.

PropertyTypeRead-OnlyDescription
pathStringyesPath represented by url
FunctionInputOutputDescription
writeString(text)StringWrite text at location represented by url
readString()StringLoad text from location represented by url
toString()StringReturn representation of url as string
ConstructorArgumentsDescription
new URL(string)StringConstructor with string argument

Some examples:

var url = new URL("file://" + runtime.resourcesPath + "/some-image.png");

console.log("File located at " + url.path);

var url = new URL("http://localhost/some-image.png");

console.log("Resource located at " + url.toString());
    

Stateful Objects

HttpClient

HttpClient represents a HTTP client. HttpClient must be invalidate to free resources when it is not required anymore.

PropertyTypeRead-OnlyDescription
onDidCompleteRequestFunctionnoCallback invoked when request is completed
onDidFailRequestFunctionnoCallback invoked when request has failed
FunctionInputOutputDescription
sendRequest(request)HttpRequestBooleanSubmit a http request. Returns true if request has been sent successfuly, otherwise returns false
cancelRequest(request)HttpRequestBooleanCancel a http request. Returns false if request has been cancelled already, otherwise returns true
invalidate()Invalidate the client. Further interaction with the client won't produce any effect
toString()StringReturn representation of client as string
CallbackInputOutputDescription
onDidCompleteRequest(request, response)HttpRequest
HttpResponse
Request completed
onDidFailRequest(request)HttpRequestRequest failed
ConstructorArgumentsDescription
new HttpClient()Constructor without arguments

Some examples:

var httpClient = new HttpClient();

httpClient.onDidCompleteRequest = function(request, response) {
    console.log("Request url: " + request.url);
    console.log("Request method: " + response.method);
    console.log("Request headers: ");
    printArray(request.headers);
    console.log("Response code: " + response.statusCode);
    console.log("Response encoding: " + response.encoding);
    console.log("Response headers: ");
    printArray(response.headers);
    console.log("Response body: ");
    printArray(response.data.toText("ISO-8859-1"));
};

httpClient.onDidFailRequest = function(request) {
    console.log("Request failed");
};

var getRequest = new HttpRequestBuilder()
    .withHeader("Accept-Encoding", "gzip")
    .withHeader("Accept", "text/html; charset=ISO-8859-1")
    .withURL("http://www.google.com")
    .build();

httpClient.sendRequest(getRequest);

runtime.onApplicationStopping = function() {
    httpClient.invalidate();
};

function printArray(entries) {
  for (var i = 0; i < entries.length; i++) {
    console.log(entries[i].toString());
  }
}
    

HttpRequestBuilder

HttpRequestBuilder represents a builder for creating HTTP requests.

FunctionInputOutputDescription
withURL(url)StringHttpRequestBuilderAdd URL and return builder
withMethod(method)StringHttpRequestBuilderAdd method and return builder
withHeader(header)HttpHeaderHttpRequestBuilderAdd header and return builder
withHeader(name,value)String
String
HttpRequestBuilderAdd header by name and value and return builder
withBody(data)DataHttpRequestBuilderAdd body as opache data and return builder
withBody(text)StringHttpRequestBuilderAdd body as text and return builder. The text will be converted to data using UTF-8 encoding
build()HttpRequestCreate a HTTP request
toString()StringReturn representation of builder as string

Some examples:

var httpClient = new HttpClient();

httpClient.onDidCompleteRequest = function(request, response) {
    console.log("Request url: " + request.url);
    console.log("Request method: " + response.method);
    console.log("Request headers: ");
    printArray(request.headers);
    console.log("Response code: " + response.statusCode);
    console.log("Response encoding: " + response.encoding);
    console.log("Response headers: ");
    printArray(response.headers);
    console.log("Response body: ");
    printArray(response.data.toText("UTF-8"));
};

httpClient.onDidFailRequest = function(request) {
    console.log("Request failed");
};

var getRequest = new HttpRequestBuilder()
    .withMethod("GET")
    .withHeader("Accept-Encoding", "gzip")
    .withHeader("Accept", "text/html; charset=UTF-8")
    .withURL("https://nextbreakpoint.com")
    .build();

httpClient.sendRequest(getRequest);

var postRequest = new HttpRequestBuilder()
    .withMethod("POST")
    .withHeader("Content-Type", "application/json")
    .withHeader("Accept", "application/json; charset=UTF-8")
    .withURL("http://somehost")
    .withBody("{\"product\":\"NextSurface\"}")
    .build();

httpClient.sendRequest(postRequest);
    

Image

Image represents an image structure. Images are often created by other classes. For instance, a component can generate snapshots capturing the content of the screen.

PropertyTypeRead-OnlyDescription
sizeSizeyesDimension of image as size object
FunctionInputOutputDescription
saveTo(path)StringSave image to file located at path
saveTo(url)URLSave image to resource located at url
loadFrom(path)StringLoad image from file located at path
loadFrom(url)URLLoad image from resource located at url
toString()StringReturn representation of image as string
ConstructorArgumentsDescription
new Image(path)StringConstructor with file's path
new Image(url)URLConstructor with resource's url

Some examples:

var image = new Image(runtime.resourcesPath + "/some-image.png");

image.saveTo(runtime.resourcesPath + "/copy-of-some-image.png");

image.loadFrom("https://hostname:443/another-image.png");
    

Page

Page represents a collection of paths.

PropertyTypeRead-OnlyDescription
paths[Path]yesCopy of internal list of paths
FunctionInputOutputDescription
addPath(path)PathAdd a path to the internal list of paths
removePath(path)PathRemove a path from the internal list of paths
toString()StringReturn representation of page as string
ConstructorArgumentsDescription
new Page()Constructor without arguments

Some examples:

var page = new Page();

var path = new Path();

path.addPoint(new Point(1,2));

page.addPath(path);

console.log(page);
    

Path

Path represents a sequence of points with some attributes.

PropertyTypeRead-OnlyDescription
attributesPathAttributesnoAttributes of the path
points[Point]yesCopy of internal list of points
FunctionInputOutputDescription
addPoint(point)PointAdd a point to the internal list of points
removePoint(point)PointRemove a point from the internal list of points
scaleBy(x, y)Number
Number
PathReturn a scaled copy of the path
toString()StringReturn representation of path as string
ConstructorArgumentsDescription
new Path()Constructor without arguments
new Path(attributes)PathAttributesConstructor with attributes

Some examples:

var attributes = new PathAttributes(new Point(0,0), new Size(10,10), 0, 0.1, new Color(1,0,0,1));

var path = new Path(attributes);

path.addPoint(new Point(1,2));
path.addPoint(new Point(2,3));

console.log(path);
    

Timer

Timer represents a countdown which triggers a periodic event. Timers must be invalidate to free resources when they are not required anymore.

PropertyTypeRead-OnlyDescription
countdownNumbernoNumber of periods before triggering the event. Default value is 1
repeatNumbernoRestart when countdown is equals to zero. Default value is true
intervalNumberyesDelay interval before decrementing countdown. Default value is 1 second
FunctionInputOutputDescription
start()Start timer's countdown
stop()Stop timer's countdown
invalidate()Invalidate the timer. Further interaction with the timer won't produce any effect
toString()StringReturn representation of timer as string
ConstructorArgumentsDescription
new Timer(callback, interval)Function
Number
Constructor with callback function and interval in seconds.
The callback is invoked when the timer reaches the end of the countdown
CallbackInputOutputDescription
callback()Countdown terminated

Some examples:

var callback = function() {
    console.log("Countdown finished after " + (this.interval * this.countdown) + " seconds");
};

var timer = new Timer(callback, 1);

timer.countdown = 5;

timer.start();

console.log(timer.toString());
    

Watcher

Watcher watches the content of a directory and notifies when files are added, modified, or removed. Watchers must be invalidate to free resources when they are not required anymore.

PropertyTypeRead-OnlyDescription
onFileAddedFunctionnoCallback invoked in case of file added
onFileUpdatedFunctionnoCallback invoked in case of file updated
onFileRemovedFunctionnoCallback invoked in case of file removed
FunctionInputOutputDescription
start()Start watcher's watch loop
stop()Stop watcher's watch loop
invalidate()Invalidate the watcher. Further interaction with the watcher won't produce any effect
toString()StringReturn representation of watcher as string
ConstructorArgumentsDescription
new Watcher(path)StringConstructor with path as string. The path represents the directory watched by the watcher
CallbackInputOutputDescription
onFileAdded(path)StringFile added
onFileUpdated(path)StringFile updated
onFileRemoved(path)StringFile removed

Some examples:

var watcher = new Watcher(runtime.resourcePath + "/resources");

watcher.onFileAdded = function(filePath) {
    console.log("File added " + filePath);
};

watcher.onFileUpdated = function(filePath) {
    console.log("File updated " + filePath);
};

watcher.onFileRemoved = function(filePath) {
    console.log("File removed " + filePath);
};

watcher.start();
    

Built-in Objects

Console

Console is a built-in object which provides logging capability.

FunctionsInputOutputDescription
log(message)StringPrint message on standard output

Some examples:

console.log("Hello " + "World!");
    

The output is produced on the standard output and can be observed using the system application Console, just filtering by process name. Alternatively, the output appears on the terminal when executing the command:

MacBook-di-Andrea:~ andrea$ /Applications/NextSurface.app/Contents/MacOS/NextSurface

Output looks like:

2018-04-06 19:09:37.450 NextSurface[54709:2142262] NextSurface 1.2 (20160710)
2018-04-06 19:09:37.450 NextSurface[54709:2142262] Copyright (c) 2016 Andrea Medeghini
2018-04-06 19:09:37.450 NextSurface[54709:2142262] Application is loading...
...
2018-04-06 19:09:54.966 NextSurface[54715:2142873] deallocate object 39 [JSGestureRecognizer] (0)
2018-04-06 19:09:54.966 NextSurface[54715:2142873] deallocate object 12 [JSLayoutManager2] (0)
2018-04-06 19:09:54.966 NextSurface[54715:2142873] deallocate object 40 [JSTimer] (0)
2018-04-06 19:09:54.966 NextSurface[54715:2142873] deallocate object 37 [JSWatcher] (0)
2018-04-06 19:09:54.985 NextSurface[54715:2142873] Application is terminated
MacBook-di-Andrea:~ andrea$
    

Runtime

Runtime is a built-in object which represents NextSurface's engine.

PropertyTypeRead-OnlyDescription
versionStringyesRuntime's version
programStringyesRuntime's program
windowFrameRectyesOrigin and size of application's window
workspacePathStringyesPath of application's workspace
rootComponentComponentnoRoot component associated with application's window
inactivityTimeoutNumbernoTime in seconds of user's inactivity before generating inactivity timeout
onApplicationStartedFunctionnoCallback invoked when application has started
onApplicationStoppingFunctionnoCallback invoked when application is stopping
onApplicationStoppedFunctionnoCallback invoked when application has stopped
onWindowResizedFunctionnoCallback invoked when application's window has been resised
onInactivityTimeoutFunctionnoCallback invoked when user's inactivity timeout is generated
onFileUploadedFunctionnoCallback invoked when user uploads a file using a iOS device
FunctionInputOutputDescription
createComponent(type,rect)String
Rect
ComponentCreate a component by type and initial frame
createLayoutManager(type)StringLayoutManagerCreate a layout manager by type
createGestureRecognizer(type)StringGestureRecognizerCreate a gesture recognizer by type
componentTypeForURL(url)String or URLStringReturn the component type associated with a resource url
isComponentAvailableForURL(url)String or URLBooleanReturn true if a component type associated with a resource url exists
createComponentDataFromURL(url)String or URLDataLoad the data associated with a resource url
createComponentDataFromURL(url, callback)String or URL
Function
Asyncronously load the data associated with a resource url and invoke callback when data is ready
createDefaultCaptureData()DataCreate data which represents the default capture device
findResource(name)StringURLSearch for a resource by name and return the url of the file if exists
registerContentType(contentType)StringRegister a content type as accepted value when uploading a file
unregisterContentType(contentType)StringUnregister a content type as accepted value when uploading a file
clearCursors()Abort all gestures and remove all cursors
urlencode(string)StringStringEncode a string using url encoding
toString()StringReturn representation of runtime as string
CallbackInputOutputDescription
onApplicationStarted()Application started
onApplicationStopping()Application stopping
onApplicationStopped()Application stopped
onWindowResized(rect)RectWindows frame changed
onInactivityTimeout()User inactivity timeout
onFileUploaded(path)StringFile has been uploaded

Some examples:

runtime.onApplicationStopping = function() {
    console.log("NextSurface is stopping...");
};

runtime.onApplicationStopped = function() {
    console.log("NextSurface has stopped");
};

runtime.onApplicationStarted = function() {
    console.log("NextSurface has started");
};

runtime.onWindowResized = function(rect) {
    console.log("The new window size is " + rect.width + " \u2613 " + rect.height);
};

console.log("Runtime " + runtime.toString());
    

System

System is a built-in object which represents the operating system.

FunctionInputOutputDescription
listFiles(path)String[String]List files or directories at given path
deleteFile(path)StringDelete file or directory at given path
makeDirs(path)StringMake directories at given path
makeTmp(path, suffix)String
String
StringCreate a temporary file
chmode(path, mode)String
Number
Change access mode of a file or directory

Some examples:

var files = system.listFiles(runtime.workspacePath);

for (var i = 0; i < files.length; i++) {
    console.log(files[i]);
}
    

Abstract Objects

Component

Component represents the parent abstract class of all UI components. Components must be invalidate to free resources when they are not required anymore.

PropertyTypeRead-OnlyDescription
typeStringyesType of the component
identifierStringnoIdentifier of the component
frameRectnoOrigin and size of the component
frameSizeSizenoSize of the component
frameScaleSizenoScale of the component
frameOriginPointnoOrigin of the component
frameRotationNumbernoRotation of the component
actualTransformTransformyesCurrent transform of the component
savedTransformTransformyesSaved transform of the component
targetTransformTransformnoTarget transform of the component. The runtime will animate the component interpolating the difference between the current transform and the target transform
hiddenBooleannoVisibility of the component. When component is hidden, it is not able to receive events
activeBooleannoUse this flag to signal when the component is active
loadingBooleannoUse this flag to signal when the component is loading
opacityNumbernoOpacity of the component. It must be a value between 0.0 and 1.0
depthNumbernoDepth of the component. Depth is relevant only when the component is inside a container
dirtyFrameBooleanyesTrue means that the current component's frame is being changed by an animation. False means that the component's frame reflects the final value of an animation
drawInSnapshotBooleannoTrue means that the component will be visible when creating a snapshot image of the parent component. False means the component is ignored
masksToBoundsBooleannoTrue means that the child components are clipped with the bounds of the component. False means the child components are still visible when they are positioned outside the bounds of the component
drawBackgroundBooleannoTrue means that the component is filled with the background color. False means that the component has a transparent background
dispatchEventsBooleannoTrue means that the events are dispatched to child components. False means that only the component receive events
backgroundColorColornoBackground color of the component
foregroundColorColornoForeground color of the component
preferredSizeSizeyesRecommended size of the component
onInvalidateFunctionnoCallback invoked when component is invalidated
onUpdateTransformFunctionnoCallback invoked when component transform is updated. This callback is invoked multiple times during an animation
onChangeTransformFunctionnoCallback invoked when component transform is changed. This callback is invoked once when the animation is completed
FunctionInputOutputDescription
isKindOfType(type)StringBooleanEvaluate if component is compatible with a given type
initTransform()Copy the target transform into the current transform and save the current transform
saveTransform()Save the current transform. The transform will be kept until is overriden by some other action
resetTransform()Update the current transform and apply changes to component
updateTransform()Update the transform by interpolating the distance from the target transform and the current transform. The new transform depends on the speed value in the transform
transformPoint(point)PointPointTransform a point using the current transform
containsPoint(point)PointBooleanCheck if a point is contained in the component
convertPointToComponent(point)PointPointConvert a point from screen coordinates to component coordinates
convertPointFromComponent(point)PointPointConvert a point from component coordinates to screen coordinates
convertPointToContainer(point)PointPointConvert a point from screen coordinates to parent component coordinates
convertPointFromContainer(point)PointPointConvert a point from parent component coordinates to screen coordinates
setGestureRecognizer(recognizer)GestureRecognizerAssign a gesture recognizer to the component. Pass null to remove the current recognizer
takeSnapshot()ImageCreate a snapshot image from the component. The image will have the same size as the component
invalidate()Invalidate the component. Further interaction with the component won't produce any effect
redraw()Request component to redraw content
toString()StringReturn representation of component as string

Some examples:

var component = runtime.createComponent("image", new Rect(0,0,runtime.frame.width,runtime.frame.height));

component.identifier = "component-image";

component.backgroundColor = new Color(1,0,0,1);

console.log("Component " + component.toString());
    

GestureRecognizer

GestureRecognizer transforms touch events into gestures. GestureRecognizer represents the parent abstract class of all gesture recognizers. Gesture recognizers must be invalidate to free resources when they are not required anymore.

PropertyTypeRead-OnlyDescription
onDidAddCursorFunctionnoCallback invoked when a cursor is added
onDidUpdateCursorFunctionnoCallback invoked when a cursor is updated
onDidRemoveCursorFunctionnoCallback invoked when a cursor is removed
onDidProcessGestureFunctionnoCallback invoked when previous gesture has been processed
cursorCountNumberyesNumber of cursors in current gesture
elapsedTimeNumberyesTime elapsed since gesture began
FunctionInputOutputDescription
reset()Reset internal state and reset state of cursors which are associated with gesture recognizer
clearCursors()Disassociate cursors from gesture recognizer and reset internal state
updateStartTime()Set gesture's start time to current time
invalidate()Invalidate the gesture recognizer. Further interaction with the gesture recognizer won't produce any effect
toString()StringReturn representation of gesture recognizer as string
CallbackInputOutputDescription
onDidAddCursor(cursor, component)Cursor
Component
Cursor added
onDidUpdateCursor(cursor, component)Cursor
Component
Cursor updated
onDidRemoveCursor(cursor, component)Cursor
Component
Cursor removed
onDidProcessGesture(component)ComponentGesture processed

Some examples:

var gestureRecognizer = runtime.createGestureRecognizer("smart");

gestureRecognizer.onDidBeginGesture = function (event, component) {
    if (this.isScroll) {
      return;
    }

    component.saveTransform();
    component.updateTransform();
};

gestureRecognizer.onDidUpdateGesture = function (event, component) {
    if (this.isScroll) {
      return;
    }

    var transform = component.transform;

    var w = transform.scaleX * event.scaleX;
    var h = transform.scaleY * event.scaleY;
    var r = transform.rotation + event.rotation;

    var s = new Point(event.scaleX, event.scaleY);
    var c = new Point(event.centerX, event.centerY);
    var d = new Point(event.translationX, event.translationY);

    var p = new Point(transform.x, transform.y);
    p = component.convertPointFromSuperView(p);
    var t = new Point(c.x - d.x, c.y - d.y);
    p = component.transformPoint(p, new Transform(t.x, t.y, s.x, s.y, rz, 0));
    p = new Point(p.x + d.x, p.y + d.y);
    p = component.convertPointToSuperView(p);

    var x = p.x;
    var y = p.y;

    component.targetTransform = new Transform(x, y, w, h, r, 0.5);
};

gestureRecognizer.onDidEndGesture = function (event, component) {
};

gestureRecognizer.onDidAddCursor = function (cursor, component) {
    component.active = true;
    if (cursor.isScroll) {
      this.isScroll = true;
    }
};

gestureRecognizer.onDidRemoveCursor = function (cursor, component) {
    if (this.cursorCount == 0) {
      component.active = false;
      this.isScroll = false;
    }
};

component.setGestureRecognizer(gestureRecognizer);
    

LayoutManager

LayoutManager assigns position and size to children of a container. LayoutManager represents the parent abstract class of all layout managers. Layout managers must be invalidate to free resources when they are not required anymore.

FunctionInputOutputDescription
invalidate()Invalidate the layout manager. Further interaction with the layout manager won't produce any effect
toString()StringReturn representation of layout manager as string

Some examples:

var container = runtime.createComponent("panel", new Rect(0, 0, 100, 100));

var component1 = runtime.createComponent("panel", new Rect(0, 0, 100, 100));
component1.identifier = "name1";

var component2 = runtime.createComponent("panel", new Rect(0, 0, 100, 100));
component2.identifier = "name2";

container.setConstraint(new LayoutConstraint().withSize("50%", "100%"), "name1");
container.setConstraint(new LayoutConstraint().withSize("50%", "100%"), "name2");

var layoutManager = runtime.createLayoutManager("grid");

container.setLayoutManager(layoutManager);

container.addComponent(component1);
container.addComponent(component2);

container.layoutComponents();
    

Are you looking for something else?


Follow NextSurface on Facebook