chore(platform): move plugins to platform

This commit is contained in:
Max Lynch
2015-09-23 11:57:07 -05:00
parent 1d275497f1
commit cfa906dfde
21 changed files with 1 additions and 1 deletions

View File

@@ -0,0 +1,71 @@
import * as Rx from 'rx';
import * as util from 'ionic/util';
import {NativePlugin} from '../plugin';
/**
* Open installed apps on the device. Note: Android and iOS have different ways of
* opening and specifying launch params, so they have separate launch functions.
*
* Example:
*
* if(platform.is('ios') {
* AppLinks.check('twitter://').then((installed) => {
* AppLinks.openIOS('twitter://user?screen_name=ionicframework')
* }, (err) => {
*
* })
* } else if(platform.is('android') {
* AppLinks.check('com.twitter.android').then((installed) => {
* AppLinks.openAndroid([["action", "VIEW"], ['twitter://user?screen_name=ionicframework']])
* })
* }
*/
@NativePlugin({
name: 'AppLinks',
platforms: ['ios', 'android'],
engines: {
cordova: 'cordova-plugin-statusbar'
},
pluginCheck: () => {
return !!navigator.startApp;
}
})
export class AppLinks {
/**
* Open app on iOS with a given URL (iOS), or scheme (Android)
*/
static openIOS(url) {
this.ifPlugin(() => {
navigator.startApp.start(url)
})
}
/**
* Open app on Android with a given scheme and params.
*/
static openAndroid(args) {
this.ifPlugin(() => {
navigator.startApp.start(...args);
})
}
/**
* Check if an installed app can be opened from the given URL.
*/
static canOpen(urlOrScheme) {
return new Promise((resolve, reject) => {
let hasPlugin = this.ifPlugin(() => {
navigator.startApp.check(urlOrScheme, (message) => {
resolve(message);
}, function(err) {
reject(err);
});
});
if(!hasPlugin) {
reject('Plugin not installed');
}
});
}
}

View File

@@ -0,0 +1,69 @@
import * as Rx from 'rx';
import * as util from 'ionic/util';
import {NativePlugin} from '../plugin';
@NativePlugin({
name: 'Barcode',
platforms: ['ios', 'android'],
engines: {
cordova: 'phonegap-plugin-barcodescanner'
},
pluginCheck: () => {
return window.cordova && window.cordova.plugins && window.cordova.plugins.barcodeScanner;
}
})
export class Barcode {
static TEXT_TYPE = "TEXT_TYPE"
static EMAIL_TYPE = "EMAIL_TYPE"
static PHONE_TYPE = "PHONE_TYPE"
static SMS_TYPE = "SMS_TYPE"
/**
* Scan a barcode.
*
* @return Promise that resolves with an object of the format: {
* text: text that was scanned,
* format: format of barcode,
* cancelled: was it canceled?
* }
*/
static scan() {
return new Promise((resolve, reject) => {
let hasPlugin = this.ifPlugin(() => {
window.cordova.plugins.barcodeScanner.scan((result) => {
resolve(result);
}, (err) => {
reject(err);
})
});
if(!hasPlugin) {
reject('No scanner available');
}
});
}
/**
* Encode the given data in a barcode.
*
* @param type the type to use for encoding (if in doubt, use TYPE_TEXT).
* @param data the data to encode
* @return Promise
*/
static encode(type, data) {
return new Promise((resolve, reject) => {
let hasPlugin = this.ifPlugin(() => {
window.cordova.plugins.barcodeScanner.encode(type, data, (result) => {
resolve(result);
}, (err) => {
reject(err);
})
});
if(!hasPlugin) {
reject('No scanner available');
}
});
}
}

View File

@@ -0,0 +1,44 @@
import * as util from 'ionic/util';
import {NativePlugin} from '../plugin';
@NativePlugin({
name: 'Battery',
platforms: ['ios', 'android', 'web'],
engines: {
cordova: 'cordova-plugin-battery-status'
}
})
export class Battery {
static getStatus() {
return new Promise((resolve, reject) => {
if(navigator.getBattery) {
navigator.getBattery().then((battery) => {
this.battery = battery;
resolve(Battery._format(battery));
});
} else {
var fnCb = function fnCb(battery) {
resolve(battery);
window.removeEventListener('batterystatus', fnCb);
}
window.addEventListener('batterystatus', fnCb);
}
});
}
static _format(batteryObj) {
if(typeof batteryObj.isPlugged !== 'undefined') {
// This is the old format, map it to the new format
util.extend(batteryObj, {
charging: batteryObj.isPlugged,
level: batteryObj.level / 100,
chargingTime: 0, //not provided,
dischargingTime: 0 //not provided
});
}
return batteryObj;
}
}

