how-tos made with markdown snippet injector

This commit is contained in:
Nikolay Iliev
2016-04-14 15:20:35 +03:00
parent 5ceeb7fddd
commit 89fad4f41c
43 changed files with 1207 additions and 1116 deletions

View File

@ -1,10 +1,7 @@
// <snippet module="application-settings" title="application-settings">
// # Application Settings
// Using application settings methods requires to load "application settings" module.
// ``` JavaScript
// >> application-settings-require
var appSettings = require("application-settings");
// ```
// </snippet>
// << application-settings-require
var TKUnit = require("./TKUnit");
var stringKey:string = "stringKey";
@ -14,72 +11,51 @@ var noStringKey: string = "noStringKey";
var noBoolKey: string = "noBoolKey";
var noNumberKey: string = "noNumberKey";
// <snippet module="application-settings" title="application-settings">
// ## Working with string, number and boolean values
// </snippet>
export var testBoolean = function () {
appSettings.setBoolean(boolKey, false);
var boolValueBefore = appSettings.getBoolean(boolKey);
TKUnit.assert(false === boolValueBefore, "Cannot set boolean to false, currently it is: " + appSettings.getBoolean(boolKey));
// <snippet module="application-settings" title="application-settings">
// ### Set and get boolean value and provide default value in case it is not set
// ``` JavaScript
// >> application-settings-boolean
appSettings.setBoolean("boolKey", true);
var boolValue = appSettings.getBoolean("boolKey", false);
// ```
// </snippet>
// << application-settings-boolean
TKUnit.assert(true === boolValue, "Cannot set boolean to true");
TKUnit.assert(true === appSettings.getBoolean(boolKey), "Cannot set boolean to true (no default)");
};
export var testString = function () {
// <snippet module="application-settings" title="application-settings">
// ### Set and get string value
// ``` JavaScript
// >> application-settings-string
appSettings.setString("stringKey", "String value");
var stringValue = appSettings.getString("stringKey");
// ```
// </snippet>
// << application-settings-string
TKUnit.assert("String value" === stringValue, "Cannot set string value");
};
export var testNumber = function () {
// <snippet module="application-settings" title="application-settings">
// ### Set and get numeric value.
// We use `toFixed()` here in order to avoid floating point errors - ex: `54.321` becoming `54.320999999537`.
// Beware the result of `toFixed()` is a string not a number therefore you cannot use `===` or `!==` when comparing with a number.
// ``` JavaScript
// >> application-settings-number
appSettings.setNumber("numberKey", 54.321);
var value = parseFloat(appSettings.getNumber("numberKey").toFixed(3));
// ```
// </snippet>
// << application-settings-number
TKUnit.assert(54.321 === value, "Cannot set number value 54.321 != " + value);
};
export var testDefaults = function () {
// <snippet module="application-settings" title="application-settings">
// ### Reading values that are not set before while providing default value
// ``` JavaScript
// >> application-settings-notset
var defaultValue = appSettings.getString("noStringKey", "No string value");
//// will return "No string value" if there is no value for "noStringKey"
// ```
// </snippet>
// << application-settings-notset
TKUnit.assert("No string value" === defaultValue, "Bad default string value");
TKUnit.assert(true === appSettings.getBoolean(noBoolKey, true), "Bad default boolean value");
TKUnit.assert(123.45 === appSettings.getNumber(noNumberKey, 123.45), "Bad default number value");
}
export var testDefaultsWithNoDefaultValueProvided = function () {
// <snippet module="application-settings" title="application-settings">
// ### Reading values that are not set before not providing default value
// ``` JavaScript
// >> application-settings-nodefault
var defaultValue = appSettings.getString("noStringKey");
//// will return undefined if there is no value for "noStringKey"
// ```
// </snippet>
// << application-settings-nodefault
TKUnit.assert("undefined" === typeof defaultValue, "Default string value is not undefined");
TKUnit.assert("undefined" === typeof appSettings.getBoolean(noBoolKey), "Default boolean value is not undefined");
@ -91,13 +67,10 @@ export var testDefaultsWithNoDefaultValueProvided = function () {
// </snippet>
export var testHasKey = function () {
// <snippet module="application-settings" title="application-settings">
// ### Checking for existence of value for key
// ``` JavaScript
// >> application-settings-haskey
var hasKey = appSettings.hasKey("noBoolKey");
//// will return false if there is no value for "noBoolKey"
// ```
// </snippet>
// << application-settings-haskey
TKUnit.assert(!hasKey, "There is a key: " + noBoolKey);
TKUnit.assert(!appSettings.hasKey(noStringKey), "There is a key: " + noStringKey);
TKUnit.assert(!appSettings.hasKey(noNumberKey), "There is a key: " + noNumberKey);
@ -108,12 +81,9 @@ export var testHasKey = function () {
};
export var testRemove = function () {
// <snippet module="application-settings" title="application-settings">
// ### Removing value for key
// ``` JavaScript
// >> application-settings-removekey
appSettings.remove("boolKey");
// ```
// </snippet>
// << application-settings-removekey
TKUnit.assert(!appSettings.hasKey(boolKey), "Failed to remove key: " + boolKey);
appSettings.remove(stringKey);
@ -124,12 +94,9 @@ export var testRemove = function () {
};
export var testClear = function () {
// <snippet module="application-settings" title="application-settings">
// ### Removing all values
// ``` JavaScript
// >> application-settings-clear
appSettings.clear();
// ```
// </snippet>
// << application-settings-clear
TKUnit.assert(!appSettings.hasKey(boolKey), "Failed to remove key: " + boolKey);
TKUnit.assert(!appSettings.hasKey(stringKey), "Failed to remove key: " + stringKey);
TKUnit.assert(!appSettings.hasKey(numberKey), "Failed to remove key: " + numberKey);

View File

@ -0,0 +1,36 @@
---
nav-title: "application-settings How-To"
title: "How-To"
description: "Examples for using application-settings"
---
# Application Settings
Using application settings methods requires to load "application settings" module.
<snippet id='application-settings-require'/>
## Working with string, number and boolean values
### Set and get boolean value and provide default value in case it is not set
<snippet id='application-settings-boolean'/>
### Set and get string value
<snippet id='application-settings-string'/>
### Set and get numeric value.
We use `toFixed()` here in order to avoid floating point errors - ex: `54.321` becoming `54.320999999537`.
Beware the result of `toFixed()` is a string not a number therefore you cannot use `===` or `!==` when comparing with a number.
<snippet id='application-settings-number'/>
### Reading values that are not set before while providing default value
<snippet id='application-settings-notset'/>
### Reading values that are not set before not providing default value
<snippet id='application-settings-nodefault'/>
## Other functions
### Checking for existence of value for key
<snippet id='application-settings-haskey'/>
### Removing value for key
<snippet id='application-settings-removekey'/>
### Removing all values
<snippet id='application-settings-clear'/>

View File

@ -1,26 +1,15 @@
// <snippet module="application" title="application">
// # Application
// The Application module provides abstraction over the platform-specific Application implementations.
// It is the main BCL module and is required for other BCL modules to work properly.
// The default bootstrap.js implementation for each platform loads and initializes this module.
// ``` JavaScript
// >> application-require
import app = require("application");
import platform = require("platform");
// ```
// The pre-required `app` module is used throughout the following code snippets.
// </snippet>
// << application-require
// <snippet module="application" title="application">
// ### Checking the target platform
// Use the following code in case you need to check somewhere in your code the platform you are running against:
// ``` JavaScript
// >> application-app-check
if (app.android) {
console.log("We are running on Android device!");
} else if (app.ios) {
console.log("We are running on iOS device");
}
// ```
// </snippet>
// << application-app-check
import TKUnit = require("./TKUnit");

View File

@ -5,32 +5,23 @@ import commonTests = require("./application-tests-common");
global.moduleMerge(commonTests, exports);
// <snippet module="application" title="application">
// ### Using the Android-specific implementation
// Accessing the Android-specific object instance (will be undefined if running on iOS)
// ``` JavaScript
// >> application-app-android
var androidApp = app.android;
// ```
// </snippet>
// <snippet module="application" title="application">
// ### Using the Android Application context
// ``` JavaScript
// << application-app-android
// >> application-app-android-context
var context = app.android.context;
//// get the Files (Documents) folder (directory)
var dir = context.getFilesDir();
// ```
// </snippet>
// <snippet module="application" title="application">
// ### Tracking the current Activity
// ``` JavaScript
// << application-app-android-context
// >> application-app-android-current
if (androidApp.foregroundActivity === androidApp.startActivity) {
////console.log("We are currently in the main (start) activity of the application");
}
// ```
// </snippet>
// <snippet module="application" title="application">
// ### Registering a Broadcast Receiver (Android)
// ``` JavaScript
// << application-app-android-current
// >> application-app-android-broadcast
//// Register the broadcast receiver
if (app.android) {
app.android.registerBroadcastReceiver(android.content.Intent.ACTION_BATTERY_CHANGED,
@ -45,8 +36,7 @@ if (app.android) {
if (app.android) {
app.android.unregisterBroadcastReceiver(android.content.Intent.ACTION_BATTERY_CHANGED);
}
// ```
// </snippet>
// << application-app-android-broadcast
export var testAndroidApplicationInitialized = function () {
TKUnit.assert(app.android, "Android application not initialized.");

View File

@ -5,9 +5,7 @@ import commonTests = require("./application-tests-common");
global.moduleMerge(commonTests, exports);
// <snippet module="application" title="application">
// ### Adding a Notification Observer (iOS)
// ``` JavaScript
// >> application-ios-observer
//// Add the notification observer
if (app.ios) {
var observer = app.ios.addNotificationObserver(UIDeviceBatteryLevelDidChangeNotification,
@ -21,5 +19,4 @@ if (app.ios) {
if (app.ios) {
app.ios.removeNotificationObserver(observer, UIDeviceBatteryLevelDidChangeNotification);
}
// ```
// </snippet>
// << application-ios-observer

32
apps/tests/application.md Normal file
View File

@ -0,0 +1,32 @@
---
nav-title: "application How-To"
title: "How-To"
description: "Examples for using application"
---
# Application
The Application module provides abstraction over the platform-specific Application implementations.
It is the main BCL module and is required for other BCL modules to work properly.
The default bootstrap.js implementation for each platform loads and initializes this module.
<snippet id='application-require'/>
The pre-required `app` module is used throughout the following code snippets.
### Checking the target platform
Use the following code in case you need to check somewhere in your code the platform you are running against:
<snippet id='application-app-check'/>
### Using the Android-specific implementation
Accessing the Android-specific object instance (will be undefined if running on iOS)
<snippet id='application-app-android'/>
### Using the Android Application context
<snippet id='application-app-android-context'/>
### Tracking the current Activity
<snippet id='application-app-android-current'/>
### Registering a Broadcast Receiver (Android)
<snippet id='application-app-android-broadcast'/>
### Adding a Notification Observer (iOS)
<snippet id='application-ios-observer'/>

View File

@ -1,20 +1,13 @@
import camera = require("camera");
// <snippet module="camera" title="camera">
// # Camera module
// Using a camera requires the camera module.
// ``` JavaScript
// >> camera-require
// var camera = require("camera");
// ```
// </snippet>
// << camera-require
export var test_takePicture = function () {
// <snippet module="camera" title="camera">
// ### Taking a picture.
// ``` JavaScript
// >> camera-take-picture
camera.takePicture().then(result => {
//// result is ImageSource
});
// ```
// </snippet>
// << camera-take-picture
};

11
apps/tests/camera.md Normal file
View File

@ -0,0 +1,11 @@
---
nav-title: "camera How-To"
title: "How-To"
description: "Examples for using camera"
---
# Camera module
Using a camera requires the camera module.
<snippet id='camera-require'/>
### Taking a picture.
<snippet id='camera-take-picture'/>

View File

@ -1,21 +1,14 @@
// <snippet module="color" title="color">
// # Color
// Using Colors requires the "color" module.
// ``` JavaScript
// >> color-require
import colorModule = require("color");
var Color = colorModule.Color;
// ```
// </snippet>
// << color-require
import TKUnit = require("./TKUnit");
export var test_Hex_Color = function () {
// <snippet module="color" title="color">
// ### Creating a Color from a hex value.
// ``` JavaScript
// >> color-hex
//// Creates the red color
var color = new Color("#FF0000");
// ```
// </snippet>
// << color-hex
TKUnit.assertEqual(color.a, 255, "Color.a not properly parsed");
TKUnit.assertEqual(color.r, 255, "Color.r not properly parsed");
TKUnit.assertEqual(color.g, 0, "Color.g not properly parsed");
@ -25,13 +18,10 @@ export var test_Hex_Color = function () {
}
export var test_ShortHex_Color = function () {
// <snippet module="color" title="color">
// ### Creating a Color from a short hex value.
// ``` JavaScript
// >> color-hex-short
//// Creates the color #FF8800
var color = new Color("#F80");
// ```
// </snippet>
// << color-hex-short
TKUnit.assertEqual(color.a, 255, "Color.a not properly parsed");
TKUnit.assertEqual(color.r, 255, "Color.r not properly parsed");
TKUnit.assertEqual(color.g, 136, "Color.g not properly parsed"); // 0x88 == 136
@ -41,13 +31,10 @@ export var test_ShortHex_Color = function () {
}
export var test_Argb_Color = function () {
// <snippet module="color" title="color">
// ### Creating a Color from four ARGB values
// ``` JavaScript
// >> color-rgb
//// Creates the color with 100 alpha, 255 red, 100 green, 100 blue
var color = new Color(100, 255, 100, 100);
// ```
// </snippet>
// << color-rgb
TKUnit.assertEqual(color.a, 100, "Color.a not properly parsed");
TKUnit.assertEqual(color.r, 255, "Color.r not properly parsed");
TKUnit.assertEqual(color.g, 100, "Color.g not properly parsed");
@ -57,14 +44,11 @@ export var test_Argb_Color = function () {
}
export var test_ArgbInt_Color = function () {
// <snippet module="color" title="color">
// ### Creating a Color from a single ARGB value
// ``` JavaScript
// >> color-rgb-single
//// Creates the color with 100 alpha, 100 red, 100 green, 100 blue
var argb = (100 << 24) | (100 << 16) | (100 << 8) | 100;
var color = new Color(argb);
// ```
// </snippet>
// << color-rgb-single
TKUnit.assertEqual(color.a, 100, "Color.a not properly parsed");
TKUnit.assertEqual(color.r, 100, "Color.r not properly parsed");
TKUnit.assertEqual(color.g, 100, "Color.g not properly parsed");

20
apps/tests/color.md Normal file
View File

@ -0,0 +1,20 @@
---
nav-title: "color How-To"
title: "How-To"
description: "Examples for using color"
---
# Color
Using Colors requires the "color" module.
<snippet id='color-require'/>
### Creating a Color from a hex value.
<snippet id='color-hex'/>
### Creating a Color from a short hex value.
<snippet id='color-hex-short'/>
### Creating a Color from four ARGB values
<snippet id='color-rgb'/>
### Creating a Color from a single ARGB value
<snippet id='color-rgb-single'/>

View File

@ -1,15 +1,9 @@
// <snippet module="connectivity" title="connectivity">
// # Connectivity
// Obtaining connectivity information requires the "connectivity" module.
// ``` JavaScript
// >> connectivity-require
import connectivity = require("connectivity");
// ```
// </snippet>
// << connectivity-require
export var test_DummyTestForSnippetOnly0 = function () {
// <snippet module="connectivity" title="connectivity">
// ### Getting connection type
// ``` JavaScript
// >> connectivity-type
var connectionType = connectivity.getConnectionType();
switch (connectionType) {
case connectivity.connectionType.none:
@ -22,14 +16,11 @@ export var test_DummyTestForSnippetOnly0 = function () {
////console.log("Mobile connection");
break;
}
// ```
// </snippet>
// << connectivity-type
}
export var test_DummyTestForSnippetOnly1 = function () {
// <snippet module="connectivity" title="connectivity">
// ### Monitoring connection type.
// ``` JavaScript
// >> connectivity-monitoring
connectivity.startMonitoring(function onConnectionTypeChanged(newConnectionType: number) {
switch (newConnectionType) {
case connectivity.connectionType.none:
@ -45,6 +36,5 @@ export var test_DummyTestForSnippetOnly1 = function () {
});
////...
connectivity.stopMonitoring();
// ```
// </snippet>
// << connectivity-monitoring
}

View File

@ -0,0 +1,14 @@
---
nav-title: "connectivity How-To"
title: "How-To"
description: "Examples for using connectivity"
---
# Connectivity
Obtaining connectivity information requires the "connectivity" module.
<snippet id='connectivity-require'/>
### Getting connection type
<snippet id='connectivity-type'/>
### Monitoring connection type.
<snippet id='connectivity-monitoring'/>

View File

@ -11,9 +11,9 @@ export var test_DummyTestForSnippetOnly1 = function () {
// >> console-time
console.time("LoadTime");
// << console-time
// >> console-timeEnd
// >> console-timeend
console.timeEnd("LoadTime");
// << console-timeEnd
// << console-timeend
}
export var test_DummyTestForSnippetOnly2 = function () {

View File

@ -14,7 +14,7 @@ Begins counting a time span for a given name (key).
<snippet id='console-time'/>
Ends a previously started time span through the time method.
<snippet id='console-timeEnd'/>
<snippet id='console-timeend'/>
### Assert
Asserts a boolean condition and prints a message in case the assert fails.

View File

@ -8,89 +8,77 @@ export var test_fetch_defined = function () {
export var test_fetch = function (done: (err: Error, res?: string) => void) {
var result;
// <snippet module="fetch" title="fetch">
// ### Get Response from URL
// ``` JavaScript
// >> fetch-response
fetch("https://httpbin.org/get").then(function (r) {
//// Argument (r) is Response!
// <hide>
// >> (hide)
TKUnit.assert(r instanceof Response, "Result from fetch() should be valid Response object! Actual result is: " + result);
done(null);
// </hide>
// << (hide)
}, function (e) {
//// Argument (e) is Error!
// <hide>
// >> (hide)
done(e);
// </hide>
// << (hide)
});
// ```
// </snippet>
// << fetch-response
};
export var test_fetch_text = function (done: (err: Error, res?: string) => void) {
var result;
// <snippet module="fetch" title="fetch">
// ### Get string from URL
// ``` JavaScript
// >> fetch-string'
fetch("https://httpbin.org/get").then(response => { return response.text(); }).then(function (r) {
//// Argument (r) is string!
// <hide>
// >> (hide)
TKUnit.assert(types.isString(r), "Result from text() should be string! Actual result is: " + r);
done(null);
// </hide>
// << (hide)
}, function (e) {
//// Argument (e) is Error!
// <hide>
// >> (hide)
done(e);
// </hide>
// << (hide)
});
// ```
// </snippet>
// << fetch-string'
};
export var test_fetch_json = function (done: (err: Error, res?: string) => void) {
var result;
// <snippet module="fetch" title="fetch">
// ### Get JSON from URL
// ``` JavaScript
// >> fetch-json
fetch("https://httpbin.org/get").then(response => { return response.json(); }).then(function (r) {
//// Argument (r) is JSON object!
// <hide>
// >> (hide)
TKUnit.assert(types.isString(JSON.stringify(r)), "Result from json() should be JSON object! Actual result is: " + r);
done(null);
// </hide>
// << (hide)
}, function (e) {
//// Argument (e) is Error!
// <hide>
// >> (hide)
done(e);
// </hide>
// << (hide)
});
// ```
// </snippet>
// << fetch-json
};
export var test_fetch_formData = function (done: (err: Error, res?: string) => void) {
var result;
// <snippet module="fetch" title="fetch">
// ### Get FormData from URL
// ``` JavaScript
// >> fetch-formdata
fetch("https://httpbin.org/get").then(response => { return response.formData(); }).then(function (r) {
//// Argument (r) is FormData object!
// <hide>
// >> (hide)
TKUnit.assert(r instanceof FormData, "Result from formData() should be FormData object! Actual result is: " + r);
done(null);
// </hide>
// << (hide)
}, function (e) {
//// Argument (e) is Error!
// <hide>
// >> (hide)
done(e);
// </hide>
// << (hide)
});
// ```
// </snippet>
// << fetch-formdata
};
export var test_fetch_fail_invalid_url = function (done) {
@ -105,13 +93,11 @@ export var test_fetch_fail_invalid_url = function (done) {
export var test_fetch_response_status = function (done) {
// <snippet module="fetch" title="fetch">
// ### Get Response status
// ``` JavaScript
// >> fetch-status-response
fetch("https://httpbin.org/get").then(function (response) {
//// Argument (response) is Response!
var statusCode = response.status;
// <hide>
// >> (hide)
try {
TKUnit.assert(types.isDefined(statusCode), "response.status should be defined! Actual result is: " + statusCode);
done(null);
@ -119,26 +105,23 @@ export var test_fetch_response_status = function (done) {
catch (err) {
done(err);
}
// </hide>
// << (hide)
}, function (e) {
//// Argument (e) is Error!
// <hide>
// >> (hide)
done(e);
// </hide>
// << (hide)
});
// ```
// </snippet>
// << fetch-status-response
};
export var test_fetch_response_headers = function (done) {
// <snippet module="fetch" title="fetch">
// ### Get response headers
// ``` JavaScript
// >> fetch-headers-response
fetch("https://httpbin.org/get").then(function (response) {
//// Argument (response) is Response!
// var all = response.headers.getAll();
// <hide>
// >> (hide)
try {
TKUnit.assert(types.isDefined(response.headers), "response.headers should be defined! Actual result is: " + response.headers);
done(null);
@ -146,15 +129,14 @@ export var test_fetch_response_headers = function (done) {
catch (err) {
done(err);
}
// </hide>
// << (hide)
}, function (e) {
//// Argument (e) is Error!
// <hide>
// >> (hide)
done(e);
// </hide>
// << (hide)
});
// ```
// </snippet>
// << fetch-headers-response
};
export var test_fetch_headers_sent = function (done) {
@ -202,15 +184,13 @@ export var test_fetch_post_form_data = function (done) {
};
export var test_fetch_post_json = function (done) {
// <snippet module="fetch" title="fetch">
// ### Post JSON
// ``` JavaScript
// >> fetch-post-json
fetch("https://httpbin.org/post", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ MyVariableOne: "ValueOne", MyVariableTwo: "ValueTwo" })
}).then(r => { return r.json(); }).then(function (r) {
// <hide>
// >> (hide)
try {
TKUnit.assert(r.json["MyVariableOne"] === "ValueOne" && r.json["MyVariableTwo"] === "ValueTwo", "Content not sent/received properly! Actual result is: " + r.json);
done(null);
@ -218,14 +198,13 @@ export var test_fetch_post_json = function (done) {
catch (err) {
done(err);
}
// </hide>
// << (hide)
// console.log(result);
}, function (e) {
// <hide>
// >> (hide)
done(e);
// </hide>
// << (hide)
// console.log("Error occurred " + e);
});
// ```
// </snippet>
// << fetch-post-json
};

25
apps/tests/fetch.md Normal file
View File

@ -0,0 +1,25 @@
---
nav-title: "fetch How-To"
title: "How-To"
description: "Examples for using fetch"
---
### Get Response from URL
<snippet id='fetch-response'/>
### Get string from URL
<snippet id='fetch-string'/>
### Get JSON from URL
<snippet id='fetch-json'/>
### Get FormData from URL
<snippet id='fetch-formdata'/>
### Get Response status
<snippet id='fetch-status-response'/>
### Get response headers
<snippet id='fetch-headers-response'/>
### Post JSON
<snippet id='fetch-post-json'/>

View File

@ -1,73 +1,50 @@
/* tslint:disable:no-unused-variable */
// <snippet module="file-system" title="file-system">
// # File System
// Using the file system requires the FileSystem module.
// ``` JavaScript
// >> file-system-require
import fs = require("file-system");
// ```
// The pre-required `fs` module is used throughout the following code snippets.
// </snippet>
// << file-system-require
import TKUnit = require("./TKUnit");
import appModule = require("application");
import platform = require("platform");
// <snippet module="file-system" title="file-system">
// ## Path
// </snippet>
export var testPathNormalize = function () {
// <snippet module="file-system" title="file-system">
// ### Normalize a Path
// ``` JavaScript
// >> file-system-normalize
var documents = fs.knownFolders.documents();
var testPath = "///test.txt";
//// Get a normalized path such as <folder.path>/test.txt from <folder.path>///test.txt
var normalizedPath = fs.path.normalize(documents.path + testPath);
// <hide>
// >> (hide)
var expected = documents.path + "/test.txt";
TKUnit.assert(normalizedPath === expected);
// </hide>
// ```
// </snippet>
// << (hide)
// << file-system-normalize
};
export var testPathJoin = function () {
// <snippet module="file-system" title="file-system">
// ### Path Join
// Concatenate a path to a file by providing multiple path arguments.
// ``` JavaScript
// >> file-system-multiple-args
var documents = fs.knownFolders.documents();
//// Generate a path like <documents.path>/myFiles/test.txt
var path = fs.path.join(documents.path, "myFiles", "test.txt");
// <hide>
// >> (hide)
var expected = documents.path + "/myFiles/test.txt";
TKUnit.assert(path === expected);
// </hide>
// ```
// </snippet>
// << (hide)
// << file-system-multiple-args
};
export var testPathSeparator = function () {
// <snippet module="file-system" title="file-system">
// ### Get the Path Separator
// ``` JavaScript
// >> file-system-separator
//// An OS dependent path separator, "\" or "/".
var separator = fs.path.separator;
// <hide>
// >> (hide)
var expected = "/";
TKUnit.assert(separator === expected);
// </hide>
// ```
// </snippet>
// << (hide)
// << file-system-separator
};
export var testFileFromPath = function () {
// <snippet module="file-system" title="file-system">
// ### Get or Create a File With Path
// The following example writes some text to a file created for path.
// It will create a new file or overwrite an existing file.
// ``` JavaScript
// >> file-system-create
var documents = fs.knownFolders.documents();
var path = fs.path.join(documents.path, "FileFromPath.txt");
var file = fs.File.fromPath(path);
@ -76,7 +53,7 @@ export var testFileFromPath = function () {
file.writeText("Something")
.then(function () {
//// Succeeded writing to the file.
// <hide>
// >> (hide)
file.readText()
.then(function (content) {
TKUnit.assert(content === "Something", "File read/write not working.");
@ -85,43 +62,31 @@ export var testFileFromPath = function () {
TKUnit.assert(false, "Failed to read/write text");
//console.dump(error);
});
// </hide>
// << (hide)
}, function (error) {
//// Failed to write to the file.
// <hide>
// >> (hide)
TKUnit.assert(false, "Failed to read/write text");
//console.dump(error);
// </hide>
// << (hide)
});
// ```
// </snippet>
// << file-system-create
}
export var testFolderFromPath = function () {
// <snippet module="file-system" title="file-system">
// ### Get or Create a Folder With Path
// ``` JavaScript
// >> file-system-create-folder
var path = fs.path.join(fs.knownFolders.documents().path, "music");
var folder = fs.Folder.fromPath(path);
// <hide>
// >> (hide)
TKUnit.assert(<any>folder, "Folder.getFolder API not working.");
TKUnit.assert(fs.Folder.exists(folder.path), "Folder.getFolder API not working.");
folder.remove();
// </hide>
// ```
// </snippet>
// << (hide)
// << file-system-create-folder
}
// <snippet module="file-system" title="file-system">
// ## Create
// </snippet>
export var testFileWrite = function () {
// <snippet module="file-system" title="file-system">
// ### Writing a string to a File
// The following example writes some text to a file.
// It will create a new file or overwrite an existing file.
// ``` JavaScript
// >> file-system-write-string
var documents = fs.knownFolders.documents();
var file = documents.getFile("Test_Write.txt");
@ -129,7 +94,7 @@ export var testFileWrite = function () {
file.writeText("Something")
.then(function () {
//// Succeeded writing to the file.
// <hide>
// >> (hide)
file.readText()
.then(function (content) {
TKUnit.assert(content === "Something", "File read/write not working.");
@ -138,57 +103,43 @@ export var testFileWrite = function () {
TKUnit.assert(false, "Failed to read/write text");
//console.dump(error);
});
// </hide>
// << (hide)
}, function (error) {
//// Failed to write to the file.
// <hide>
// >> (hide)
TKUnit.assert(false, "Failed to read/write text");
//console.dump(error);
// </hide>
// << (hide)
});
// ```
// </snippet>
// << file-system-write-string
};
export var testGetFile = function () {
// <snippet module="file-system" title="file-system">
// ### Get or Create a File
// ``` JavaScript
// >> file-system-create-file
var documents = fs.knownFolders.documents();
var file = documents.getFile("NewFileToCreate.txt");
// <hide>
// >> (hide)
TKUnit.assert(<any>file, "File.getFile API not working.");
TKUnit.assert(fs.File.exists(file.path), "File.getFile API not working.");
file.remove();
// </hide>
// ```
// </snippet>
// << (hide)
// << file-system-create-file
}
export var testGetFolder = function () {
// <snippet module="file-system" title="file-system">
// ### Get or Create a Folder
// ``` JavaScript
// >> file-system-get-folder
var documents = fs.knownFolders.documents();
var folder = documents.getFolder("NewFolderToCreate");
// <hide>
// >> (hide)
TKUnit.assert(<any>folder, "Folder.getFolder API not working.");
TKUnit.assert(fs.Folder.exists(folder.path), "Folder.getFolder API not working.");
folder.remove();
// </hide>
// ```
// </snippet>
// << (hide)
// << file-system-get-folder
};
// <snippet module="file-system" title="file-system">
// ## Read
// </snippet>
export var testFileRead = function () {
// <snippet module="file-system" title="file-system">
// ### Reading from a File
// The following example writes some text to a file and then reads it back.
// ``` JavaScript
// >> file-system-example-text
var documents = fs.knownFolders.documents();
var myFile = documents.getFile("Test_Write.txt");
@ -202,33 +153,30 @@ export var testFileRead = function () {
myFile.readText()
.then(function (content) {
//// Successfully read the file's content.
// <hide>
// >> (hide)
written = content === "Something";
TKUnit.assert(written, "File read/write not working.");
myFile.remove();
// </hide>
// << (hide)
}, function (error) {
//// Failed to read from the file.
// <hide>
// >> (hide)
TKUnit.assert(false, "Failed to read/write text");
//console.dump(error);
// </hide>
// << (hide)
});
}, function (error) {
//// Failed to write to the file.
// <hide>
// >> (hide)
TKUnit.assert(false, "Failed to read/write text");
//console.dump(error);
// </hide>
// << (hide)
});
// ```
// </snippet>
// << file-system-example-text
};
export var testFileReadWriteBinary = function () {
// <snippet module="file-system" title="file-system">
// ### Reading/writing binary data from/to a File
// ``` JavaScript
// >> file-system-read-binary
var fileName = "logo.png";
var error;
@ -239,7 +187,7 @@ export var testFileReadWriteBinary = function () {
destinationFile.writeSync(source, e=> { error = e; });
// <hide>
// >> (hide)
var destination = destinationFile.readSync(e=> { error = e; });
TKUnit.assertNull(error);
if (platform.device.os === platform.platformNames.ios) {
@ -249,39 +197,31 @@ export var testFileReadWriteBinary = function () {
}
destinationFile.removeSync();
// </hide>
// ```
// </snippet>
// << (hide)
// << file-system-read-binary
};
export var testGetKnownFolders = function () {
// <snippet module="file-system" title="file-system">
// ### Getting the Known Folders
// Each app has several well known folders. This is how to access them:
// ``` JavaScript
// >> file-system-known-folders
//// Getting the application's 'documents' folder.
var documents = fs.knownFolders.documents();
// <hide>
// >> (hide)
TKUnit.assert(<any>documents, "Could not retrieve the Documents known folder.");
TKUnit.assert(documents.isKnown, "The Documents folder should have its isKnown property set to true.");
// </hide>
// << (hide)
//// Getting the application's 'temp' folder.
var temp = fs.knownFolders.temp();
// <hide>
// >> (hide)
TKUnit.assert(<any>temp, "Could not retrieve the Temporary known folder.");
TKUnit.assert(temp.isKnown, "The Temporary folder should have its isKnown property set to true.");
// </hide>
// ```
// </snippet>
// << (hide)
// << file-system-known-folders
};
export var testGetEntities = function () {
// <snippet module="file-system" title="file-system">
// ### Getting Folder Contents
// Getting all files and folders within a folder:
// ``` JavaScript
// >> file-system-folders-content
var documents = fs.knownFolders.documents();
// <hide>
// >> (hide)
var file = documents.getFile("Test.txt");
var file1 = documents.getFile("Test1.txt");
@ -300,37 +240,32 @@ export var testGetEntities = function () {
}
};
// </hide>
// << (hide)
documents.getEntities()
.then(function (entities) {
//// entities is array with the document's files and folders.
entities.forEach(function (entity) {
console.log(entity.name);
});
// <hide>
// >> (hide)
TKUnit.assert(fileFound, "Failed to enumerate Test.txt");
TKUnit.assert(file1Found, "Failed to enumerate Test1.txt");
file.remove();
file1.remove();
// </hide>
// << (hide)
}, function (error) {
//// Failed to obtain folder's contents.
// globalConsole.error(error.message);
});
// ```
// </snippet>
// << file-system-folders-content
};
export var testEnumEntities = function () {
// <snippet module="file-system" title="file-system">
// ### Enumerating Folder Contents
// Getting all folder entities in array may be slow with large number of files.
// Enumerating the folder entities would iterate the files one by one without blocking the UI.
// ``` JavaScript
// >> file-system-enum-content
var documents = fs.knownFolders.documents();
// <hide>
// >> (hide)
var file = documents.getFile("Test.txt");
var file1 = documents.getFile("Test1.txt");
var testFolder = documents.getFolder("testFolder");
@ -348,13 +283,13 @@ export var testEnumEntities = function () {
}
}
}
// </hide>
// << (hide)
documents.eachEntity(function (entity) {
console.log(entity.name);
//// Return true to continue, or return false to stop the iteration.
return true;
});
// <hide>
// >> (hide)
TKUnit.assert(fileFound, "Failed to enumerate Test.txt");
TKUnit.assert(file1Found, "Failed to enumerate Test1.txt");
TKUnit.assert(testFolderFound, "Failed to enumerate testFolder");
@ -362,79 +297,66 @@ export var testEnumEntities = function () {
file.remove();
file1.remove();
testFolder.remove();
// </hide>
// ```
// </snippet>
// << (hide)
// << file-system-enum-content
};
export var testGetParent = function () {
// <snippet module="file-system" title="file-system">
// ### Getting Parent Folder
// ``` JavaScript
// >> file-system-parent
var documents = fs.knownFolders.documents();
var file = documents.getFile("Test.txt");
// <hide>
// >> (hide)
TKUnit.assert(<any>file, "Failed to create file in the Documents folder.");
// </hide>
// << (hide)
//// The parent folder of the file would be the documents folder.
var parent = file.parent;
// <hide>
// >> (hide)
TKUnit.assert(documents === parent, "The parent folder should be the Documents folder.");
file.remove();
// </hide>
// ```
// </snippet>
// << (hide)
// << file-system-parent
};
export var testFileNameExtension = function () {
// <snippet module="file-system" title="file-system">
// ### Getting File Name and Extension
// ``` JavaScript
// >> file-system-extension
var documents = fs.knownFolders.documents();
var file = documents.getFile("Test.txt");
//// Getting the file name "Test.txt".
var fileName = file.name;
//// Getting the file extension ".txt".
var fileExtension = file.extension;
// <hide>
// >> (hide)
TKUnit.assert(fileName === "Test.txt", "Wrong file name.");
TKUnit.assert(fileExtension === ".txt", "Wrong extension.");
file.remove();
// </hide>
// ```
// </snippet>
// << (hide)
// << file-system-extension
};
export var testFileExists = function () {
// <snippet module="file-system" title="file-system">
// ### Checking if a File Exists
// ``` JavaScript
// >> file-system-fileexists
var documents = fs.knownFolders.documents();
var file = documents.getFile("Test.txt");
var exists = fs.File.exists(file.path);
// <hide>
// >> (hide)
TKUnit.assert(exists, "File.exists API not working.");
exists = fs.File.exists(file.path + "_");
TKUnit.assert(!exists, "File.exists API not working.");
file.remove();
// </hide>
// ```
// </snippet>
// << (hide)
// << file-system-fileexists
};
export var testFolderExists = function () {
// <snippet module="file-system" title="file-system">
// ### Checking if a Folder Exists
// ``` JavaScript
// >> file-system-folderexists
var documents = fs.knownFolders.documents();
var exists = fs.Folder.exists(documents.path);
// <hide>
// >> (hide)
TKUnit.assert(exists, "Folder.exists API not working.");
exists = fs.Folder.exists(documents.path + "_");
TKUnit.assert(!exists, "Folder.exists API not working.");
// </hide>
// ```
// </snippet>
// << (hide)
// << file-system-folderexists
};
export var testContainsFile = function () {
@ -449,143 +371,118 @@ export var testContainsFile = function () {
file.remove();
};
// <snippet module="file-system" title="file-system">
// ## Update
// </snippet>
export var testFileRename = function () {
// <snippet module="file-system" title="file-system">
// ### Renaming a File
// ``` JavaScript
// >> file-system-renaming
var documents = fs.knownFolders.documents();
var file = documents.getFile("Test.txt");
file.rename("Test_renamed.txt")
.then(function (result) {
//// Successfully Renamed.
// <hide>
// >> (hide)
TKUnit.assert(file.name === "Test_renamed.txt", "File.rename API not working.");
file.remove();
documents.getFile("Test.txt").remove();
// </hide>
// << (hide)
}, function (error) {
//// Failed to rename the file.
// <hide>
// >> (hide)
TKUnit.assert(false, "Failed to rename file");
// </hide>
// << (hide)
});
// ```
// </snippet>
// << file-system-renaming
};
export var testFolderRename = function () {
// <snippet module="file-system" title="file-system">
// ### Renaming a Folder
// ``` JavaScript
// >> file-system-renaming-folder
var folder = fs.knownFolders.documents();
var myFolder = folder.getFolder("Test__");
myFolder.rename("Something")
.then(function (result) {
//// Successfully Renamed.
// <hide>
// >> (hide)
TKUnit.assert(myFolder.name === "Something", "Folder.rename API not working.");
myFolder.remove();
folder.getFolder("Test__").remove();
// </hide>
// << (hide)
}, function (error) {
//// Failed to rename the folder.
// <hide>
// >> (hide)
TKUnit.assert(false, "Folder.rename API not working.");
// </hide>
// << (hide)
});
// ```
// </snippet>
// << file-system-renaming-folder
};
// <snippet module="file-system" title="file-system">
// ## Delete
// </snippet>
export var testFileRemove = function () {
// <snippet module="file-system" title="file-system">
// ### Removing a File
// To 'delete', 'remove' or 'unlink' a file use the file's remove method:
// ``` JavaScript
// >> file-system-remove-file
var documents = fs.knownFolders.documents();
var file = documents.getFile("AFileToRemove.txt");
file.remove()
.then(function (result) {
//// Success removing the file.
// <hide>
// >> (hide)
TKUnit.assert(!fs.File.exists(file.path));
// </hide>
// << (hide)
}, function (error) {
//// Failed to remove the file.
// <hide>
// >> (hide)
TKUnit.assert(false, "File.remove API not working.");
// </hide>
// << (hide)
});
// ```
// </snippet>
// << file-system-remove-file
};
export var testFolderRemove = function () {
// <snippet module="file-system" title="file-system">
// ### Removing a Folder
// ``` JavaScript
// >> file-system-remove-folder
var documents = fs.knownFolders.documents();
var file = documents.getFolder("AFolderToRemove");
//// Remove a folder and recursively its content.
file.remove()
.then(function (result) {
//// Success removing the folder.
// <hide>
// >> (hide)
TKUnit.assert(!fs.File.exists(file.path));
// </hide>
// << (hide)
}, function (error) {
//// Failed to remove the folder.
// <hide>
// >> (hide)
TKUnit.assert(false, "File.remove API not working.");
// </hide>
// << (hide)
});
// ```
// </snippet>
// << file-system-remove-folder
}
export var testFolderClear = function () {
// <snippet module="file-system" title="file-system">
// ### Clearing the Contents of a Folder
// The clear method removes all files within a folder.
// ``` JavaScript
// >> file-system-clear-folder
var documents = fs.knownFolders.documents();
var folder = documents.getFolder("testFolderEmpty");
// <hide>
// >> (hide)
folder.getFile("Test1.txt");
folder.getFile("Test2.txt");
var emptied;
// </hide>
// << (hide)
folder.clear()
.then(function () {
//// Successfully cleared the folder.
// <hide>
// >> (hide)
emptied = true;
// </hide>
// << (hide)
}, function (error) {
//// Failed to clear the folder.
// <hide>
// >> (hide)
TKUnit.assert(false, error.message);
// </hide>
// << (hide)
});
// <hide>
// >> (hide)
folder.getEntities()
.then(function (entities) {
TKUnit.assert(entities.length === 0, "Failed to clear a Folder");
folder.remove();
});
// </hide>
// ```
// </snippet>
// << (hide)
// << file-system-clear-folder
};
// misc

91
apps/tests/file-system.md Normal file
View File

@ -0,0 +1,91 @@
---
nav-title: "file-system How-To"
title: "How-To"
description: "Examples for using file-system"
---
# File System
Using the file system requires the FileSystem module.
<snippet id='file-system-require'/>
The pre-required `fs` module is used throughout the following code snippets.
## Path
### Normalize a Path
<snippet id='file-system-normalize'/>
### Path Join
Concatenate a path to a file by providing multiple path arguments.
<snippet id='file-system-multiple-args'/>
### Get the Path Separator
<snippet id='file-system-separator'/>
### Get or Create a File With Path
The following example writes some text to a file created for path.
It will create a new file or overwrite an existing file.
<snippet id='file-system-create'/>
### Get or Create a Folder With Path
<snippet id='file-system-create-folder'/>
## Create
### Writing a string to a File
The following example writes some text to a file.
It will create a new file or overwrite an existing file.
<snippet id='file-system-write-string'/>
### Get or Create a File
<snippet id='file-system-create-file'/>
### Get or Create a Folder
<snippet id='file-system-get-folder'/>
## Read
### Reading from a File
The following example writes some text to a file and then reads it back.
<snippet id='file-system-example-text'/>
### Reading/writing binary data from/to a File
<snippet id='file-system-read-binary'/>
### Getting the Known Folders
Each app has several well known folders. This is how to access them:
<snippet id='file-system-known-folders'/>
### Getting Folder Contents
Getting all files and folders within a folder:
<snippet id='file-system-folders-content'/>
### Enumerating Folder Contents
Getting all folder entities in array may be slow with large number of files.
Enumerating the folder entities would iterate the files one by one without blocking the UI.
<snippet id='file-system-enum-content'/>
### Getting Parent Folder
<snippet id='file-system-parent'/>
### Getting File Name and Extension
<snippet id='file-system-extension'/>
### Checking if a File Exists
<snippet id='file-system-fileexists'/>
### Checking if a Folder Exists
<snippet id='file-system-folderexists'/>
## Update
### Renaming a File
<snippet id='file-system-renaming'/>
### Renaming a Folder
<snippet id='file-system-renaming-folder'/>
## Delete
### Removing a File
To 'delete', 'remove' or 'unlink' a file use the file's remove method:
<snippet id='file-system-remove-file'/>
### Removing a Folder
<snippet id='file-system-remove-folder'/>
### Clearing the Contents of a Folder
The clear method removes all files within a folder.
<snippet id='file-system-clear-folder'/>

View File

@ -1,15 +1,9 @@
// <snippet module="fps-meter" title="fps-meter">
// # Frames-per-second meter
// Logging frames-per-second statistics for your app requires the "fps-meter" module.
// ``` JavaScript
// >> fps-meter-require
import fpsMeter = require("fps-meter");
// ```
// </snippet>
// << fps-meter-require
export var test_DummyTestForSnippetOnly0 = function () {
// <snippet module="fps-meter" title="fps-meter">
// ### Start and stop logging
// ``` JavaScript
// >> fps-meter-logging
var callbackId = fpsMeter.addCallback(function (fps: number, minFps: number) {
console.info("fps=" + fps + " minFps=" + minFps);
});
@ -17,6 +11,5 @@ export var test_DummyTestForSnippetOnly0 = function () {
////...
fpsMeter.removeCallback(callbackId);
fpsMeter.stop();
// ```
// </snippet>
// << fps-meter-logging
}

11
apps/tests/fps-meter.md Normal file
View File

@ -0,0 +1,11 @@
---
nav-title: "fps-meter How-To"
title: "How-To"
description: "Examples for using fps-meter"
---
# Frames-per-second meter
Logging frames-per-second statistics for your app requires the "fps-meter" module.
<snippet id='fps-meter-require'/>
### Start and stop logging
<snippet id='fps-meter-logging'/>

View File

@ -5,13 +5,9 @@ import types = require("utils/types");
import fs = require("file-system");
require("globals");
// <snippet module="http" title="http">
// # Http module
// Using http methods requires to load "http" module.
// ``` JavaScript
// >> http-require
// var http = require("http");
// ```
// </snippet>
// << http-require
export var test_getString_isDefined = function () {
TKUnit.assert(typeof (http.getString) !== "undefined", "Method http.getString() should be defined!");
@ -20,23 +16,20 @@ export var test_getString_isDefined = function () {
export var test_getString = function (done: (err: Error, res?: string) => void) {
var result;
// <snippet module="http" title="http">
// ### Get string from URL
// ``` JavaScript
// >> http-get-string
http.getString("https://httpbin.org/get").then(function (r) {
//// Argument (r) is string!
// <hide>
// >> (hide)
result = r;
done(null);
// </hide>
// << (hide)
}, function (e) {
//// Argument (e) is Error!
// <hide>
// >> (hide)
done(e);
// </hide>
// << (hide)
});
// ```
// </snippet>
// << http-get-string
};
export var test_getString_fail = function (done) {
@ -73,12 +66,10 @@ export var test_getJSON_isDefined = function () {
export var test_getJSON = function (done) {
var result;
// <snippet module="http" title="http">
// ### Get JSON from URL
// ``` JavaScript
// >> http-get-json
http.getJSON("https://httpbin.org/get").then(function (r) {
//// Argument (r) is JSON!
// <hide>
// >> (hide)
//completed = true;
result = r;
try {
@ -89,16 +80,15 @@ export var test_getJSON = function (done) {
done(e);
}
done(null);
// </hide>
// << (hide)
}, function (e) {
//// Argument (e) is Error!
//console.log(e);
// <hide>
// >> (hide)
done(e);
// </hide>
// << (hide)
});
// ```
// </snippet>
// << http-get-json
};
export var test_getJSON_fail = function (done) {
@ -171,12 +161,10 @@ export var test_getImage_isDefined = function () {
export var test_getImage = function (done) {
var result;
// <snippet module="http" title="http">
// ### Get Image from URL
// ``` JavaScript
// >> http-get-image
http.getImage("https://httpbin.org/image/png").then(function (r) {
//// Argument (r) is Image!
// <hide>
// >> (hide)
result = r;
try {
TKUnit.assert(result instanceof require("image-source").ImageSource, "Result from getImage() should be valid ImageSource object!");
@ -185,15 +173,14 @@ export var test_getImage = function (done) {
catch (err) {
done(err);
}
// </hide>
// << (hide)
}, function (e) {
//// Argument (e) is Error!
// <hide>
// >> (hide)
done(e);
// </hide>
// << (hide)
});
// ```
// </snippet>
// << http-get-image
};
export var test_getImage_fail = function (done) {
@ -233,12 +220,10 @@ export var test_getFile_isDefined = function () {
export var test_getFile = function (done) {
var result;
// <snippet module="http" title="http">
// ### Get File from URL. By default the file will be saved in Documents folder.
// ``` JavaScript
// >> http-get-urlfile
http.getFile("https://raw.githubusercontent.com/NativeScript/NativeScript/master/apps/tests/logo.png").then(function (r) {
//// Argument (r) is File!
// <hide>
// >> (hide)
result = r;
try {
TKUnit.assert(result instanceof fs.File, "Result from getFile() should be valid File object!");
@ -247,27 +232,24 @@ export var test_getFile = function (done) {
catch (err) {
done(err);
}
// </hide>
// << (hide)
}, function (e) {
//// Argument (e) is Error!
// <hide>
// >> (hide)
done(e);
// </hide>
// << (hide)
});
// ```
// </snippet>
// << http-get-urlfile
};
export var test_getContentAsFile = function (done) {
var result;
// <snippet module="http" title="http">
// ### Get content as File from URL. You can specify where the file should be saved.
// ``` JavaScript
// >> http-get-urlfile-content
var filePath = fs.path.join(fs.knownFolders.documents().path, "test.png");
http.getFile("https://httpbin.org/image/png", filePath).then(function (r) {
//// Argument (r) is File!
// <hide>
// >> (hide)
result = r;
try {
TKUnit.assert(result instanceof fs.File, "Result from getFile() should be valid File object!");
@ -276,15 +258,14 @@ export var test_getContentAsFile = function (done) {
catch (err) {
done(err);
}
// </hide>
// << (hide)
}, function (e) {
//// Argument (e) is Error!
// <hide>
// >> (hide)
done(e);
// </hide>
// << (hide)
});
// ```
// </snippet>
// << http-get-urlfile-content
};
export var test_getFile_fail = function (done) {
@ -338,13 +319,11 @@ export var test_request_requestShouldTimeout = function (done) {
export var test_request_responseStatusCodeShouldBeDefined = function (done) {
var result: http.HttpResponse;
// <snippet module="http" title="http">
// ### Get response status code
// ``` JavaScript
// >> http-get-response
http.request({ url: "https://httpbin.org/get", method: "GET" }).then(function (response) {
//// Argument (response) is HttpResponse!
var statusCode = response.statusCode;
// <hide>
// >> (hide)
result = response;
try {
TKUnit.assert(typeof (result.statusCode) !== "undefined", "response.statusCode should be defined!");
@ -353,29 +332,26 @@ export var test_request_responseStatusCodeShouldBeDefined = function (done) {
catch (err) {
done(err);
}
// </hide>
// << (hide)
}, function (e) {
//// Argument (e) is Error!
// <hide>
// >> (hide)
done(e);
// </hide>
// << (hide)
});
// ```
// </snippet>
// << http-get-response
};
export var test_request_responseHeadersShouldBeDefined = function (done) {
var result: http.HttpResponse;
// <snippet module="http" title="http">
// ### Get response headers
// ``` JavaScript
// >> http-get-response-headers
http.request({ url: "https://httpbin.org/get", method: "GET" }).then(function (response) {
//// Argument (response) is HttpResponse!
//for (var header in response.headers) {
// console.log(header + ":" + response.headers[header]);
//}
// <hide>
// >> (hide)
result = response;
try {
TKUnit.assert(typeof (result.headers) !== "undefined", "response.headers should be defined!");
@ -384,30 +360,27 @@ export var test_request_responseHeadersShouldBeDefined = function (done) {
catch (err) {
done(err);
}
// </hide>
// << (hide)
}, function (e) {
//// Argument (e) is Error!
// <hide>
// >> (hide)
done(e);
// </hide>
// << (hide)
});
// ```
// </snippet>
// << http-get-response-headers
};
export var test_request_responseContentShouldBeDefined = function (done) {
var result: http.HttpResponse;
// <snippet module="http" title="http">
// ### Get response content
// ``` JavaScript
// >> http-get-response-content
http.request({ url: "https://httpbin.org/get", method: "GET" }).then(function (response) {
//// Argument (response) is HttpResponse!
//// Content property of the response is HttpContent!
var str = response.content.toString();
var obj = response.content.toJSON();
var img = response.content.toImage();
// <hide>
// >> (hide)
result = response;
try {
TKUnit.assert(typeof (result.content) !== "undefined", "response.content should be defined!");
@ -416,15 +389,14 @@ export var test_request_responseContentShouldBeDefined = function (done) {
catch (err) {
done(err);
}
// </hide>
// << (hide)
}, function (e) {
//// Argument (e) is Error!
// <hide>
// >> (hide)
done(e);
// </hide>
// << (hide)
});
// ```
// </snippet>
// << http-get-response-content
};
export var test_request_responseContentToStringShouldReturnString = function (done) {
@ -629,9 +601,7 @@ export var test_request_NonStringHeadersSentAndReceivedProperly = function (done
};
export var test_request_jsonAsContentSentAndReceivedProperly = function (done) {
// <snippet module="http" title="http">
// ### Post JSON
// ``` JavaScript
// >> http-post-json
var result;
http.request({
@ -641,7 +611,7 @@ export var test_request_jsonAsContentSentAndReceivedProperly = function (done) {
content: JSON.stringify({ MyVariableOne: "ValueOne", MyVariableTwo: "ValueTwo" })
}).then(function (response) {
// result = response.content.toJSON();
// <hide>
// >> (hide)
result = response.content.toJSON();
try {
TKUnit.assert(result["json"]["MyVariableOne"] === "ValueOne" && result["json"]["MyVariableTwo"] === "ValueTwo", "Content not sent/received properly!");
@ -650,14 +620,13 @@ export var test_request_jsonAsContentSentAndReceivedProperly = function (done) {
catch (err) {
done(err);
}
// </hide>
// << (hide)
// console.log(result);
}, function (e) {
// <hide>
// >> (hide)
done(e);
// </hide>
// << (hide)
// console.log("Error occurred " + e);
});
// ```
// </snippet>
// << http-post-json
};

35
apps/tests/http.md Normal file
View File

@ -0,0 +1,35 @@
---
nav-title: "http How-To"
title: "How-To"
description: "Examples for using http"
---
# Http module
Using http methods requires to load "http" module.
<snippet id='http-require'/>
### Get string from URL
<snippet id='http-get-string'/>
### Get JSON from URL
<snippet id='http-get-json'/>
### Get Image from URL
<snippet id='http-get-image'/>
### Get File from URL. By default the file will be saved in Documents folder.
<snippet id='http-get-urlfile'/>
### Get content as File from URL. You can specify where the file should be saved.
<snippet id='http-get-urlfile-content'/>
### Get response status code
<snippet id='http-get-response'/>
### Get response headers
<snippet id='http-get-response-headers'/>
### Get response content
<snippet id='http-get-response-content'/>
### Post JSON
<snippet id='http-post-json'/>

View File

@ -1,16 +1,10 @@
// <snippet module="image-source" title="image-source">
// # Image source
// Using the image source requires the image-source module.
// ``` JavaScript
//var imageSource = require("image-source");
// ```
// The pre-required `imageSource` module is used throughout the following code snippets.
// We also use fs module defined as follows:
// ``` JavaScript
//var fs = require("file-system");
// ```
// ## Loading and saving images
// </snippet>
// >> imagesource-require
// var imageSource = require("image-source");
// << imagesource-require
// >> imagesource-require-alt
// var fs = require("file-system");
// << imagesource-require-alt
import imageSource = require("image-source");
import fs = require("file-system");
@ -24,13 +18,9 @@ var smallImagePath = fs.path.join(__dirname, "/small-image.png");
/* TODO: We need a way to programmatically add an image to resources and then load it from, otherwise we do not know if there is such resource in the target native app.
export function testFromResource() {
// <snippet module="image-source" title="image-source">
// ### Load image using resource name
// This is similar to loading Bitmap from `R.drawable.logo` on Android or calling `[UIImage imageNamed@"logo"]` on iOS
// ``` JavaScript
// >> imagesource-resname
var img = imageSource.fromResource("logo");
// ```
// </snippet>
// << imagesource-resname
TKUnit.assert(img.height > 0, "image.fromResource failed");
}
*/
@ -38,13 +28,11 @@ export function testFromUrl(done) {
//var completed;
var result: imageSource.ImageSource;
// <snippet module="image-source" title="image-source">
// ### Load image from URL
// ``` JavaScript
// >> imagesource-load-url
imageSource.fromUrl("https://www.google.com/images/errors/logo_sm_2.png")
.then(function (res: imageSource.ImageSource) {
//console.log("Image successfully loaded");
// <hide>
// >> (hide)
//completed = true;
result = res;
try {
@ -55,41 +43,34 @@ export function testFromUrl(done) {
catch (e) {
done(e);
}
// </hide>
// << (hide)
}, function (error) {
//console.log("Error loading image: " + error);
// <hide>
// >> (hide)
//completed = true;
done(error);
// </hide>
// << (hide)
});
// ```
// </snippet>
// << imagesource-load-url
}
export function testSaveToFile() {
// <snippet module="image-source" title="image-source">
// ### Save image source to PNG or JPG file
// ``` JavaScript
// >> imagesource-save-to
var img = imageSource.fromFile(imagePath);
var folder = fs.knownFolders.documents();
var path = fs.path.join(folder.path, "Test.png");
var saved = img.saveToFile(path, enums.ImageFormat.png);
// ```
// </snippet>
// << imagesource-save-to
TKUnit.assert(saved, "Image not saved to file");
TKUnit.assert(fs.File.exists(path), "Image not saved to file");
}
export function testFromFile() {
// <snippet module="image-source" title="image-source">
// ### Load image from a local file
// ``` JavaScript
// >> imagesource-load-local
var folder = fs.knownFolders.documents();
var path = fs.path.join(folder.path, "Test.png");
var img = imageSource.fromFile(path);
// ```
// </snippet>
// << imagesource-load-local
TKUnit.assert(img.height > 0, "image.fromResource failed");

View File

@ -0,0 +1,25 @@
---
nav-title: "image-source How-To"
title: "How-To"
description: "Examples for using image-source"
---
# Image source
Using the image source requires the image-source module.
<snippet id='imagesource-require'/>
The pre-required `imageSource` module is used throughout the following code snippets.
We also use fs module defined as follows:
<snippet id='imagesource-require-alt'/>
## Loading and saving images
### Load image using resource name
This is similar to loading Bitmap from `R.drawable.logo` on Android or calling `[UIImage imageNamed@"logo"]` on iOS
<snippet id='imagesource-resname'/>
### Load image from URL
<snippet id='imagesource-load-url'/>
### Save image source to PNG or JPG file
<snippet id='imagesource-save-to'/>
### Load image from a local file
<snippet id='imagesource-load-local'/>

View File

@ -1,10 +1,6 @@
// <snippet module="location" title="location">
// # Location
// Using the location requires the Location module.
// ``` JavaScript
// >> location-require
import locationModule = require("location");
// ```
// </snippet>
// << location-require
import TKUnit = require("./TKUnit");
@ -21,29 +17,20 @@ export function tearDown() {
locationIsEnabled = undefined;
}
// <snippet module="location" title="location">
// ## Other functions
// </snippet>
export var testIsEnabled = function () {
if (!locationIsEnabled) {
console.log("Location service is not enabled!!!");
return;
}
// <snippet module="location" title="location">
// ### Test are location services available for this device
// ``` JavaScript
// >> location-funcs
//var LocationManager = require("location").LocationManager;
var isEnabled = LocationManager.isEnabled();
// ```
// </snippet>
// << location-funcs
TKUnit.assert(isEnabled);
};
export var testDistance = function () {
// <snippet module="location" title="location">
// ### Get distance between two locations
// ``` JavaScript
// >> location-distance
//var Location = require("location").Location;
var locSofia = new Location();
locSofia.longitude = 42.696552;
@ -52,15 +39,10 @@ export var testDistance = function () {
locNewYork.longitude = 40.71448;
locNewYork.latitude = -74.00598;
var distance = LocationManager.distance(locSofia, locNewYork);
// ```
// </snippet>
// << location-distance
TKUnit.assert((distance > 10780000) && (distance < 10860000), "invalid distance " + distance);
};
// <snippet module="location" title="location">
// ## Getting location
// </snippet>
export var testLocation = function (done) {
if (!locationIsEnabled) {
done(null);
@ -68,15 +50,13 @@ export var testLocation = function (done) {
var locationReceived;
// <snippet module="location" title="location">
// ### Receive continuous location updates
// ``` JavaScript
// >> location-updates
//var LocationManager = require("location").LocationManager;
var locationManager = new LocationManager();
locationManager.startLocationMonitoring(function (location) {
//console.log('Location received: ' + location);
// <hide>
// >> (hide)
locationReceived = true;
locationManager.stopLocationMonitoring();
try {
@ -86,19 +66,18 @@ export var testLocation = function (done) {
catch (e) {
done(e);
}
// </hide>
// << (hide)
}, function (error) {
//console.log('Location error received: ' + error);
// <hide>
// >> (hide)
locationReceived = error;
locationManager.stopLocationMonitoring();
done(error);
// </hide>
// << (hide)
}
);
// ```
// </snippet>
// << location-updates
//var isReady = function () {
// return locationReceived;
//}
@ -116,14 +95,11 @@ export var testLastKnownLocation = function () {
}
TKUnit.waitUntilReady(function () { return false; }, 1); // give it some time after the last test
// <snippet module="location" title="location">
// ### Get last known location
// ``` JavaScript
//var LocationManager = require("location").LocationManager;
// >> location-last-known
// var LocationManager = require("location").LocationManager;
var locationManager = new LocationManager();
var lastKnownLocation = locationManager.lastKnownLocation;
// ```
// </snippet>
// << location-last-known
TKUnit.assert((lastKnownLocation != null), "There is no last known location");
};
@ -179,27 +155,21 @@ export var testSnippet = function (done) {
return done(null);
}
var locationReceived;
// <snippet module="location" title="location">
// ### Get location once
// if there is `options.timeout` you will receive error on timeout. If `options.timeout` is 0 then the result is the same as the result from `LocationManager.lastKnownLocation`
// and there will be no wait. You can use `options.maximumAge` to specify you don't want to receive locations older than specified time in ms.
//
// ``` JavaScript
// >> location-timeour
// var locationModule = require("location");
//// options can also look like { maximumAge: 2000, timeout: 20 * 1000 }
locationModule.getLocation({ maximumAge: 30000, timeout: 0 }).then(function (location) {
//console.log('Location received: ' + location);
// <hide>
// >> (hide)
locationReceived = true;
done(null);
// </hide>
// << (hide)
}, function (error) {
//console.log('Location error received: ' + error);
// <hide>
// >> (hide)
locationReceived = error;
done(error);
// </hide>
// << (hide)
});
// ```
// </snippet>
// << location-timeour
};

27
apps/tests/location.md Normal file
View File

@ -0,0 +1,27 @@
---
nav-title: "location How-To"
title: "How-To"
description: "Examples for using location"
---
# Location
Using the location requires the Location module.
<snippet id='location-require'/>
## Other functions
### Test are location services available for this device
<snippet id='location-funcs'/>
### Get distance between two locations
<snippet id='location-distance'/>
## Getting location
### Receive continuous location updates
<snippet id='location-updates'/>
### Get last known location
<snippet id='location-last-known'/>
### Get location once
if there is `options.timeout` you will receive error on timeout. If `options.timeout` is 0 then the result is the same as the result from `LocationManager.lastKnownLocation`
and there will be no wait. You can use `options.maximumAge` to specify you don't want to receive locations older than specified time in ms.
<snippet id='location-timeour'/>

View File

@ -2,93 +2,70 @@ import TKUnit = require("./TKUnit");
import bindableModule = require("ui/core/bindable");
require("globals");
// <snippet module="data/observable-array" title="observable-array">
// # Observable Array module
// ``` JavaScript
// >> observable-array-require
import observableArrayModule = require("data/observable-array");
// ```
// </snippet>
// << observable-array-require
require("globals");
export var test_ObservableArray_shouldCopySourceArrayItems = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Create ObservableArray from array.
// ``` JavaScript
// >> observable-array-create
var sa = [1, 2, 3];
var array = new observableArrayModule.ObservableArray(sa);
// ```
// </snippet>
// << observable-array-create
TKUnit.assert(sa.length === array.length && array.length === 3, "ObservableArray should copy all source array items!");
};
export var test_ObservableArray_shouldCopyMultipleItemsAsSource = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Create ObservableArray from arguments.
// ``` JavaScript
// >> observable-array-arguments
var array = new observableArrayModule.ObservableArray(1, 2, 3);
// ```
// </snippet>
// << observable-array-arguments
TKUnit.assert(array.length === 3 && array.getItem(1) === 2, "ObservableArray should copy multiple items from source!");
};
export var test_ObservableArray_shouldCreateArrayFromSpecifiedLength = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Create ObservableArray with specific length.
// ``` JavaScript
// >> observable-array-length
var array = new observableArrayModule.ObservableArray(100);
// ```
// </snippet>
// << observable-array-length
TKUnit.assert(array.length === 100, "ObservableArray should create array from specified length!");
};
export var test_ObservableArray_shouldBeAbleToSetLength = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Set ObservableArray length to new value.
// ``` JavaScript
// >> observable-array-newvalue
var array = new observableArrayModule.ObservableArray(100);
// <hide>
// >> (hide)
TKUnit.assert(array.length === 100, "ObservableArray should create array from specified length!");
// </hide>
// << (hide)
array.length = 50;
// ```
// </snippet>
// << observable-array-newvalue
TKUnit.assert(array.length === 50, "ObservableArray should respect new length!");
};
export var test_ObservableArray_getItemShouldReturnCorrectItem = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Get item at specified index using getItem(index) method.
// ``` JavaScript
// >> observable-array-getitem
var array = new observableArrayModule.ObservableArray([1, 2, 3]);
var firstItem = array.getItem(0);
var secondItem = array.getItem(1);
var thirdItem = array.getItem(2);
// ```
// </snippet>
// << observable-array-getitem
TKUnit.assert(firstItem === 1 && secondItem === 2 && thirdItem === 3, "ObservableArray getItem() should return correct item!");
};
export var test_ObservableArray_setItemShouldSetCorrectItem = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Set item at specified index using setItem(index, item) method.
// ``` JavaScript
// >> observable-array-setitem
var array = new observableArrayModule.ObservableArray([1, 2, 3]);
array.setItem(1, 5);
// ```
// </snippet>
// << observable-array-setitem
TKUnit.assert(array.getItem(1) === 5, "ObservableArray setItem() should set correct item!");
};
export var test_ObservableArray_setItemShouldRaiseCorrectEvent = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Set item at specified index using setItem(index, item) method and observe change event data.
// ``` JavaScript
// >> observable-array-eventdata
var index: number;
var action: string;
var addedCount: number;
@ -102,8 +79,7 @@ export var test_ObservableArray_setItemShouldRaiseCorrectEvent = function () {
removed = args.removed; // Array of removed items. In this case with single item (2).
});
array.setItem(1, 5);
// ```
// </snippet>
// << observable-array-eventdata
TKUnit.assertEqual(index, 1);
TKUnit.assertEqual(action, observableArrayModule.ChangeType.Update);
TKUnit.assertEqual(addedCount, 1);
@ -111,51 +87,39 @@ export var test_ObservableArray_setItemShouldRaiseCorrectEvent = function () {
};
export var test_ObservableArray_concatShouldReturnNewArrayWithNewItemsAtTheEnd = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Use concat() method to combine ObservableArray with array.
// ``` JavaScript
// >> observable-array-combine
var array = new observableArrayModule.ObservableArray([1, 2, 3]);
var result = array.concat([4, 5, 6]);
// ```
// </snippet>
// << observable-array-combine
TKUnit.assert(result.length === 6 && result[4] === 5, "ObservableArray concat() should add items at the end!");
};
export var test_ObservableArray_joinShouldReturnStringWithAllItemsSeparatedWithComma = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Use join() method to convert ObservableArray to comma separated string.
// ``` JavaScript
// >> observable-array-join
var array = new observableArrayModule.ObservableArray([1, 2, 3]);
var result = array.join();
// ```
// </snippet>
// >> observable-array-join
TKUnit.assert(result === "1,2,3", "ObservableArray join() should return string with all items separated with comma!");
};
export var test_ObservableArray_joinShouldReturnStringWithAllItemsSeparatedWithDot = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Use join(separator) method to convert ObservableArray to string separated with specified separator.
// ``` JavaScript
// >> observable-array-join-separator
var array = new observableArrayModule.ObservableArray([1, 2, 3]);
var result = array.join(".");
// ```
// </snippet>
// << observable-array-join-separator
TKUnit.assert(result === "1.2.3", "ObservableArray join() should return string with all items separated with dot!");
};
export var test_ObservableArray_popShouldRemoveTheLastElement = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Use pop() method to remove the last element.
// ``` JavaScript
// >> observable-array-join-pop'
var array = new observableArrayModule.ObservableArray([1, 2, 3]);
// <hide>
// >> (hide)
var bindable = new bindableModule.Bindable();
bindable.set("testProperty", 0);
bindable.bind({ sourceProperty: "length", targetProperty: "testProperty" }, array);
// </hide>
// << (hide)
var result = array.pop();
// ```
// </snippet>
// << observable-array-join-pop'
TKUnit.assert(result === 3 && array.length === 2, "ObservableArray pop() should remove last element!");
TKUnit.assert(bindable.get("testProperty") === array.length, "Expected: " + array.length + ", Actual: " + bindable.get("testProperty"));
};
@ -163,13 +127,11 @@ export var test_ObservableArray_popShouldRemoveTheLastElement = function () {
export var test_ObservableArray_popShouldRemoveTheLastElementAndRaiseChangeEventWithCorrectArgs = function () {
var result: observableArrayModule.ChangedData<number>;
// <snippet module="data/observable-array" title="observable-array">
// ### Handle "change" event to know more info about the change after calling pop() method.
// ``` JavaScript
// >> observable-array-join-change
var array = new observableArrayModule.ObservableArray([1, 2, 3]);
// <hide>
// >> (hide)
var index = array.length - 1;
// </hide>
// << (hide)
array.on(observableArrayModule.ObservableArray.changeEvent, (args: observableArrayModule.ChangedData<number>) => {
//// Argument (args) is ChangedData<T>.
@ -179,32 +141,28 @@ export var test_ObservableArray_popShouldRemoveTheLastElementAndRaiseChangeEvent
//// args.removed.length is 1.
//// args.addedCount is 0.
// <hide>
// >> (hide)
result = args;
// </hide>
// << (hide)
});
array.pop();
// ```
// </snippet>
// << observable-array-join-change
TKUnit.assert(result.eventName === observableArrayModule.ObservableArray.changeEvent && result.action === observableArrayModule.ChangeType.Delete &&
result.removed.length === 1 && result.index === index && result.addedCount === 0, "ObservableArray pop() should raise 'change' event with correct args!");
};
export var test_ObservableArray_pushShouldAppendNewElement = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Use push() method to add single element to the array.
// ``` JavaScript
// >> observable-array-push
var array = new observableArrayModule.ObservableArray([1, 2, 3]);
// <hide>
// >> (hide)
var bindable = new bindableModule.Bindable();
bindable.set("testProperty", 0);
bindable.bind({ sourceProperty: "length", targetProperty: "testProperty" }, array);
// </hide>
// << (hide)
var result = array.push(4);
// ```
// </snippet>
// << observable-array-push
TKUnit.assert(result === 4 && array.getItem(3) === 4, "ObservableArray push() should append new element!");
TKUnit.assert(bindable.get("testProperty") === array.length, "Expected: " + array.length + ", Actual: " + bindable.get("testProperty"));
};
@ -212,9 +170,7 @@ export var test_ObservableArray_pushShouldAppendNewElement = function () {
export var test_ObservableArray_pushShouldAppendNewElementAndRaiseChangeEventWithCorrectArgs = function () {
var result: observableArrayModule.ChangedData<number>;
// <snippet module="data/observable-array" title="observable-array">
// ### Handle "change" event to know more info about the change after calling push() method with single element.
// ``` JavaScript
// >> observable-array-change-push
var array = new observableArrayModule.ObservableArray([1, 2, 3]);
array.on(observableArrayModule.ObservableArray.changeEvent, (args: observableArrayModule.ChangedData<number>) => {
//// Argument (args) is ChangedData<T>.
@ -224,32 +180,28 @@ export var test_ObservableArray_pushShouldAppendNewElementAndRaiseChangeEventWit
//// args.removed.length is 0.
//// args.addedCount is 1.
// <hide>
// >> (hide)
result = args;
// </hide>
// << (hide)
});
array.push(4);
// ```
// </snippet>
// << observable-array-change-push
TKUnit.assert(result.eventName === observableArrayModule.ObservableArray.changeEvent && result.action === observableArrayModule.ChangeType.Add &&
result.removed.length === 0 && result.index === 3 && result.addedCount === 1, "ObservableArray push() should raise 'change' event with correct args!");
};
export var test_ObservableArray_pushShouldAppendNewElements = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Use push() method to add multiple elements to the array.
// ``` JavaScript
// >> observable-array-push-multiple
var array = new observableArrayModule.ObservableArray([1, 2, 3]);
// <hide>
// >> (hide)
var bindable = new bindableModule.Bindable();
bindable.set("testProperty", 0);
bindable.bind({ sourceProperty: "length", targetProperty: "testProperty" }, array);
// </hide>
// << (hide)
var result = array.push(4, 5, 6);
// ```
// </snippet>
// << observable-array-push-multiple
TKUnit.assert(result === 6 && array.getItem(5) === 6, "ObservableArray push() should append new elements!");
TKUnit.assert(bindable.get("testProperty") === array.length, "Expected: " + array.length + ", Actual: " + bindable.get("testProperty"));
};
@ -257,9 +209,7 @@ export var test_ObservableArray_pushShouldAppendNewElements = function () {
export var test_ObservableArray_pushShouldAppendNewElementsAndRaiseChangeEventWithCorrectArgs = function () {
var result: observableArrayModule.ChangedData<number>;
// <snippet module="data/observable-array" title="observable-array">
// ### Handle "change" event to know more info about the change after calling push() method with multiple elements.
// ``` JavaScript
// >> observable-array-push-multiple-info
var array = new observableArrayModule.ObservableArray([1, 2, 3]);
array.on(observableArrayModule.ObservableArray.changeEvent, (args: observableArrayModule.ChangedData<number>) => {
//// Argument (args) is ChangedData<T>.
@ -269,32 +219,28 @@ export var test_ObservableArray_pushShouldAppendNewElementsAndRaiseChangeEventWi
//// args.removed.length is 0.
//// args.addedCount is equal to the number of added items.
// <hide>
// >> (hide)
result = args;
// </hide>
// << (hide)
});
array.push(4, 5, 6);
// ```
// </snippet>
// << observable-array-push-multiple-info
TKUnit.assert(result.eventName === observableArrayModule.ObservableArray.changeEvent && result.action === observableArrayModule.ChangeType.Add &&
result.removed.length === 0 && result.index === 3 && result.addedCount === 3, "ObservableArray push() should raise 'change' event with correct args!");
};
export var test_ObservableArray_pushShouldAppendNewElementsFromSourceArray = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Use push() method to add multiple elements from source array to the ObservableArray.
// ``` JavaScript
// >> observable-array-push-source
var array = new observableArrayModule.ObservableArray([1, 2, 3]);
// <hide>
// >> (hide)
var bindable = new bindableModule.Bindable();
bindable.set("testProperty", 0);
bindable.bind({ sourceProperty: "length", targetProperty: "testProperty" }, array);
// </hide>
// << (hide)
var result = array.push([4, 5, 6]);
// ```
// </snippet>
// << observable-array-push-source
TKUnit.assert(result === 6 && array.getItem(5) === 6, "ObservableArray push() should append new elements from source array!");
TKUnit.assert(bindable.get("testProperty") === array.length, "Expected: " + array.length + ", Actual: " + bindable.get("testProperty"));
};
@ -302,9 +248,7 @@ export var test_ObservableArray_pushShouldAppendNewElementsFromSourceArray = fun
export var test_ObservableArray_pushShouldAppendNewElementsFromSourceArrayAndRaiseChangeEventWithCorrectArgs = function () {
var result: observableArrayModule.ChangedData<number>;
// <snippet module="data/observable-array" title="observable-array">
// ### Handle "change" event to know more info about the change after calling push() method with multiple elements from source array.
// ``` JavaScript
// >> observable-array-push-source-info
var array = new observableArrayModule.ObservableArray([1, 2, 3]);
array.on(observableArrayModule.ObservableArray.changeEvent, (args: observableArrayModule.ChangedData<number>) => {
//// Argument (args) is ChangedData<T>.
@ -314,43 +258,36 @@ export var test_ObservableArray_pushShouldAppendNewElementsFromSourceArrayAndRai
//// args.removed.length is 0.
//// args.addedCount is equal to the number of added items.
// <hide>
// >> (hide)
result = args;
// </hide>
// << (hide)
});
array.push([4, 5, 6]);
// ```
// </snippet>
// << observable-array-push-source-info
TKUnit.assert(result.eventName === observableArrayModule.ObservableArray.changeEvent && result.action === observableArrayModule.ChangeType.Add &&
result.removed.length === 0 && result.index === 3 && result.addedCount === 3, "ObservableArray push() should raise 'change' event with correct args!");
};
export var test_ObservableArray_reverseShouldReturnNewReversedArray = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Use reverse() method to reverse the elements order of the ObservableArray.
// ``` JavaScript
// >> observable-array-reverse
var array = new observableArrayModule.ObservableArray([1, 2, 3]);
var result = array.reverse();
// ```
// </snippet>
// << observable-array-reverse
TKUnit.assert(result.length === 3 && result[0] === 3, "ObservableArray reverse() should return new reversed array!");
};
export var test_ObservableArray_shiftShouldRemoveTheFirstElement = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Use shift() method to remove the first element of the array.
// ``` JavaScript
// >> observable-array-shift
var array = new observableArrayModule.ObservableArray([1, 2, 3]);
// <hide>
// >> (hide)
var bindable = new bindableModule.Bindable();
bindable.set("testProperty", 0);
bindable.bind({ sourceProperty: "length", targetProperty: "testProperty" }, array);
// </hide>
// << (hide)
var result = array.shift();
// ```
// </snippet>
// << observable-array-shift
TKUnit.assert(result === 1 && array.length === 2, "ObservableArray shift() should remove first element!");
TKUnit.assert(bindable.get("testProperty") === array.length, "Expected: " + array.length + ", Actual: " + bindable.get("testProperty"));
};
@ -358,9 +295,7 @@ export var test_ObservableArray_shiftShouldRemoveTheFirstElement = function () {
export var test_ObservableArray_shiftShouldRemoveTheFirstElementAndRaiseChangeEventWithCorrectArgs = function () {
var result: observableArrayModule.ChangedData<number>;
// <snippet module="data/observable-array" title="observable-array">
// ### Handle "change" event to know more info about the change after calling shift() method.
// ``` JavaScript
// >> observable-array-shift-change
var array = new observableArrayModule.ObservableArray([1, 2, 3]);
array.on(observableArrayModule.ObservableArray.changeEvent, (args: observableArrayModule.ChangedData<number>) => {
@ -371,76 +306,60 @@ export var test_ObservableArray_shiftShouldRemoveTheFirstElementAndRaiseChangeEv
//// args.removed.length is 1.
//// args.addedCount is 0.
// <hide>
// >> (hide)
result = args;
// </hide>
// << (hide)
});
array.shift();
// ```
// </snippet>
// << observable-array-shift-change
TKUnit.assert(result.eventName === observableArrayModule.ObservableArray.changeEvent && result.action === observableArrayModule.ChangeType.Delete &&
result.removed.length === 1 && result.index === 0 && result.addedCount === 0, "ObservableArray shift() should raise 'change' event with correct args!");
};
export var test_ObservableArray_sliceShouldReturnSectionAsNewArray = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Use slice() method to return array with all ObservableArray elements.
// ``` JavaScript
// observable-array-slice
var array = new observableArrayModule.ObservableArray([1, 2, 3]);
var result = array.slice();
// ```
// </snippet>
// << observable-array-slice
TKUnit.assert(result[2] === 3 && result.length === 3, "ObservableArray slice() should return section!");
};
export var test_ObservableArray_sliceWithParamsShouldReturnSectionAsNewArray = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Use slice(star, end) method to return section of the array.
// ``` JavaScript
// >> observable-array-slice-args
var array = new observableArrayModule.ObservableArray([1, 2, 3, 4, 5]);
var result = array.slice(2, 4);
// ```
// </snippet>
// << observable-array-slice-args
TKUnit.assert(result[1] === 4 && result.length === 2, "ObservableArray slice() should return section according to specified arguments!");
};
export var test_ObservableArray_sortShouldReturnNewSortedArray = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Use sort() method to sort the array.
// ``` JavaScript
// >> observable-array-sort
var array = new observableArrayModule.ObservableArray([3, 2, 1]);
var result = array.sort();
// ```
// </snippet>
// << observable-array-sort
TKUnit.assert(result[0] === 1 && result.length === 3, "ObservableArray sort() should return new sorted array!");
};
export var test_ObservableArray_sortShouldReturnNewSortedArrayAccordingSpecifiedOrder = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Use sort(compareFunction) method to sort the array with your own comparing logic.
// ``` JavaScript
// >> observable-array-sort-comparer
var array = new observableArrayModule.ObservableArray([10, 100, 1]);
var result = array.sort((a: number, b: number) => { return a - b; });
// ```
// </snippet>
// << observable-array-sort-comparer
TKUnit.assert(result[2] === 100 && result.length === 3, "ObservableArray sort() should return new sorted array according to specified order!");
};
export var test_ObservableArray_spliceShouldRemoveSpecifiedNumberOfElementsStartingFromSpecifiedIndex = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Use splice(start, deleteCount) method to delete elements in the array.
// ``` JavaScript
// >> observable-array-splice
var array = new observableArrayModule.ObservableArray(["one", "two", "three"]);
// <hide>
// >> (hide)
var bindable = new bindableModule.Bindable();
bindable.set("testProperty", 0);
bindable.bind({ sourceProperty: "length", targetProperty: "testProperty" }, array);
// </hide>
// << (hide)
var result = array.splice(1, 2);
// ```
// </snippet>
// <, observable-array-splice
TKUnit.assert(result.length === 2 && result[0] === "two" && array.length === 1 && array.getItem(0) === "one",
"ObservableArray splice() should remove specified number of elements starting from specified index!");
TKUnit.assert(bindable.get("testProperty") === array.length, "Expected: " + array.length + ", Actual: " + bindable.get("testProperty"));
@ -449,9 +368,7 @@ export var test_ObservableArray_spliceShouldRemoveSpecifiedNumberOfElementsStart
export var test_ObservableArray_spliceShouldRemoveSpecifiedNumberOfElementsStartingFromSpecifiedIndexAndRaiseChangeEventWithCorrectArgs = function () {
var result: observableArrayModule.ChangedData<number>;
// <snippet module="data/observable-array" title="observable-array">
// ### Handle "change" event to know more info about the change after calling splice(start, deleteCount) method.
// ``` JavaScript
// >> observable-array-splice-change
var array = new observableArrayModule.ObservableArray([1, 2, 3]);
array.on(observableArrayModule.ObservableArray.changeEvent, (args: observableArrayModule.ChangedData<number>) => {
@ -462,27 +379,23 @@ export var test_ObservableArray_spliceShouldRemoveSpecifiedNumberOfElementsStart
//// args.removed.length is equal to the number of deleted items.
//// args.addedCount is 0.
// <hide>
// >> (hide)
result = args;
// </hide>
// << (hide)
});
array.splice(1, 2);
// ```
// </snippet>
// << observable-array-splice-change
TKUnit.assert(result.eventName === observableArrayModule.ObservableArray.changeEvent && result.action === observableArrayModule.ChangeType.Splice &&
result.removed.length === 2 && result.index === 1 && result.addedCount === 0, "ObservableArray splice() should raise 'change' event with correct args!");
};
export var test_ObservableArray_spliceShouldInsertNewItemsInPlaceOfRemovedItemsStartingFromSpecifiedIndex = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Use splice(start, deleteCount, ...arguments) method to remove and insert elements in the array.
// ``` JavaScript
// >> observable-array-splice-args
var array = new observableArrayModule.ObservableArray(["one", "two", "three"]);
var result = array.splice(1, 2, "six", "seven");
// ```
// </snippet>
// << observable-array-splice-args
TKUnit.assert(result.length === 2 && result[0] === "two" && array.length === 3 && array.getItem(2) === "seven",
"ObservableArray splice() should insert new items in place of removed!");
};
@ -490,9 +403,7 @@ export var test_ObservableArray_spliceShouldInsertNewItemsInPlaceOfRemovedItemsS
export var test_ObservableArray_spliceShouldRemoveAndInertSpecifiedNumberOfElementsStartingFromSpecifiedIndexAndRaiseChangeEventWithCorrectArgs = function () {
var result: observableArrayModule.ChangedData<number>;
// <snippet module="data/observable-array" title="observable-array">
// ### Handle "change" event to know more info about the change after calling splice(start, deleteCount, ...arguments) method.
// ``` JavaScript
// >> observable-array-splice-args-change
var array = new observableArrayModule.ObservableArray(["one", "two", "three"]);
array.on(observableArrayModule.ObservableArray.changeEvent, (args: observableArrayModule.ChangedData<number>) => {
@ -503,32 +414,28 @@ export var test_ObservableArray_spliceShouldRemoveAndInertSpecifiedNumberOfEleme
//// args.removed.length is equal to the number of deleted items.
//// args.addedCount is equal to the delta between number of inserted items and number of deleted items but not less than 0.
// <hide>
// >> (hide)
result = args;
// </hide>
// << (hide)
});
array.splice(1, 2, "six", "seven", "eight");
// ```
// </snippet>
// << observable-array-splice-args-change
TKUnit.assert(result.eventName === observableArrayModule.ObservableArray.changeEvent && result.action === observableArrayModule.ChangeType.Splice &&
result.removed.length === 2 && result.index === 1 && result.addedCount === 1, "ObservableArray splice() should raise 'change' event with correct args!");
};
export var test_ObservableArray_unshiftShouldInsertNewElementsFromTheStart = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Use unshift(item1, item2... itemN) method to insert elements from the start of the array.
// ``` JavaScript
// >> observable-array-unshift
var array = new observableArrayModule.ObservableArray([1, 2, 3]);
// <hide>
// >> (hide)
var bindable = new bindableModule.Bindable();
bindable.set("testProperty", 0);
bindable.bind({ sourceProperty: "length", targetProperty: "testProperty" }, array);
// </hide>
// << (hide)
var result = array.unshift(4, 5);
// ```
// </snippet>
// << observable-array-unshift
TKUnit.assert(array.getItem(0) === 4 && result === 5 && array.length === 5, "ObservableArray unshift() should insert new elements from the start!");
TKUnit.assert(bindable.get("testProperty") === array.length, "Expected: " + array.length + ", Actual: " + bindable.get("testProperty"));
@ -537,9 +444,7 @@ export var test_ObservableArray_unshiftShouldInsertNewElementsFromTheStart = fun
export var test_ObservableArray_unshiftShouldInsertNewElementsFromTheStartAndRaiseChangeEventWithCorrectArgs = function () {
var result: observableArrayModule.ChangedData<number>;
// <snippet module="data/observable-array" title="observable-array">
// ### Handle "change" event to know more info about the change after calling unshift(item1, item2... itemN) method.
// ``` JavaScript
// >> observable-array-unshift-change
var array = new observableArrayModule.ObservableArray([1, 2, 3]);
array.on(observableArrayModule.ObservableArray.changeEvent, (args: observableArrayModule.ChangedData<number>) => {
//// Argument (args) is ChangedData<T>.
@ -549,60 +454,47 @@ export var test_ObservableArray_unshiftShouldInsertNewElementsFromTheStartAndRai
//// args.removed.length is 0.
//// args.addedCount is equal to the number of inserted items.
// <hide>
// >> (hide)
result = args;
// </hide>
// << (hide)
});
array.unshift(4, 5);
// ```
// </snippet>
// << observable-array-unshift-change
TKUnit.assert(result.eventName === observableArrayModule.ObservableArray.changeEvent && result.action === observableArrayModule.ChangeType.Add &&
result.removed.length === 0 && result.index === 0 && result.addedCount === 2, "ObservableArray unshift() should raise 'change' event with correct args!");
};
export var test_ObservableArray_indexOfShouldReturnCorrectIndex = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Use indexOf(item) method to get the index of the desired item in the array.
// ``` JavaScript
// >> observable-array-indexof
var array = new observableArrayModule.ObservableArray(["one", "two", "three"]);
var result = array.indexOf("two");
// ```
// </snippet>
// << observable-array-indexof
TKUnit.assert(result === 1, "ObservableArray indexOf() should return correct index!");
};
export var test_ObservableArray_indexOfShouldReturnCorrectIndexStartingFrom = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Use indexOf(item, fromIndex) method to get the index of the desired item in the array starting from specified index.
// ``` JavaScript
// >> observable-array-indexof-args
var array = new observableArrayModule.ObservableArray(["one", "two", "three"]);
var result = array.indexOf("two", 2);
// ```
// </snippet>
// << observable-array-indexof-args
TKUnit.assert(result === -1, "ObservableArray indexOf() should return correct index!");
};
export var test_ObservableArray_lastIndexOfShouldReturnCorrectIndex = function () {
var array = new observableArrayModule.ObservableArray(["one", "two", "two", "three"]);
// <snippet module="data/observable-array" title="observable-array">
// ### Use lastIndexOf(item) method to get the last index of the desired item in the array.
// ``` JavaScript
// >> observable-array-lastindexof
var result = array.lastIndexOf("two");
// ```
// </snippet>
// << observable-array-lastindexof
TKUnit.assert(result === 2, "ObservableArray lastIndexOf() should return correct index!");
};
export var test_ObservableArray_lastIndexOfShouldReturnCorrectIndexStartingFrom = function () {
// <snippet module="data/observable-array" title="observable-array">
// ### Use lastIndexOf(item, fromIndex) method to get the last index of the desired item in the array starting from specified index.
// ``` JavaScript
// >> observable-array-lastindexof-args
var array = new observableArrayModule.ObservableArray(["one", "two", "two", "one", "three"]);
var result = array.lastIndexOf("two", 1);
// ```
// </snippet>
// << observable-array-lastindexof-args
TKUnit.assert(result === 1, "ObservableArray lastIndexOf() should return correct index!");
};

View File

@ -0,0 +1,112 @@
---
nav-title: "observable-array How-To"
title: "How-To"
description: "Examples for using observable-array"
---
# Observable Array module
<snippet id='observable-array-require'/>
### Create ObservableArray from array.
<snippet id='observable-array-create'/>
### Create ObservableArray from arguments.
<snippet id='observable-array-arguments'/>
### Create ObservableArray with specific length.
<snippet id='observable-array-length'/>
### Set ObservableArray length to new value.
<snippet id='observable-array-newvalue'/>
### Get item at specified index using getItem(index) method.
<snippet id='observable-array-getitem'/>
### Set item at specified index using setItem(index, item) method.
<snippet id='observable-array-setitem'/>
### Set item at specified index using setItem(index, item) method and observe change event data.
<snippet id='observable-array-eventdata'/>
### Use concat() method to combine ObservableArray with array.
<snippet id='observable-array-combine'/>
### Use join() method to convert ObservableArray to comma separated string.
<snippet id='observable-array-join'/>
### Use join(separator) method to convert ObservableArray to string separated with specified separator.
<snippet id='observable-array-join-separator'/>
### Use pop() method to remove the last element.
<snippet id='observable-array-join-pop'/>
### Handle "change" event to know more info about the change after calling pop() method.
<snippet id='observable-array-join-change'/>
### Use push() method to add single element to the array.
<snippet id='observable-array-push'/>
### Handle "change" event to know more info about the change after calling push() method with single element.
<snippet id='observable-array-change-push'/>
### Use push() method to add multiple elements to the array.
<snippet id='observable-array-push-multiple'/>
### Handle "change" event to know more info about the change after calling push() method with multiple elements.
<snippet id='observable-array-push-multiple-info'/>
### Use push() method to add multiple elements from source array to the ObservableArray.
<snippet id='observable-array-push-source'/>
### Handle "change" event to know more info about the change after calling push() method with multiple elements from source array.
<snippet id='observable-array-push-source-info'/>
### Use reverse() method to reverse the elements order of the ObservableArray.
<snippet id='observable-array-reverse'/>
### Use shift() method to remove the first element of the array.
<snippet id='observable-array-shift'/>
### Handle "change" event to know more info about the change after calling shift() method.
<snippet id='observable-array-shift-change'/>
### Use slice() method to return array with all ObservableArray elements.
<snippet id='observable-array-slice'/>
### Use slice(star, end) method to return section of the array.
<snippet id='observable-array-slice-args'/>
### Use sort() method to sort the array.
<snippet id='observable-array-sort'/>
### Use sort(compareFunction) method to sort the array with your own comparing logic.
<snippet id='observable-array-sort-comparer'/>
### Use splice(start, deleteCount) method to delete elements in the array.
<snippet id='observable-array-splice'/>
### Handle "change" event to know more info about the change after calling splice(start, deleteCount) method.
<snippet id='observable-array-splice-change'/>
### Use splice(start, deleteCount, ...arguments) method to remove and insert elements in the array.
<snippet id='observable-array-splice-args'/>
### Handle "change" event to know more info about the change after calling splice(start, deleteCount, ...arguments) method.
<snippet id='observable-array-splice-args-change'/>
### Use unshift(item1, item2... itemN) method to insert elements from the start of the array.
<snippet id='observable-array-unshift'/>
### Handle "change" event to know more info about the change after calling unshift(item1, item2... itemN) method.
<snippet id='observable-array-unshift-change'/>
### Use indexOf(item) method to get the index of the desired item in the array.
<snippet id='observable-array-indexof'/>
### Use indexOf(item, fromIndex) method to get the index of the desired item in the array starting from specified index.
<snippet id='observable-array-indexof-args'/>
### Use lastIndexOf(item) method to get the last index of the desired item in the array.
<snippet id='observable-array-lastindexof'/>
### Use lastIndexOf(item, fromIndex) method to get the last index of the desired item in the array starting from specified index.
<snippet id='observable-array-lastindexof-args'/>

View File

@ -1,10 +1,6 @@
// <snippet module="data/observable" title="data/observable">
// # Observable
// Using Observable objects requires the "data/observable" module.
// ``` JavaScript
// >> observable-require
import observable = require("data/observable");
// ```
// </snippet>
// << observable-require
import dependencyObservable = require("ui/core/dependency-observable");
import TKUnit = require("./TKUnit");
@ -19,9 +15,7 @@ class TestObservable extends observable.Observable {
}
export var test_Observable_Constructor = function () {
// <snippet module="data/observable" title="data/observable">
// ### Creating an Observable
// ``` JavaScript
// >> observable-creating
var json = {
Name: "John",
Age: 34,
@ -32,17 +26,14 @@ export var test_Observable_Constructor = function () {
var age = person.get("Age");
var married = person.get("Married");
//// console.log(name + " " + age + " " + married); // Prints out "John 34 true" if uncommented.
// ```
// </snippet>
// << observable-creating
TKUnit.assert(name === "John", "Expected name is John");
TKUnit.assert(age === 34, "Expected age is 34");
TKUnit.assert(married === true, "Expected married is true");
}
export var tests_DummyTestForCodeSnippet = function () {
// <snippet module="data/observable" title="data/observable">
// ### Responding to property changes
// ``` JavaScript
// >> observable-property-change
var person = new observable.Observable();
person.set("Name", "John");
person.set("Age", 34);
@ -55,8 +46,7 @@ export var tests_DummyTestForCodeSnippet = function () {
//// If uncommented, the console.log above produces the following output:
//// propertyChange Age 35
//// propertyChange Married false
// ```
// </snippet>
// << observable-property-change
}
export var test_Observable_Members = function () {

14
apps/tests/observable.md Normal file
View File

@ -0,0 +1,14 @@
---
nav-title: "data/observable How-To"
title: "How-To"
description: "Examples for using data/observable"
---
# Observable
Using Observable objects requires the "data/observable" module.
<snippet id='observable-require'/>
### Creating an Observable
<snippet id='observable-creating'/>
### Responding to property changes
<snippet id='observable-property-change'/>

View File

@ -1,14 +1,9 @@
import TKUnit = require("./TKUnit");
import app = require("application");
// <snippet module="platform" title="platform">
// # Platform
// Information about the current device and screen are defined in the platform module
// ### Declaring platform module to be available for further usage.
// ``` JavaScript
// >> platform-require
import platformModule = require("platform");
// ```
// </snippet>
// << platform-require
export function test_setTimeout_isDefined() {
var expected;
@ -22,9 +17,7 @@ export function test_setTimeout_isDefined() {
};
export function snippet_print_all() {
// <snippet module="platform" title="platform">
// ### Getting information about the current device:
// ``` JavaScript
// >> platform-current
console.log("Device model: " + platformModule.device.model);
console.log("Device type: " + platformModule.device.deviceType);
console.log("OS: " + platformModule.device.os);
@ -34,6 +27,5 @@ export function snippet_print_all() {
console.log("Screen width: " + platformModule.screen.mainScreen.widthPixels);
console.log("Screen height: " + platformModule.screen.mainScreen.heightPixels);
console.log("Screen scale: " + platformModule.screen.mainScreen.scale);
// ```
// </snippet>
// << platform-current
};

12
apps/tests/platform.md Normal file
View File

@ -0,0 +1,12 @@
---
nav-title: "platform How-To"
title: "How-To"
description: "Examples for using platform"
---
# Platform
Information about the current device and screen are defined in the platform module
### Declaring platform module to be available for further usage.
<snippet id='platform-require'/>
### Getting information about the current device:
<snippet id='platform-current'/>

View File

@ -1,20 +1,14 @@
// <snippet module="text/formatted-string" title="Formatted String">
// # Formatted String
// Using a formatted string requires loading formatted-string and span module.
// ``` JavaScript
// >> formatted-string-require
import formattedStringModule = require("text/formatted-string");
import spanModule = require("text/span");
// ```
// </snippet>
// << formatted-string-require
import observable = require("data/observable");
import TKUnit = require("../TKUnit");
import LabelModule = require("ui/label");
export var test_FormattedString_RemovesEventListeners_for_spans = function () {
// <snippet module="text/formatted-string" title="Formatted String">
// ### How to set formatted text content for a label
// ``` JavaScript
// >> formatted-string-set
var label = new LabelModule.Label();
var formattedString = new formattedStringModule.FormattedString();
var firstSpan = new spanModule.Span();
@ -23,8 +17,7 @@ export var test_FormattedString_RemovesEventListeners_for_spans = function () {
firstSpan.text = "LoremIpsum";
formattedString.spans.push(firstSpan);
label.formattedText = formattedString;
// ```
// </snippet>
// << formatted-string-set
TKUnit.assert(formattedString.spans.getItem(0).hasListeners(observable.Observable.propertyChangeEvent) === true, "Listener for spans collection change event is not attached!");
var removedSpan = formattedString.spans.pop();

View File

@ -0,0 +1,11 @@
---
nav-title: "Formatted String How-To"
title: "How-To"
description: "Examples for using Formatted String"
---
# Formatted String
Using a formatted string requires loading formatted-string and span module.
<snippet id='formatted-string-require'/>
### How to set formatted text content for a label
<snippet id='formatted-string-set'/>

View File

@ -2,15 +2,11 @@
import platform = require("platform");
var timer = require("timer/timer");
// <snippet module="timer" title="timer">
// # Timer module
// ### How to require timer module
// ``` JavaScript
// >> timer-require
// require("globals");
//// OR
// var timer = require("timer");
// ```
// </snippet>
// << timer-require
export var test_setTimeout_isDefined = function () {
TKUnit.assert(typeof (timer.setTimeout) !== "undefined", "Method timer.setTimeout() should be defined!");
@ -32,16 +28,13 @@ export var test_setTimeout = function () {
var completed: boolean;
var isReady = function () { return completed; }
// <snippet module="timer" title="timer">
// ### Evaluates an expression after 0 milliseconds.
// ``` JavaScript
// >> timer-set-zero
timer.setTimeout(function () {
// <hide>
// >> (hide)
completed = true;
// </hide>
// << (hide)
});
// ```
// </snippet>
// << timer-set-zero
TKUnit.waitUntilReady(isReady, 0.5);
TKUnit.assert(completed, "Callback should be called!");
@ -51,16 +44,13 @@ export var test_setTimeout_callbackCalledAfterSpecifiedTime = function () {
var completed: boolean;
var isReady = function () { return completed; }
// <snippet module="timer" title="timer">
// ### Evaluates an expression after a specified number of milliseconds.
// ``` JavaScript
// >> timer-set-fivehundred
timer.setTimeout(function () {
// <hide>
// >> (hide)
completed = true;
// </hide>
// << (hide)
}, 500);
// ```
// </snippet>
// << timer-set-fivehundred
TKUnit.waitUntilReady(isReady, 1);
TKUnit.assert(completed, "Callback should be called after specified time!");
@ -95,20 +85,17 @@ export var test_setTimeout_callbackShouldBeCleared = function () {
var completed: boolean;
var isReady = function () { return completed; }
// <snippet module="timer" title="timer">
// ### Cancels the evaluation with the clearTimeout method.
// ``` JavaScript
// >> timer-set-twothousands
var id = timer.setTimeout(function () {
// <hide>
// >> (hide)
completed = true;
// </hide>
// << (hide)
}, 2000);
//// Clear timeout with specified id.
timer.clearTimeout(id);
// ```
// </snippet>
// << timer-set-twothousands
TKUnit.waitUntilReady(isReady, 3);
TKUnit.assert(!completed, "Callback should be cleared when clearTimeout() is executed for specified id!");
@ -119,16 +106,13 @@ export var test_setInterval_callbackCalledDuringPeriod = function () {
var expected = 4;
var isReady = function () { return counter >= expected; }
// <snippet module="timer" title="timer">
// ### Evaluates an expression each time a specified number of milliseconds has elapsed.
// ``` JavaScript
// >> timer-set-expression
timer.setInterval(function () {
// <hide>
// >> (hide)
counter++;
// </hide>
// << (hide)
}, 100);
// ```
// </snippet>
// << timer-set-expression
TKUnit.waitUntilReady(isReady, 0.5);
TKUnit.assert(isReady(), "Callback should be raised at least" + expected + "times! Callback raised " + counter + " times.");
@ -138,17 +122,14 @@ export var test_setInterval_callbackShouldBeCleared = function () {
var counter = 0;
var isReady = function () { return false; }
// <snippet module="timer" title="timer">
// ### Cancel the interval previously started using the setInterval method.
// ``` JavaScript
// >> timer-set-interval
var id = timer.setInterval(function () {
// <hide>
// >> (hide)
counter++;
// </hide>
// << (hide)
timer.clearInterval(id);
}, 100);
// ```
// </snippet>
// << timer-set-interval
TKUnit.waitUntilReady(isReady, 0.5);
TKUnit.assert(counter === 1, "Callback should be raised only once!");

23
apps/tests/timer.md Normal file
View File

@ -0,0 +1,23 @@
---
nav-title: "timer How-To"
title: "How-To"
description: "Examples for using timer"
---
# Timer module
### How to require timer module
<snippet id='timer-require'/>
### Evaluates an expression after 0 milliseconds.
<snippet id='timer-set-zero'/>
### Evaluates an expression after a specified number of milliseconds.
<snippet id='timer-set-fivehundred'/>
### Cancels the evaluation with the clearTimeout method.
<snippet id='timer-set-twothousands'/>
### Evaluates an expression each time a specified number of milliseconds has elapsed.
<snippet id='timer-set-expression'/>
### Cancel the interval previously started using the setInterval method.
<snippet id='timer-set-interval'/>

View File

@ -1,25 +1,16 @@
// <snippet module="trace" title="trace">
// # Trace
// Tracing information about your app requires the "trace" module.
// ``` JavaScript
// >> trace-require
import trace = require("trace");
// ```
// </snippet>
// << trace-require
export var test_DummyTestForSnippetOnly0 = function () {
// <snippet module="trace" title="trace">
// ### Tracing all categories of events.
// ``` JavaScript
// >> trace-all-categories
trace.setCategories(trace.categories.All);
trace.enable();
// ```
// </snippet>
// << trace-all-categories
}
export var test_DummyTestForSnippetOnly1 = function () {
// <snippet module="trace" title="trace">
// ### Tracing specific categories of events.
// ``` JavaScript
// >> trace-specific-categories
trace.setCategories(trace.categories.concat(
trace.categories.Binding
, trace.categories.Debug
@ -31,17 +22,13 @@ export var test_DummyTestForSnippetOnly1 = function () {
, trace.categories.VisualTreeEvents
));
trace.enable();
// ```
// </snippet>
// << trace-specific-categories
}
export var test_DummyTestForSnippetOnly2 = function () {
// <snippet module="trace" title="trace">
// ### Write your own trace message.
// ``` JavaScript
// >> trace-message
trace.setCategories(trace.categories.Debug);
trace.enable();
trace.write("My Debug Message", trace.categories.Debug);
// ```
// </snippet>
// << trace-message
}

17
apps/tests/trace.md Normal file
View File

@ -0,0 +1,17 @@
---
nav-title: "trace How-To"
title: "How-To"
description: "Examples for using trace"
---
# Trace
Tracing information about your app requires the "trace" module.
<snippet id='trace-require'/>
### Tracing all categories of events.
<snippet id='trace-all-categories'/>
### Tracing specific categories of events.
<snippet id='trace-specific-categories'/>
### Write your own trace message.
<snippet id='trace-message'/>

View File

@ -8,151 +8,9 @@ import viewModule = require("ui/core/view");
import fs = require("file-system");
import { Observable } from "data/observable";
// <snippet module="ui/action-bar" title="ActionBar">
// # ActionBar
// Using a ActionBar requires the action-bar module.
// ``` JavaScript
// >> actionbar-common-require
import actionBarModule = require("ui/action-bar");
// ```
//
// ## Setting Title and Icon
//``` XML
// <Page>
// <Page.actionBar>
// {%raw%}<ActionBar title="{{ title }}" android.icon="res://is_custom_home_icon"/>{%endraw%}
// </Page.actionBar>
// ...
// </Page>
//```
//The icon can only be set in Android platform. It is hidden by default, but you explicitly control its visibility with the `android.iconVisibility' property.
//
//
// ## Setting Custom Title View
//``` XML
// <Page loaded="pageLoaded">
// <Page.actionBar>
// <ActionBar title="Title">
// <ActionBar.titleView>
// <StackLayout orientation="horizontal">
// <Button text="1st" />
// <Button text="2nd" />
// <Button text="3rd" />
// </StackLayout>
// </ActionBar.titleView>
// </ActionBar>
// </Page.actionBar>
// ...
// </Page>
//```
//
// ## Setting Action Items
//``` XML
// <Page>
// <Page.actionBar>
// <ActionBar title="Title">
// <ActionBar.actionItems>
// <ActionItem text="left" ios.position="left"/>
// <ActionItem text="right" ios.position="right"/>
// <ActionItem text="pop" ios.position="right" android.position="popup"/>
// </ActionBar.actionItems>
// </ActionBar>
// </Page.actionBar>
// ...
// </Page>
//```
//
//The position option is platform specific. The available values are as follows:
// * **Android** - `actionBar`, `actionBarIfRoom` and `popup`. The default is `actionBar`.
// * **iOS** - `left` and `right`. The default is `left`.
//
// ## Displaying Platform-Specific System Icons on Action Items
//``` XML
// <Page>
// <Page.actionBar>
// <ActionBar>
// <ActionBar.actionItems>
// <ActionItem ios.systemIcon="12" android.systemIcon = "ic_menu_search" />
// <ActionItem ios.systemIcon="15" android.systemIcon = "ic_menu_camera" />
// <ActionItem ios.systemIcon="16" android.systemIcon = "ic_menu_delete" />
// </ActionBar.actionItems>
// </ActionBar>
// </Page.actionBar>
// ...
// </Page>
//```
//
//### iOS
//Set `ios.systemIcon` to a number representing the iOS system item to be displayed.
//Use this property instead of `ActionItem.icon` if you want to diplsay a built-in iOS system icon.
//Note: systemIcon is not supported on NavigationButton in iOS
//The value should be a number from the `UIBarButtonSystemItem` enumeration
//(https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIBarButtonItem_Class/#//apple_ref/c/tdef/UIBarButtonSystemItem)
//0: Done
//1: Cancel
//2: Edit
//3: Save
//4: Add
//5: FlexibleSpace
//6: FixedSpace
//7: Compose
//8: Reply
//9: Action
//10: Organize
//11: Bookmarks
//12: Search
//13: Refresh
//14: Stop
//15: Camera
//16: Trash
//17: Play
//18: Pause
//19: Rewind
//20: FastForward
//21: Undo
//22: Redo
//23: PageCurl
//
//### Android
//Set `android.systemIcon` the name of the system drawable resource to be displayed.
//Use this property instead of `ActionItem.icon` if you want to diplsay a built-in Android system icon.
//The value should be a string such as 'ic_menu_search' if you want to display the built-in Android Menu Search icon for example.
//For a full list of Android drawable names, please visit http://androiddrawables.com
//
// ## Displaying Custom View in Action Items
//``` XML
// <Page>
// <Page.actionBar>
// <ActionBar>
// <ActionBar.actionItems>
// <ActionItem>
// <ActionItem.actionView>
// <StackLayout orientation="horizontal">
// <Label text="Green" color="green"/>
// <Label text="Red" color="red"/>
// </StackLayout>
// </ActionItem.actionView>
// </ActionItem>
// </ActionBar.actionItems>
// </ActionBar>
// </Page.actionBar>
// ...
// </Page>
//```
//
// ## Setting Navigation Button
//``` XML
// <Page>
// <Page.actionBar>
// <ActionBar title="Title">
// <NavigationButton text="go back" android.systemIcon = "ic_menu_back"/>
// </ActionBar>
// ...
// </Page>
//```
//Setting `text` for the navigation button is not supported in Android. You can use `icon` or `android.systemIcon` to set the image in Android.
//Setting `ios.systemIcon` for the navigation button is not supported in iOS.
//
// </snippet>
// << actionbar-common-require
export function test_actionItem_inherit_bindingContext() {
var page: PageModule.Page;

View File

@ -0,0 +1,146 @@
---
nav-title: "ActionBar How-To"
title: "How-To"
description: "Examples for using ActionBar"
---
# ActionBar
Using a ActionBar requires the action-bar module.
<snippet id='actionbar-common-require'/>
## Setting Title and Icon
```XML
<Page>
<Page.actionBar>
{%raw%}<ActionBar title="{{ title }}" android.icon="res://is_custom_home_icon"/>{%endraw%}
</Page.actionBar>
...
</Page>
```
The icon can only be set in Android platform. It is hidden by default, but you explicitly control its visibility with the `android.iconVisibility' property.
## Setting Custom Title View
```XML
<Page loaded="pageLoaded">
<Page.actionBar>
<ActionBar title="Title">
<ActionBar.titleView>
<StackLayout orientation="horizontal">
<Button text="1st" />
<Button text="2nd" />
<Button text="3rd" />
</StackLayout>
</ActionBar.titleView>
</ActionBar>
</Page.actionBar>
...
</Page>
```
## Setting Action Items
```XML
<Page>
<Page.actionBar>
<ActionBar title="Title">
<ActionBar.actionItems>
<ActionItem text="left" ios.position="left"/>
<ActionItem text="right" ios.position="right"/>
<ActionItem text="pop" ios.position="right" android.position="popup"/>
</ActionBar.actionItems>
</ActionBar>
</Page.actionBar>
...
</Page>
```
The position option is platform specific. The available values are as follows:
* **Android** - `actionBar`, `actionBarIfRoom` and `popup`. The default is `actionBar`.
* **iOS** - `left` and `right`. The default is `left`.
## Displaying Platform-Specific System Icons on Action Items
```XML
<Page>
<Page.actionBar>
<ActionBar>
<ActionBar.actionItems>
<ActionItem ios.systemIcon="12" android.systemIcon = "ic_menu_search" />
<ActionItem ios.systemIcon="15" android.systemIcon = "ic_menu_camera" />
<ActionItem ios.systemIcon="16" android.systemIcon = "ic_menu_delete" />
</ActionBar.actionItems>
</ActionBar>
</Page.actionBar>
...
</Page>
```
### iOS
Set `ios.systemIcon` to a number representing the iOS system item to be displayed.
Use this property instead of `ActionItem.icon` if you want to diplsay a built-in iOS system icon.
Note: systemIcon is not supported on NavigationButton in iOS
The value should be a number from the `UIBarButtonSystemItem` enumeration
(https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIBarButtonItem_Class/#//apple_ref/c/tdef/UIBarButtonSystemItem)
0: Done
1: Cancel
2: Edit
3: Save
4: Add
5: FlexibleSpace
6: FixedSpace
7: Compose
8: Reply
9: Action
10: Organize
11: Bookmarks
12: Search
13: Refresh
14: Stop
15: Camera
16: Trash
17: Play
18: Pause
19: Rewind
20: FastForward
21: Undo
22: Redo
23: PageCurl
### Android
Set `android.systemIcon` the name of the system drawable resource to be displayed.
Use this property instead of `ActionItem.icon` if you want to diplsay a built-in Android system icon.
The value should be a string such as 'ic_menu_search' if you want to display the built-in Android Menu Search icon for example.
For a full list of Android drawable names, please visit http://androiddrawables.com
## Displaying Custom View in Action Items
```XML
<Page>
<Page.actionBar>
<ActionBar>
<ActionBar.actionItems>
<ActionItem>
<ActionItem.actionView>
<StackLayout orientation="horizontal">
<Label text="Green" color="green"/>
<Label text="Red" color="red"/>
</StackLayout>
</ActionItem.actionView>
</ActionItem>
</ActionBar.actionItems>
</ActionBar>
</Page.actionBar>
...
</Page>
```
## Setting Navigation Button
```XML
<Page>
<Page.actionBar>
<ActionBar title="Title">
<NavigationButton text="go back" android.systemIcon = "ic_menu_back"/>
</ActionBar>
...
</Page>
```
Setting `text` for the navigation button is not supported in Android. You can use `icon` or `android.systemIcon` to set the image in Android.
Setting `ios.systemIcon` for the navigation button is not supported in iOS.

View File

@ -0,0 +1,32 @@
---
nav-title: "activity-indicator How-To"
title: "How-To"
description: "Examples for using activity-indicator"
---
# ActivityIndicator
Using the activity indicator requires the ActivityIndicator module.
``` JavaScript
var activityIndicatorModule = require("ui/activity-indicator");
```
### Binding the activity indicator busy property to a view-model property.
``` XML
<Page>
{%raw%}<ActivityIndicator busy="{{ isLoading }}" />{%endraw%}
</Page>
```
### Creating an activity indicator
``` JavaScript
var indicator = new activityIndicatorModule.ActivityIndicator();
```
### Showing activity indicator while image is loading
``` JavaScript
var image = new imageModule.Image();
var indicator = new activityIndicatorModule.ActivityIndicator();
indicator.width = 100;
indicator.height = 100;
// Bind the busy property of the indicator to the isLoading property of the image
indicator.bind({
sourceProperty: "isLoading",
targetProperty: "busy"
}, image);
```

View File

@ -1,12 +1,9 @@
import TKUnit = require("./TKUnit");
import types = require("utils/types");
// <snippet module="data/virtual-array" title="virtual-array">
// # Virtual Array module
// ``` JavaScript
// >> virtual-array-require
import virtualArrayModule = require("data/virtual-array");
// ```
// </snippet>
// << virtual-array-require
require("globals");
@ -23,18 +20,11 @@ export var test_VirtualArray_setItemShouldSetCorrectItem = function () {
};
export var test_VirtualArray_setItemShouldRaiseChangeEventWhenYouSetDifferentItem = function () {
// <snippet module="data/virtual-array" title="virtual-array">
// ### Handle "itemsLoading" event to load items on demand using load() method.
// Use "length" property set via VirtualArray constructor to specify total number of items,
// "loadSize" to specify number of items to be requested in a single request,
// "itemsLoading" event to handle items request and "load()" method to copy items into the array.
// All already loaded items are cached in -memory and when "getItem()" method is called
// the array will raise "itemsLoading" event for still not loaded items.
// ``` JavaScript
// >> virtual-array-itemsloading
var array = new virtualArrayModule.VirtualArray<number>(100);
array.loadSize = 15;
// <hide>
// >> (hide)
var result: virtualArrayModule.ChangedData<number>;
var index = 0;
@ -53,7 +43,7 @@ export var test_VirtualArray_setItemShouldRaiseChangeEventWhenYouSetDifferentIte
TKUnit.assert(result && result.eventName === "change" && result.action === virtualArrayModule.ChangeType.Update &&
result.removed.length === 1 && result.index === index && result.addedCount === 1, "VirtualArray<T> setItem() should raise 'change' event with correct args!");
// </hide>
// << (hide)
array.on(virtualArrayModule.VirtualArray.itemsLoadingEvent, (args: virtualArrayModule.ItemsLoading) => {
//// Argument (args) is ItemsLoading.
@ -74,21 +64,18 @@ export var test_VirtualArray_setItemShouldRaiseChangeEventWhenYouSetDifferentIte
array.load(args.index, itemsToLoad);
});
// ```
// </snippet>
// << virtual-array-itemsloading
};
export var test_VirtualArray_loadShouldRaiseChangeEventWithCorrectArgs = function () {
// <snippet module="data/virtual-array" title="virtual-array">
// ### Handle "change" event when you load items using load() method.
// ``` JavaScript
// >> virtual-array-change
var array = new virtualArrayModule.VirtualArray<number>(100);
array.loadSize = 15;
// <hide>
// >> (hide)
var result: virtualArrayModule.ChangedData<number>;
var index = 0;
// </hide>
// << (hide)
array.on(virtualArrayModule.VirtualArray.changeEvent, (args: virtualArrayModule.ChangedData<number>) => {
//// Argument (args) is ChangedData<T>.
@ -96,16 +83,15 @@ export var test_VirtualArray_loadShouldRaiseChangeEventWithCorrectArgs = functio
//// args.action is "update".
//// args.removed.length and result.addedCount are equal to number of loaded items with load() method.
// <hide>
// >> (hide)
result = args;
// </hide>
// << (hide)
});
var itemsToLoad = [0, 1, 2];
array.load(index, itemsToLoad);
// ```
// </snippet>
// << virtual-array-change
TKUnit.assert(result && result.eventName === "change" && result.action === virtualArrayModule.ChangeType.Update &&
result.removed.length === itemsToLoad.length && result.index === index && result.addedCount === itemsToLoad.length,
@ -113,16 +99,14 @@ export var test_VirtualArray_loadShouldRaiseChangeEventWithCorrectArgs = functio
};
export var test_VirtualArray_lengthIncreaseShouldRaiseChangeEventWithCorrectArgs = function () {
// <snippet module="data/virtual-array" title="virtual-array">
// ### Handle "change" event when you increase "length" property.
// ``` JavaScript
// >> virtual-array-lenght
var array = new virtualArrayModule.VirtualArray<number>(100);
array.loadSize = 15;
// <hide>
// >> (hide)
var result: virtualArrayModule.ChangedData<number>;
var index = array.length;
// </hide>
// << (hide)
array.on(virtualArrayModule.VirtualArray.changeEvent, (args: virtualArrayModule.ChangedData<number>) => {
//// Argument (args) is ChangedData<T>.
@ -130,14 +114,13 @@ export var test_VirtualArray_lengthIncreaseShouldRaiseChangeEventWithCorrectArgs
//// args.action is "add".
//// args.removed.length is 0, result.addedCount is equal to the delta between new and old "length" property values.
// <hide>
// >> (hide)
result = args;
// </hide>
// << (hide)
});
array.length += array.loadSize;
// ```
// </snippet>
// << virtual-array-lenght
TKUnit.assert(result && result.eventName === "change" && result.action === virtualArrayModule.ChangeType.Add
&& result.index === index && result.addedCount === array.loadSize && result.removed.length === 0,

View File

@ -0,0 +1,22 @@
---
nav-title: "virtual-array How-To"
title: "How-To"
description: "Examples for using virtual-array"
---
# Virtual Array module
<snippet id='virtual-array-require'/>
### Handle "itemsLoading" event to load items on demand using load() method.
Use "length" property set via VirtualArray constructor to specify total number of items,
"loadSize" to specify number of items to be requested in a single request,
"itemsLoading" event to handle items request and "load()" method to copy items into the array.
All already loaded items are cached in -memory and when "getItem()" method is called
the array will raise "itemsLoading" event for still not loaded items.
<snippet id='virtual-array-itemsloading'/>
### Handle "change" event when you load items using load() method.
<snippet id='virtual-array-change'/>
### Handle "change" event when you increase "length" property.
<snippet id='virtual-array-lenght'/>