View File

@@ -0,0 +1,45 @@
import * as Rx from 'rx';
import * as util from 'ionic/util';
import {NativePlugin} from '../plugin';
/**
* Save and load photos from the Camera Roll
*/
@NativePlugin({
name: 'CameraRoll',
platforms: ['ios'],
engines: {
cordova: 'cordova-plugin-camera-roll'
},
pluginCheck: () => {
return !!window.CameraRoll;
}
})
export class CameraRoll {
/**
* Save the base64 encoded image to the camera roll.
*/
static save(base64String) {
return new Promise((resolve, reject) => {
this.ifPlugin(() => {
window.CameraRoll.saveToCameraRoll(base64String, () => {
resolve();
}, (err) => {
reject(err);
});
})
});
}
/**
* Get photos from the camera roll
*/
static getPhotos(options) {
return new Promise((resolve, reject) => {
this.ifPlugin(() => {
window.CameraRoll.saveToCameraRoll(base64String);
})
});
}
}

View File

@@ -0,0 +1,50 @@
import * as util from 'ionic/util';
import {NativePlugin} from '../plugin';
@NativePlugin({
name: 'Camera',
platforms: ['ios', 'android'],
engines: {
cordova: 'cordova-plugin-camera'
},
pluginCheck: () => {
return !!navigator.camera;
}
})
export class Camera {
static getPicture(options) {
return new Promise((resolve, reject) => {
if (!navigator.camera) {
this.pluginWarn();
resolve(null);
return;
}
var options = util.defaults({
quality: 80,
destinationType: window.Camera.DestinationType.DATA_URL,
sourceType: window.Camera.PictureSourceType.CAMERA,
allowEdit: true,
encodingType: window.Camera.EncodingType.JPEG,
popoverOptions: window.CameraPopoverOptions,
saveToPhotoAlbum: false
}, options);
navigator.camera.getPicture(function (imageData) {
resolve(imageData);
}, function (err) {
reject(err);
}, options);
});
}
static cleanup() {
return new Promise((resolve, reject) => {
navigator.camera.cleanup(function () {
resolve();
}, function (err) {
reject(err);
});
});
}
}

View File

@@ -0,0 +1,92 @@
// install : cordova plugin add cordova-plugin-contacts
// link : https://github.com/apache/cordova-plugin-contacts
import * as Rx from 'rx';
import * as util from 'ionic/util';
import {NativePlugin} from '../plugin';
@NativePlugin({
name: 'Contacts',
platforms: ['ios', 'android'],
engines: {
cordova: 'cordova-plugin-contacts'
}
})
export class Contacts {
static save(contact) {
return new Promise((resolve, reject) => {
if(!navigator.contacts) {
this.pluginWarn();
reject('Contacts plugin not installed');
}
var deviceContact = navigator.contacts.create(contact);
deviceContact.save(function (result) {
resolve(result);
}, function (err) {
reject(err);
});
});
}
static remove(contact) {
return new Promise((resolve, reject) => {
if(!navigator.contacts) {
this.pluginWarn();
reject('Contacts plugin not installed');
}
var deviceContact = navigator.contacts.create(contact);
deviceContact.remove(function (result) {
resolve(result);
}, function (err) {
reject(err);
});
})
}
static clone(contact) {
if(!navigator.contacts) {
this.pluginWarn();
return null;
}
var deviceContact = navigator.contacts.create(contact);
return deviceContact.clone(contact);
}
static find(options) {
return new Promise((resolve, reject) => {
var fields = options.fields || ['id', 'displayName'];
delete options.fields;
if (Object.keys(options).length === 0) {
navigator.contacts.find(fields, function (results) {
resolve(results);
},function (err) {
reject(err);
});
} else {
navigator.contacts.find(fields, function (results) {
resolve(results);
}, function (err) {
reject(err);
}, options);
}
});
}
static pickContact() {
return new Promise((resolve, reject) => {
navigator.contacts.pickContact(function (contact) {
resolve(contact);
}, function (err) {
reject(err);
});
})
}
// TODO: method to set / get ContactAddress
// TODO: method to set / get ContactError
// TODO: method to set / get ContactField
// TODO: method to set / get ContactName
// TODO: method to set / get ContactOrganization
}

View File

@@ -0,0 +1,91 @@
import * as Rx from 'rx';
import * as util from 'ionic/util';
import {NativePlugin} from '../plugin';
@NativePlugin({
name: 'Device Motion',
platforms: ['ios', 'android', 'web'],
engines: {
cordova: 'cordova-plugin-device-motion'
}
})
export class DeviceMotion {
static _wrap(result) {
// Mimic the DeviceMotionEvent
return util.extend({
acceleration: result, // result will be x/y/z accel
accelerationIncludingGravity: result, //TODO: I know this isn't correct but not sure how to normalize from native plugin
rotationRate: 0,
interval: 0,
native: true
}, result);
}
static getCurrentAcceleration() {
return new Promise((resolve, reject) => {
if(window.DeviceMotionEvent || ('listenForDeviceMovement' in window)) {
var fnCb = function fnCb(eventData) {
resolve(DeviceMotion._wrap(eventData));
window.removeEventListener('devicemotion', fnCb);
}
window.addEventListener('devicemotion', fnCb);
} else if(navigator.accelerometer) {
navigator.accelerometer.getCurrentAcceleration(function (result) {
resolve(DeviceMotion._wrap(result));
}, function (err) {
reject(err);
});
} else {
this.pluginWarn();
reject('The Device does not support device motion events.');
return;
}
});
}
static watchAcceleration(options) {
if(window.DeviceMotionEvent || ('listenForDeviceMovement' in window)) {
let watchID;
let source = Rx.Observable.create((observer) => {
var fnCb = function fnCb(eventData) {
observer.onNext(DeviceMotion._wrap(eventData));
};
window.addEventListener('devicemotion', fnCb);
});
return {
source: source,
watchID: watchID,
clear: () => {
window.removeEventListener('devicemotion', fnCb);
}
}
} else if(navigator.accelerometer) {
let watchID;
let source = Rx.Observable.create((observer) => {
watchID = navigator.accelerometer.watchAcceleration(function (result) {
observer.onNext(DeviceMotion._wrap(result));
}, function (err) {
observer.onError(err, observer);
}, options);
});
return {
source: source,
watchID: watchID,
clear: () => {
navigator.accelerometer.clearWatch(watchID);
}
}
}
}
}

View File

@@ -0,0 +1,87 @@
import * as Rx from 'rx';
import * as util from 'ionic/util';
import {NativePlugin} from '../plugin';
@NativePlugin({
name: 'Device Orientation',
platforms: ['ios', 'android', 'web'],
engines: {
cordova: 'cordova-plugin-device-orientation'
}
})
export class DeviceOrientation {
static _wrap(result) {
return util.extend({
alpha: result.magneticHeading,
magneticHeading: result.webkitCompassHeading || result.alpha
}, result);
}
static getCurrentHeading() {
return new Promise((resolve, reject) => {
if(window.DeviceOrientationEvent) {
var fnCb = function fnCb(eventData) {
resolve(DeviceOrientation._wrap(eventData));
window.removeEventListener('deviceorientation', fnCb);
}
window.addEventListener('deviceorientation', fnCb);
} else if(navigator.compass) {
navigator.compass.getCurrentHeading(function (result) {
resolve(DeviceOrientation._wrap(result));
}, function (err) {
reject(err);
});
} else {
this.pluginWarn();
reject('The Device does not support device orientation events.');
return;
}
});
}
static watchHeading(options) {
if(window.DeviceOrientationEvent) {
let watchID;
let source = Rx.Observable.create((observer) => {
var fnCb = function fnCb(eventData) {
observer.onNext(DeviceOrientation._wrap(eventData));
};
window.addEventListener('deviceorientation', fnCb);
});
return {
source: source,
watchID: watchID,
clear: () => {
window.removeEventListener('deviceorientation', fnCb);
}
}
} else if(navigator.accelerometer) {
let watchID;
let source = Rx.Observable.create((observer) => {
watchID = navigator.compass.watchHeading(function (result) {
observer.onNext(DeviceOrientation._wrap(result));
}, function (err) {
observer.onError(err, observer);
}, options);
});
return {
source: source,
watchID: watchID,
clear: () => {
navigator.compass.clearWatch(watchID);
}
}
}
}
}

View File

@@ -0,0 +1,123 @@
import * as Rx from 'rx';
import * as util from 'ionic/util';
import {NativePlugin} from '../plugin';
@NativePlugin({
name: 'Device',
plugins: ['ios', 'android', 'web'],
engines: {
cordova: 'cordova-plugin-device'
},
pluginCheck: () => {
return !!window.device;
}
})
export class Device {
/**
* Returns the whole device object.
* @see https://github.com/apache/cordova-plugin-device
* @returns {Object} The device object.
*/
static getDevice() {
return this.ifPlugin(() => {
return device;
}, () => {
return {
name: Device.getName(),
model: Device.getModel(),
platform: Device.getPlatform(),
uuid: Device.getUUID(),
version: Device.getVersion()
}
});
}
/**
* Returns the Cordova version.
* @see https://github.com/apache/cordova-plugin-device#devicecordova
* @returns {String} The Cordova version.
*/
static getCordova() {
this.ifPlugin(() => {
return device.cordova;
});
}
/**
* Returns the name of the device's model or product.
* @see https://github.com/apache/cordova-plugin-device#devicemodel
* @returns {String} The name of the device's model or product.
*/
static getModel() {
this.ifPlugin(() => {
return device.model;
}, () => {
return 'unknown'
});
}
/**
* @deprecated device.name is deprecated as of version 2.3.0. Use device.model instead.
* @returns {String}
*/
static getName() {
this.ifPlugin(() => {
return device.name;
}, () => {
return 'unknown'
});
}
/**
* Returns the device's operating system name.
* @see https://github.com/apache/cordova-plugin-device#deviceplatform
* @returns {String} The device's operating system name.
*/
static getPlatform() {
this.ifPlugin(() => {
return device.name;
}, () => {
return 'unknown'
});
}
/**
* Returns the device's Universally Unique Identifier.
* @see https://github.com/apache/cordova-plugin-device#deviceuuid
* @returns {String} The device's Universally Unique Identifier
*/
static getUUID() {
this.ifPlugin(() => {
return device.uuid;
}, () => {
return 'unknown';
});
}
/**
* Returns the operating system version.
* @see https://github.com/apache/cordova-plugin-device#deviceversion
* @returns {String}
*/
static getVersion() {
this.ifPlugin(() => {
return device.version;
}, () => {
return 'unknown';
});
}
/**
* Returns the device manufacturer.
* @returns {String}
*/
static getManufacturer() {
this.ifPlugin(() => {
return device.manufacturer;
}, () => {
return 'unknown';
});
}
}

View File

@@ -0,0 +1,86 @@
import * as Rx from 'rx';
import * as util from 'ionic/util';
import {NativePlugin} from '../plugin';
/**
* A native dialogs system. Native dialogs can give you a bit more
* control over the UI than the browser built-ins, though the Dialogs
* plugin will fall back to the built-ins when necessary.
*/
@NativePlugin({
name: 'Dialogs',
platforms: ['ios', 'android', 'web'],
engines: {
cordova: 'cordova-plugin-dialogs'
}
})
export class Dialogs {
/**
* Trigger an alert prompt.
*
* @param message the message to show
* @param title the title to show
* @param buttonName the button label to use (not available on browser fallback)
* @return Promise
*/
static alert(message, title, buttonName) {
return new Promise((resolve,reject) => {
if(!navigator.notification) {
this.pluginWarn();
alert(message);
resolve();
} else {
navigator.notification.alert(message, () => {
resolve();
}, title, buttonName);
}
});
}
/**
* Trigger a confirm prompt.
*
* @param message the message to show
* @param title the title to show
* @param buttonLabels the button labels to use (not available on browser fallback)
* @return Promise that resolves with the index of the button selected (zero indexed). 1 is OK on browser fallback
*/
static confirm(message, title, buttonLabels) {
return new Promise((resolve,reject) => {
if(!navigator.notification) {
this.pluginWarn();
var ok = confirm(message);
// Use 2 as OK
resolve(ok ? 2 : 0);
} else {
navigator.notification.confirm(message, (buttonIndex) => {
resolve(buttonIndex - 1);
}, title, buttonLabels);
}
});
}
static prompt(message, title, buttonLabels, defaultText) {
return new Promise((resolve,reject) => {
if(!navigator.notification) {
this.pluginWarn();
var response = prompt(message);
// Use 1 as OK
resolve(response);
} else {
navigator.notification.prompt(message, (results) => {
resolve(results.input1, buttonIndex - 1);
}, title, buttonLabels, defaultText);
}
});
}
/**
* Beep n times. Not available on browser.
* @param times the number of times to beep
*/
static beep(times) {
navigator.notification && navigator.notification.beep(times);
}
}

View File

@@ -0,0 +1,47 @@
import * as Rx from 'rx';
import * as util from 'ionic/util';
import {NativePlugin} from '../plugin';
@NativePlugin({
name: 'Geolocation',
platforms: ['ios', 'android', 'web'],
engines: {
cordova: 'cordova-plugin-geolocation'
}
})
export class Geolocation {
static getCurrentPosition(options) {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(function (result) {
resolve(result);
}, function (err) {
reject(err);
}, options);
});
}
static watchPosition(options) {
let watchID;
let source = Rx.Observable.create((observer) => {
watchID = navigator.geolocation.watchPosition(function (result) {
observer.onNext(result)
}, function(err) {
observer.onError(err, observer);
}, options);
})
return {
source: source,
watchID: watchID,
clear: () => {
navigator.geolocation.clearWatch(watchID);
}
}
}
static clearWatch(watchID) {
return navigator.geolocation.clearWatch(watchID);
}
}

View File

@@ -0,0 +1,62 @@
import * as Rx from 'rx';
import * as util from 'ionic/util';
import {NativePlugin} from '../plugin';
/**
* Manage the native keyboard. Note: this plugin performs mainly in the native
* app context. Most operations are non-functional in a normal web browser as
* keyboard control is limited.
*/
@NativePlugin({
name: 'Keyboard',
platforms: ['ios', 'android'],
engines: {
cordova: 'ionic-plugin-keyboard'
},
pluginCheck: () => {
return window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard;
}
})
export class Keyboard {
/**
* Set whether the accessory bar is visible.
*
* Note: this only works while running natively (accessory bar cannot be removed
* in most web browsers), and by default the bar is hidden when running natively.
*
* @param isVisible whether the accessory bar is visible
*/
static setAccessoryBarVisible(isVisible) {
this.ifPlugin(() => {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(!isVisible);
})
}
/**
* Close the keyboard.
*/
static close() {
this.ifPlugin(() => {
cordova.plugins.Keyboard.close();
})
}
/**
* Show the keyboard. Does nothing on iOS (has to be triggered from an input)
*/
static show() {
this.ifPlugin(() => {
cordova.plugins.Keyboard.show();
})
}
/**
* @return the visibility of the keyboard.
*/
static isVisible() {
return this.ifPlugin(() => {
return cordova.plugins.Keyboard.isVisible;
});
}
}

View File

@@ -0,0 +1,89 @@
import * as Rx from 'rx';
import * as util from 'ionic/util';
import {NativePlugin} from '../plugin';
/**
* Simple loading popup indicators.
*/
@NativePlugin({
name: 'Loading',
platforms: ['ios', 'android', 'web'],
engines: {
cordova: 'cordova-plugin-progressindicator'
},
pluginCheck: () => {
return !!window.ProgressIndicator;
}
})
export class Loading {
static simple(dim, label, detail) {
this.ifPlugin(() => {
if(typeof label === 'undefined') {
window.ProgressIndicator.showSimple(dim);
return;
}
if(typeof detail === 'undefined') {
window.ProgressIndicator.showSimpleWithLabel(dim, label);
return;
}
window.ProgressIndicator.showSimpleWithLabelDetail(dim, label, detail);
})
}
static determinate(dim, timeout, label) {
this.ifPlugin(() => {
if(typeof label === 'undefined') {
window.ProgressIndicator.showDeterminate(dim, timeout);
return;
}
if(typeof detail === 'undefined') {
window.ProgressIndicator.showSimpleWithLabel(dim, timeout, label);
return;
}
})
}
static annular(dim, timeout, label) {
this.ifPlugin(() => {
if(typeof label === 'undefined') {
window.ProgressIndicator.showAnnular(dim, timeout);
return;
}
if(typeof detail === 'undefined') {
window.ProgressIndicator.showAnnularWithLabel(dim, timeout, label);
return;
}
})
}
static bar(dim, timeout, label) {
this.ifPlugin(() => {
if(typeof label === 'undefined') {
window.ProgressIndicator.showBar(dim, timeout);
return;
}
if(typeof detail === 'undefined') {
window.ProgressIndicator.showBarWithLabel(dim, timeout, label);
return;
}
})
}
static success(dim, label) {
this.ifPlugin(() => {
window.ProgressIndicator.showSuccess(dim, label);
})
}
static hide() {
this.ifPlugin(() => {
window.ProgressIndicator.hide();
})
}
}

54
ionic/platform/plugin.ts Normal file
View File

@@ -0,0 +1,54 @@
export class NativePluginDecorator {
constructor(cls, config) {
this.cls = cls;
this.config = config;
cls.ifPlugin = (cb, returnType=null) => {
// Convert to boolean the plugin param
var exists = !!check;
if(typeof this.config.pluginCheck === 'function') {
exists = this.config.pluginCheck();
}
if(exists) {
return cb();
}
// We don't have the plugin, so print a warning message
cls.pluginWarn();
// If the user supplied a default return value, return it here.
if(returnType) {
return (typeof returnType === 'function') ? returnType() : returnType;
}
return false;
};
cls.pluginWarn = () => {
if(cls._pluginWarned) {
// Only warn once
return;
}
let platformString = [];
for(var k in this.config.engines) {
platformString.push('\t' + k + ': '+ this.config.engines[k]);
}
console.warn('Plugin for ' + this.config.name +
' not installed. For native functionality, please install the correct plugin for your platform:\n' +
platformString.join('\n'));
// Set a flag so we don't warn again
cls._pluginWarned = true;
}
}
}
export function NativePlugin(config) {
return function(cls) {
var annotations = Reflect.getMetadata('annotations', cls) || [];
annotations.push(new NativePluginDecorator(cls, config));
Reflect.defineMetadata('annotations', annotations, cls);
return cls;
}
}

14
ionic/platform/plugins.ts Normal file
View File

@@ -0,0 +1,14 @@
export * from './plugin'
export * from './applinks/applinks'
export * from './barcode/barcode'
export * from './battery/battery'
export * from './camera/camera'
export * from './contacts/contacts'
export * from './dialogs/dialogs'
export * from './device/device'
export * from './device-motion/device-motion'
export * from './device-orientation/device-orientation'
export * from './geolocation/geolocation'
export * from './keyboard/keyboard'
export * from './statusbar/statusbar'
export * from './vibration/vibration'

View File

@@ -0,0 +1,112 @@
import * as Rx from 'rx';
import * as util from 'ionic/util';
import {NativePlugin} from '../plugin';
/**
* Manage the appearance of the native status bar.
*/
@NativePlugin({
name: 'StatusBar',
platforms: ['ios', 'android'],
engines: {
cordova: 'cordova-plugin-statusbar'
},
pluginCheck: () => {
return !!window.StatusBar;
}
})
export class StatusBar {
static DEFAULT = 0
static LIGHT_CONTENT = 1
static BLACK_TRANSLUCENT = 2
static BLACK_OPAQUE = 3
/**
* Show the StatusBar
*/
static show() {
this.ifPlugin(() => {
window.StatusBar.show();
})
}
/**
* Hide the StatusBar
*/
static hide() {
this.ifPlugin(() => {
window.StatusBar.hide();
})
}
/**
* Hide the StatusBar
*
* Options:
*
* StatusBar.DEFAULT
* StatusBar.LIGHT_CONTENT
* StatusBar.BLACK_TRANSLUCENT
* StatusBar.BLACK_OPAQUE
*
* @param style the style from above
*/
static setStyle(style) {
this.ifPlugin(() => {
switch(style) {
case StatusBar.DEFAULT:
window.StatusBar.styleDefault();
break;
case StatusBar.LIGHT_CONTENT:
window.StatusBar.styleLightContent();
break;
case StatusBar.BLACK_TRANSLUCENT:
window.StatusBar.styleBlackTranslucent();
break;
case StatusBar.BLACK_OPAQUE:
window.StatusBar.styleBlackOpaque();
break;
}
})
}
/**
* Set the status bar to a specific hex color (CSS shorthand supported!).
*
* iOS note: you must call StatusBar.setOverlay(false) to enable color changing.
*
* @param hex the hex value of the color.
*/
static setHexColor(hex) {
this.ifPlugin(() => {
window.StatusBar.backgroundColorByHexName(hex);
});
}
/**
* Set the status bar to a specific named color. Valid options:
* black, darkGray, lightGray, white, gray, red, green, blue, cyan, yellow, magenta, orange, purple, brown.
*
* iOS note: you must call StatusBar.setOverlay(false) to enable color changing.
*
* @param name the name of the color (from above)
*/
static setNamedColor(name) {
this.ifPlugin(() => {
window.StatusBar.backgroundColorByName(name);
});
}
/**
* Set whether the status bar overlays the main app view. The default
* is true.
*
* @param doesOverlay whether the status bar overlays the main app view.
*/
static setOverlays(doesOverlay) {
this.ifPlugin(() => {
window.StatusBar.overlaysWebView(doesOverlay);
});
}
}

View File

@@ -0,0 +1,48 @@
import {StorageEngine} from './storage';
/**
* The LocalStorage storage engine uses the browser's local storage system for
* storing key/value pairs.
*
* Note: LocalStorage should ONLY be used for temporary data that you can afford to lose.
* Given disk space constraints on a mobile device, local storage might be "cleaned up"
* by the operating system (iOS).
*
* For guaranteed, long-term storage, use the SqlStorage engine which stores data in a file.
*/
export class LocalStorage extends StorageEngine {
constructor() {
super();
}
get(key) {
return new Promise((resolve, reject) => {
try {
let value = window.localStorage.getItem(key);
resolve(value);
} catch(e) {
reject(e);
}
});
}
set(key, value) {
return new Promise((resolve, reject) => {
try {
window.localStorage.setItem(key, value);
resolve();
} catch(e) {
reject(e);
}
});
}
remove(key) {
return new Promise((resolve, reject) => {
try {
window.localStorage.removeItem(key);
resolve();
} catch(e) {
reject(e);
}
});
}
}

View File

@@ -0,0 +1,180 @@
import {StorageEngine} from './storage';
import * as util from 'ionic/util';
const DB_NAME = '__ionicstorage';
/**
* SqlStorage uses SQLite or WebSQL (development only!) to store data in a
* persistent SQL store on the filesystem.
*
* This is the preferred storage engine, as data will be stored in appropriate
* app storage, unlike Local Storage which is treated differently by the OS.
*/
export class SqlStorage extends StorageEngine {
static BACKUP_LOCAL = 2
static BACKUP_LIBRARY = 1
static BACKUP_DOCUMENTS = 0
constructor(options) {
super();
let dbOptions = util.defaults({
name: DB_NAME,
backupFlag: SqlStorage.BACKUP_NONE,
existingDatabase: false
}, options);
if(window.sqlitePlugin) {
let location = this._getBackupLocation(dbOptions);
this._db = window.sqlitePlugin.openDatabase(util.extend({
name: dbOptions.name,
location: location,
createFromLocation: dbOptions.existingDatabase ? 1 : 0
}, dbOptions));
} else {
console.warn('Storage: SQLite plugin not installed, falling back to WebSQL. Make sure to install cordova-sqlite-storage in production!');
this._db = window.openDatabase(dbOptions.name, '1.0', 'database', 5 * 1024 * 1024);
}
this._tryInit();
}
_getBackupLocation(dbFlag) {
switch(dbFlag) {
case SqlStorage.BACKUP_LOCAL:
return 2;
case SqlStorage.BACKUP_LIBRARY:
return 1;
case SqlStorage.BACKUP_DOCUMENTS:
return 0;
default:
throw Error('Invalid backup flag: ' + dbFlag);
}
}
// Initialize the DB with our required tables
_tryInit() {
this._db.transaction((tx) => {
tx.executeSql('CREATE TABLE IF NOT EXISTS kv (key text primary key, value text)', [], (tx, res) => {
}, (tx, err) => {
console.error('Storage: Unable to create initial storage tables', tx, err);
});
});
}
/**
* Perform an arbitrary SQL operation on the database. Use this method
* to have full control over the underlying database through SQL operations
* like SELECT, INSERT, and UPDATE.
*
* @param {string} query the query to run
* @return {Promise} that resolves or rejects with an object of the form { tx: Transaction, res: Result (or err)}
*/
query(query) {
return new Promise((resolve, reject) => {
this._db.transaction((tx) => {
ts.executeSql(query, [], (tx, res) => {
resolve({
tx: tx,
res: res
});
}, (tx, err) => {
reject({
tx: tx,
err: err
});
})
});
})
}
/**
* Get the value in the database identified by the given key.
* @param {string} key the key
* @return {Promise} that resolves or rejects with an object of the form { tx: Transaction, res: Result (or err)}
*/
get(key) {
return new Promise((resolve, reject) => {
try {
this._db.transaction(tx => {
tx.executeSql("select key, value from kv where key = ? limit 1", [key], (tx, res) => {
if(res.rows.length > 0) {
let item = res.rows.item(0);
resolve(item.value);
}
resolve(null);
}, (tx, err) => {
reject({
tx: tx,
err: err
});
})
}, err => {
reject(err);
});
} catch(e) {
reject(e);
}
});
}
/**
* Set the value in the database for the given key. Existing values will be overwritten.
* @param {string} key the key
* @param {string} value The value (as a string)
* @return {Promise} that resolves or rejects with an object of the form { tx: Transaction, res: Result (or err)}
*/
set(key, value) {
return new Promise((resolve, reject) => {
try {
this._db.transaction(tx => {
tx.executeSql('insert or replace into kv(key, value) values (?, ?)', [key, value], (tx, res) => {
resolve();
}, (tx, err) => {
reject({
tx: tx,
err: err
});
})
}, err => {
reject(err);
});
} catch(e) {
reject(e);
}
});
}
/**
* Remove the value in the database for the given key.
* @param {string} key the key
* @param {string} value The value (as a string)
* @return {Promise} that resolves or rejects with an object of the form { tx: Transaction, res: Result (or err)}
*/
remove(key) {
return new Promise((resolve, reject) => {
try {
this._db.transaction(tx => {
tx.executeSql('delete from kv where key = ?', [key], (tx, res) => {
resolve();
}, (tx, err) => {
reject({
tx: tx,
err: err
});
})
}, err => {
reject(err);
});
} catch(e) {
reject(e);
}
});
}
}

View File

@@ -0,0 +1,49 @@
/**
* Storage is an easy way to store key/value pairs and other complicated
* data in a way that uses a variety of storage engines underneath.
*
* For most cases, we recommend the SqlStorage system as it will store
* data in a file in the app's sandbox. LocalStorage should ONLY be used
* for temporary data as it may be "cleaned up" by the operation system
* during low disk space situations.
*/
export class Storage {
constructor(strategyCls: StorageEngine) {
this._strategy = new strategyCls();
}
get(key) {
return this._strategy.get(key);
}
getJson(key) {
try {
return JSON.parse(this._strategy.get(key));
} catch(e) {
console.warn('Storage getJson(): unable to parse value for key', key,' as JSON')
return null;
}
}
set(key, value) {
return this._strategy.set(key, value);
}
remove(key) {
return this._strategy.remove(key);
}
query(query) {
return this._strategy.query(key);
}
}
export class StorageEngine {
get(key, value) {
throw Error("get() not implemented for this storage engine");
}
set(key, value) {
throw Error("set() not implemented for this storage engine");
}
remove(key) {
throw Error("remove() not implemented for this storage engine");
}
query(query) {
throw Error("query() not implemented for this storage engine");
}
}

View File

@@ -0,0 +1,22 @@
import * as Rx from 'rx';
import * as util from 'ionic/util';
import {NativePlugin} from '../plugin';
@NativePlugin({
name: 'Vibration',
platforms: ['ios', 'android', 'web'],
engines: {
cordova: 'cordova-plugin-vibration'
}
})
export class Vibration {
static vibrate(pattern) {
if(!navigator.vibrate) {
this.pluginWarn();
console.log('Vibrate (dev): ', pattern);
} else {
navigator.vibrate(pattern);
}
}
}