refactor(core): beautify files and reorder imports

This commit is contained in:
Daniel 2018-04-08 18:48:55 +02:00
parent 15c73e46d0
commit 4be721b8f5
7 changed files with 408 additions and 195 deletions

View File

@ -9,13 +9,17 @@ export function checkReady() {
let didFireReady = false;
document.addEventListener('deviceready', () => {
console.log(`Ionic Native: deviceready event fired after ${(Date.now() - before)} ms`);
console.log(
`Ionic Native: deviceready event fired after ${Date.now() - before} ms`
);
didFireReady = true;
});
setTimeout(() => {
if (!didFireReady && !!window.cordova) {
console.warn(`Ionic Native: deviceready did not fire within ${DEVICE_READY_TIMEOUT}ms. This can happen when plugins are in an inconsistent state. Try removing plugins from plugins/ and reinstalling them.`);
console.warn(
`Ionic Native: deviceready did not fire within ${DEVICE_READY_TIMEOUT}ms. This can happen when plugins are in an inconsistent state. Try removing plugins from plugins/ and reinstalling them.`
);
}
}, DEVICE_READY_TIMEOUT);
}

View File

@ -1,24 +1,34 @@
import 'core-js';
import { Plugin, Cordova, CordovaProperty, CordovaCheck, CordovaInstance, InstanceProperty } from './decorators';
import { Observable } from 'rxjs/Observable';
import {
Cordova,
CordovaCheck,
CordovaInstance,
CordovaProperty,
InstanceProperty,
Plugin
} from './decorators';
import { IonicNativePlugin } from './ionic-native-plugin';
import { ERR_CORDOVA_NOT_AVAILABLE, ERR_PLUGIN_NOT_INSTALLED } from './plugin';
import { Observable } from 'rxjs/Observable';
declare const window: any;
class TestObject {
constructor(public _objectInstance: any) {}
@InstanceProperty
name: string;
@InstanceProperty name: string;
@CordovaInstance({ sync: true })
pingSync(): string { return; }
pingSync(): string {
return;
}
@CordovaInstance()
ping(): Promise<any> { return; }
ping(): Promise<any> {
return;
}
}
@Plugin({
@ -29,15 +39,17 @@ class TestObject {
platforms: ['Android', 'iOS']
})
class TestPlugin extends IonicNativePlugin {
@CordovaProperty
name: string;
@CordovaProperty name: string;
@Cordova({ sync: true })
pingSync(): string { return; }
pingSync(): string {
return;
}
@Cordova()
ping(): Promise<string> { return; }
ping(): Promise<string> {
return;
}
@CordovaCheck()
customPing(): Promise<string> {
@ -51,14 +63,17 @@ class TestPlugin extends IonicNativePlugin {
@Cordova({
destruct: true
})
destructPromise(): Promise<any> { return; }
destructPromise(): Promise<any> {
return;
}
@Cordova({
destruct: true,
observable: true
})
destructObservable(): Observable<any> { return; }
destructObservable(): Observable<any> {
return;
}
}
function definePlugin() {
@ -78,7 +93,6 @@ function definePlugin() {
}
describe('Regular Decorators', () => {
let plugin: TestPlugin;
beforeEach(() => {
@ -87,7 +101,6 @@ describe('Regular Decorators', () => {
});
describe('Plugin', () => {
it('should set pluginName', () => {
expect(TestPlugin.getPluginName()).toEqual('TestPlugin');
});
@ -103,17 +116,16 @@ describe('Regular Decorators', () => {
it('should return supported platforms', () => {
expect(TestPlugin.getSupportedPlatforms()).toEqual(['Android', 'iOS']);
});
});
describe('Cordova', () => {
it('should do a sync function', () => {
expect(plugin.pingSync()).toEqual('pong');
});
it('should do an async function', (done: Function) => {
plugin.ping()
plugin
.ping()
.then(res => {
expect(res).toEqual('pong');
done();
@ -125,39 +137,31 @@ describe('Regular Decorators', () => {
});
it('should throw plugin_not_installed error', (done: Function) => {
delete window.testPlugin;
window.cordova = true;
expect(<any>plugin.pingSync()).toEqual(ERR_PLUGIN_NOT_INSTALLED);
plugin.ping()
.catch(e => {
expect(e).toEqual(ERR_PLUGIN_NOT_INSTALLED.error);
delete window.cordova;
done();
});
plugin.ping().catch(e => {
expect(e).toEqual(ERR_PLUGIN_NOT_INSTALLED.error);
delete window.cordova;
done();
});
});
it('should throw cordova_not_available error', (done: Function) => {
delete window.testPlugin;
expect(<any>plugin.pingSync()).toEqual(ERR_CORDOVA_NOT_AVAILABLE);
plugin.ping()
.catch(e => {
expect(e).toEqual(ERR_CORDOVA_NOT_AVAILABLE.error);
done();
});
plugin.ping().catch(e => {
expect(e).toEqual(ERR_CORDOVA_NOT_AVAILABLE.error);
done();
});
});
});
describe('CordovaProperty', () => {
it('should return property value', () => {
expect(plugin.name).toEqual('John Smith');
});
@ -166,61 +170,47 @@ describe('Regular Decorators', () => {
plugin.name = 'value2';
expect(plugin.name).toEqual('value2');
});
});
describe('CordovaCheck', () => {
it('should run the method when plugin exists', (done) => {
plugin.customPing()
.then(res => {
expect(res).toEqual('pong');
done();
});
it('should run the method when plugin exists', done => {
plugin.customPing().then(res => {
expect(res).toEqual('pong');
done();
});
});
it('shouldnt run the method when plugin doesnt exist', (done) => {
it('shouldnt run the method when plugin doesnt exist', done => {
delete window.testPlugin;
window.cordova = true;
plugin.customPing()
.catch(e => {
expect(e).toEqual(ERR_PLUGIN_NOT_INSTALLED.error);
done();
});
plugin.customPing().catch(e => {
expect(e).toEqual(ERR_PLUGIN_NOT_INSTALLED.error);
done();
});
});
});
describe('CordovaOptions', () => {
describe('destruct', () => {
it('should destruct values returned by a Promise', (done) => {
plugin.destructPromise()
.then((args: any[]) => {
expect(args).toEqual(['hello', 'world']);
done();
});
it('should destruct values returned by a Promise', done => {
plugin.destructPromise().then((args: any[]) => {
expect(args).toEqual(['hello', 'world']);
done();
});
});
it('should destruct values returned by an Observable', (done) => {
plugin.destructObservable()
.subscribe((args: any[]) => {
expect(args).toEqual(['hello', 'world']);
done();
});
it('should destruct values returned by an Observable', done => {
plugin.destructObservable().subscribe((args: any[]) => {
expect(args).toEqual(['hello', 'world']);
done();
});
});
});
});
});
describe('Instance Decorators', () => {
let instance: TestObject,
plugin: TestPlugin;
let instance: TestObject, plugin: TestPlugin;
beforeEach(() => {
definePlugin();
@ -228,20 +218,14 @@ describe('Instance Decorators', () => {
instance = plugin.create();
});
describe('Instance plugin', () => {
});
describe('Instance plugin', () => {});
describe('CordovaInstance', () => {
it('should call instance async method', (done) => {
instance.ping()
.then(r => {
expect(r).toEqual('pong');
done();
});
it('should call instance async method', done => {
instance.ping().then(r => {
expect(r).toEqual('pong');
done();
});
});
it('should call instance sync method', () => {
@ -249,18 +233,16 @@ describe('Instance Decorators', () => {
});
it('shouldnt call instance method when _objectInstance is undefined', () => {
delete instance._objectInstance;
instance.ping()
instance
.ping()
.then(r => {
expect(r).toBeUndefined();
})
.catch(e => {
expect(e).toBeUndefined();
});
});
});
describe('InstanceProperty', () => {
@ -273,5 +255,4 @@ describe('Instance Decorators', () => {
expect(instance.name).toEqual('John Cena');
});
});
});

View File

@ -1,8 +1,16 @@
import { instanceAvailability, checkAvailability, wrap, wrapInstance, overrideFunction } from './plugin';
import { getPlugin, getPromise } from './util';
import { Observable } from 'rxjs/Observable';
import 'rxjs/observable/throw';
import { Observable } from 'rxjs/Observable';
import {
checkAvailability,
instanceAvailability,
overrideFunction,
wrap,
wrapInstance
} from './plugin';
import { getPlugin, getPromise } from './util';
export interface PluginConfig {
/**
* Plugin name, this should match the class name
@ -109,21 +117,23 @@ export interface CordovaCheckOptions {
* @private
*/
export function InstanceCheck(opts: CordovaCheckOptions = {}) {
return (pluginObj: Object, methodName: string, descriptor: TypedPropertyDescriptor<any>): TypedPropertyDescriptor<any> => {
return (
pluginObj: Object,
methodName: string,
descriptor: TypedPropertyDescriptor<any>
): TypedPropertyDescriptor<any> => {
return {
value: function(...args: any[]): any {
if (instanceAvailability(this)) {
return descriptor.value.apply(this, args);
} else {
if (opts.sync) {
return;
} else if (opts.observable) {
return new Observable<any>(() => { });
return new Observable<any>(() => {});
}
return getPromise(() => { });
return getPromise(() => {});
}
},
enumerable: true
@ -136,7 +146,11 @@ export function InstanceCheck(opts: CordovaCheckOptions = {}) {
* @private
*/
export function CordovaCheck(opts: CordovaCheckOptions = {}) {
return (pluginObj: Object, methodName: string, descriptor: TypedPropertyDescriptor<any>): TypedPropertyDescriptor<any> => {
return (
pluginObj: Object,
methodName: string,
descriptor: TypedPropertyDescriptor<any>
): TypedPropertyDescriptor<any> => {
return {
value: function(...args: any[]): any {
const check = checkAvailability(pluginObj);
@ -177,7 +191,6 @@ export function CordovaCheck(opts: CordovaCheckOptions = {}) {
*/
export function Plugin(config: PluginConfig): ClassDecorator {
return function(cls: any) {
// Add these fields to the class
for (let prop in config) {
cls[prop] = config[prop];
@ -226,7 +239,11 @@ export function Plugin(config: PluginConfig): ClassDecorator {
* and the required plugin are installed.
*/
export function Cordova(opts: CordovaOptions = {}) {
return (target: Object, methodName: string, descriptor: TypedPropertyDescriptor<any>) => {
return (
target: Object,
methodName: string,
descriptor: TypedPropertyDescriptor<any>
) => {
return {
value: function(...args: any[]) {
return wrap(this, methodName, opts).apply(this, args);
@ -268,7 +285,7 @@ export function CordovaProperty(target: any, key: string) {
return null;
}
},
set: (value) => {
set: value => {
if (checkAvailability(target, key) === true) {
getPlugin(target.constructor.getPluginRef())[key] = value;
}
@ -301,7 +318,11 @@ export function InstanceProperty(target: any, key: string) {
* and the required plugin are installed.
*/
export function CordovaFunctionOverride(opts: any = {}) {
return (target: Object, methodName: string, descriptor: TypedPropertyDescriptor<any>) => {
return (
target: Object,
methodName: string,
descriptor: TypedPropertyDescriptor<any>
) => {
return {
value: function(...args: any[]) {
return overrideFunction(this, methodName, opts);
@ -310,4 +331,3 @@ export function CordovaFunctionOverride(opts: any = {}) {
};
};
}

View File

@ -1,8 +1,7 @@
// This is to verify that new (FileTransfer.getPlugin)() works
import { Plugin, CordovaInstance } from './decorators';
import { checkAvailability } from './plugin';
import { CordovaInstance, Plugin } from './decorators';
import { IonicNativePlugin } from './ionic-native-plugin';
import { checkAvailability } from './plugin';
class FT {
hello(): string {
@ -21,7 +20,13 @@ class FT {
export class FileTransfer extends IonicNativePlugin {
create(): FileTransferObject {
let instance: any;
if (checkAvailability(FileTransfer.getPluginRef(), null, FileTransfer.getPluginName()) === true) {
if (
checkAvailability(
FileTransfer.getPluginRef(),
null,
FileTransfer.getPluginName()
) === true
) {
instance = new (FileTransfer.getPlugin())();
}
return new FileTransferObject(instance);
@ -29,20 +34,21 @@ export class FileTransfer extends IonicNativePlugin {
}
export class FileTransferObject {
constructor(public _objectInstance: any) {
console.info('Creating a new FileTransferObject with instance: ', _objectInstance);
console.info(
'Creating a new FileTransferObject with instance: ',
_objectInstance
);
}
@CordovaInstance({ sync: true })
hello(): string { return; }
hello(): string {
return;
}
}
describe('Mock FileTransfer Plugin', () => {
let plugin: FileTransfer,
instance: FileTransferObject;
let plugin: FileTransfer, instance: FileTransferObject;
beforeAll(() => {
plugin = new FileTransfer();
@ -65,5 +71,4 @@ describe('Mock FileTransfer Plugin', () => {
console.info('instance hello is', instance.hello());
expect(instance.hello()).toEqual('world');
});
});

View File

@ -1,5 +1,4 @@
export class IonicNativePlugin {
static pluginName: string;
static pluginRef: string;
@ -16,31 +15,40 @@ export class IonicNativePlugin {
* Returns a boolean that indicates whether the plugin is installed
* @return {boolean}
*/
static installed(): boolean { return false; }
static installed(): boolean {
return false;
}
/**
* Returns the original plugin object
*/
static getPlugin(): any { }
static getPlugin(): any {}
/**
* Returns the plugin's name
*/
static getPluginName(): string { return; }
static getPluginName(): string {
return;
}
/**
* Returns the plugin's reference
*/
static getPluginRef(): string { return; }
static getPluginRef(): string {
return;
}
/**
* Returns the plugin's install name
*/
static getPluginInstallName(): string { return; }
static getPluginInstallName(): string {
return;
}
/**
* Returns the plugin's supported platforms
*/
static getSupportedPlatforms(): string[] { return; }
static getSupportedPlatforms(): string[] {
return;
}
}

View File

@ -1,9 +1,10 @@
import { getPlugin, getPromise, cordovaWarn, pluginWarn } from './util';
import { checkReady } from './bootstrap';
import { CordovaOptions } from './decorators';
import 'rxjs/add/observable/fromEvent';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import { checkReady } from './bootstrap';
import { CordovaOptions } from './decorators';
import { cordovaWarn, getPlugin, getPromise, pluginWarn } from './util';
checkReady();
@ -13,16 +14,26 @@ checkReady();
export const ERR_CORDOVA_NOT_AVAILABLE = { error: 'cordova_not_available' };
export const ERR_PLUGIN_NOT_INSTALLED = { error: 'plugin_not_installed' };
/**
* Checks if plugin/cordova is available
* @return {boolean | { error: string } }
* @private
*/
export function checkAvailability(pluginRef: string, methodName?: string, pluginName?: string): boolean | { error: string };
export function checkAvailability(pluginObj: any, methodName?: string, pluginName?: string): boolean | { error: string };
export function checkAvailability(plugin: any, methodName?: string, pluginName?: string): boolean | { error: string } {
export function checkAvailability(
pluginRef: string,
methodName?: string,
pluginName?: string
): boolean | { error: string };
export function checkAvailability(
pluginObj: any,
methodName?: string,
pluginName?: string
): boolean | { error: string };
export function checkAvailability(
plugin: any,
methodName?: string,
pluginName?: string
): boolean | { error: string } {
let pluginRef, pluginInstance, pluginPackage;
if (typeof plugin === 'string') {
@ -35,7 +46,10 @@ export function checkAvailability(plugin: any, methodName?: string, pluginName?:
pluginInstance = getPlugin(pluginRef);
if (!pluginInstance || (!!methodName && typeof pluginInstance[methodName] === 'undefined')) {
if (
!pluginInstance ||
(!!methodName && typeof pluginInstance[methodName] === 'undefined')
) {
if (!window.cordova) {
cordovaWarn(pluginName, methodName);
return ERR_CORDOVA_NOT_AVAILABLE;
@ -52,11 +66,23 @@ export function checkAvailability(plugin: any, methodName?: string, pluginName?:
* Checks if _objectInstance exists and has the method/property
* @private
*/
export function instanceAvailability(pluginObj: any, methodName?: string): boolean {
return pluginObj._objectInstance && (!methodName || typeof pluginObj._objectInstance[methodName] !== 'undefined');
export function instanceAvailability(
pluginObj: any,
methodName?: string
): boolean {
return (
pluginObj._objectInstance &&
(!methodName ||
typeof pluginObj._objectInstance[methodName] !== 'undefined')
);
}
function setIndex(args: any[], opts: any = {}, resolve?: Function, reject?: Function): any {
function setIndex(
args: any[],
opts: any = {},
resolve?: Function,
reject?: Function
): any {
// ignore resolve and reject in case sync
if (opts.sync) {
return args;
@ -75,12 +101,19 @@ function setIndex(args: any[], opts: any = {}, resolve?: Function, reject?: Func
resolve(result);
}
});
} else if (opts.callbackStyle === 'object' && opts.successName && opts.errorName) {
} else if (
opts.callbackStyle === 'object' &&
opts.successName &&
opts.errorName
) {
let obj: any = {};
obj[opts.successName] = resolve;
obj[opts.errorName] = reject;
args.push(obj);
} else if (typeof opts.successIndex !== 'undefined' || typeof opts.errorIndex !== 'undefined') {
} else if (
typeof opts.successIndex !== 'undefined' ||
typeof opts.errorIndex !== 'undefined'
) {
const setSuccessIndex = () => {
// If we've specified a success/error index
if (opts.successIndex > args.length) {
@ -106,8 +139,6 @@ function setIndex(args: any[], opts: any = {}, resolve?: Function, reject?: Func
setSuccessIndex();
setErrorIndex();
}
} else {
// Otherwise, let's tack them on to the end of the argument list
// which is 90% of cases
@ -117,7 +148,14 @@ function setIndex(args: any[], opts: any = {}, resolve?: Function, reject?: Func
return args;
}
function callCordovaPlugin(pluginObj: any, methodName: string, args: any[], opts: any = {}, resolve?: Function, reject?: Function) {
function callCordovaPlugin(
pluginObj: any,
methodName: string,
args: any[],
opts: any = {},
resolve?: Function,
reject?: Function
) {
// Try to figure out where the success/error callbacks need to be bound
// to our promise resolve/reject handlers.
args = setIndex(args, opts, resolve, reject);
@ -130,16 +168,34 @@ function callCordovaPlugin(pluginObj: any, methodName: string, args: any[], opts
} else {
return availabilityCheck;
}
}
function wrapPromise(pluginObj: any, methodName: string, args: any[], opts: any = {}) {
function wrapPromise(
pluginObj: any,
methodName: string,
args: any[],
opts: any = {}
) {
let pluginResult: any, rej: Function;
const p = getPromise((resolve: Function, reject: Function) => {
if (opts.destruct) {
pluginResult = callCordovaPlugin(pluginObj, methodName, args, opts, (...args: any[]) => resolve(args), (...args: any[]) => reject(args));
pluginResult = callCordovaPlugin(
pluginObj,
methodName,
args,
opts,
(...args: any[]) => resolve(args),
(...args: any[]) => reject(args)
);
} else {
pluginResult = callCordovaPlugin(pluginObj, methodName, args, opts, resolve, reject);
pluginResult = callCordovaPlugin(
pluginObj,
methodName,
args,
opts,
resolve,
reject
);
}
rej = reject;
});
@ -147,13 +203,18 @@ function wrapPromise(pluginObj: any, methodName: string, args: any[], opts: any
// a warning that Cordova is undefined or the plugin is uninstalled, so there is no reason
// to error
if (pluginResult && pluginResult.error) {
p.catch(() => { });
p.catch(() => {});
typeof rej === 'function' && rej(pluginResult.error);
}
return p;
}
function wrapOtherPromise(pluginObj: any, methodName: string, args: any[], opts: any = {}) {
function wrapOtherPromise(
pluginObj: any,
methodName: string,
args: any[],
opts: any = {}
) {
return getPromise((resolve: Function, reject: Function) => {
const pluginResult = callCordovaPlugin(pluginObj, methodName, args, opts);
if (pluginResult) {
@ -168,14 +229,33 @@ function wrapOtherPromise(pluginObj: any, methodName: string, args: any[], opts:
});
}
function wrapObservable(pluginObj: any, methodName: string, args: any[], opts: any = {}) {
function wrapObservable(
pluginObj: any,
methodName: string,
args: any[],
opts: any = {}
) {
return new Observable(observer => {
let pluginResult;
if (opts.destruct) {
pluginResult = callCordovaPlugin(pluginObj, methodName, args, opts, (...args: any[]) => observer.next(args), (...args: any[]) => observer.error(args));
pluginResult = callCordovaPlugin(
pluginObj,
methodName,
args,
opts,
(...args: any[]) => observer.next(args),
(...args: any[]) => observer.error(args)
);
} else {
pluginResult = callCordovaPlugin(pluginObj, methodName, args, opts, observer.next.bind(observer), observer.error.bind(observer));
pluginResult = callCordovaPlugin(
pluginObj,
methodName,
args,
opts,
observer.next.bind(observer),
observer.error.bind(observer)
);
}
if (pluginResult && pluginResult.error) {
@ -186,26 +266,45 @@ function wrapObservable(pluginObj: any, methodName: string, args: any[], opts: a
try {
if (opts.clearFunction) {
if (opts.clearWithArgs) {
return callCordovaPlugin(pluginObj, opts.clearFunction, args, opts, observer.next.bind(observer), observer.error.bind(observer));
return callCordovaPlugin(
pluginObj,
opts.clearFunction,
args,
opts,
observer.next.bind(observer),
observer.error.bind(observer)
);
}
return callCordovaPlugin(pluginObj, opts.clearFunction, []);
}
} catch (e) {
console.warn('Unable to clear the previous observable watch for', pluginObj.constructor.getPluginName(), methodName);
console.warn(
'Unable to clear the previous observable watch for',
pluginObj.constructor.getPluginName(),
methodName
);
console.warn(e);
}
};
});
}
function callInstance(pluginObj: any, methodName: string, args: any[], opts: any = {}, resolve?: Function, reject?: Function) {
function callInstance(
pluginObj: any,
methodName: string,
args: any[],
opts: any = {},
resolve?: Function,
reject?: Function
) {
args = setIndex(args, opts, resolve, reject);
if (instanceAvailability(pluginObj, methodName)) {
return pluginObj._objectInstance[methodName].apply(pluginObj._objectInstance, args);
return pluginObj._objectInstance[methodName].apply(
pluginObj._objectInstance,
args
);
}
}
/**
@ -215,7 +314,10 @@ function callInstance(pluginObj: any, methodName: string, args: any[], opts: any
* @param element The element to attach the event listener to
* @returns {Observable}
*/
export function wrapEventObservable(event: string, element: any = window): Observable<any> {
export function wrapEventObservable(
event: string,
element: any = window
): Observable<any> {
return Observable.fromEvent(element, event);
}
@ -227,28 +329,38 @@ export function wrapEventObservable(event: string, element: any = window): Obser
* does just this.
* @private
*/
export function overrideFunction(pluginObj: any, methodName: string, args: any[], opts: any = {}): Observable<any> {
export function overrideFunction(
pluginObj: any,
methodName: string,
args: any[],
opts: any = {}
): Observable<any> {
return new Observable(observer => {
const availabilityCheck = checkAvailability(pluginObj, null, pluginObj.constructor.getPluginName());
const availabilityCheck = checkAvailability(
pluginObj,
null,
pluginObj.constructor.getPluginName()
);
if (availabilityCheck === true) {
const pluginInstance = getPlugin(pluginObj.constructor.getPluginRef());
pluginInstance[methodName] = observer.next.bind(observer);
return () => pluginInstance[methodName] = () => { };
return () => (pluginInstance[methodName] = () => {});
} else {
observer.error(availabilityCheck);
observer.complete();
}
});
}
/**
* @private
*/
export const wrap = function(pluginObj: any, methodName: string, opts: CordovaOptions = {}) {
export const wrap = function(
pluginObj: any,
methodName: string,
opts: CordovaOptions = {}
) {
return (...args: any[]) => {
if (opts.sync) {
// Sync doesn't wrap the plugin with a promise or observable, it returns the result as-is
@ -268,22 +380,36 @@ export const wrap = function(pluginObj: any, methodName: string, opts: CordovaOp
/**
* @private
*/
export function wrapInstance(pluginObj: any, methodName: string, opts: any = {}) {
export function wrapInstance(
pluginObj: any,
methodName: string,
opts: any = {}
) {
return (...args: any[]) => {
if (opts.sync) {
return callInstance(pluginObj, methodName, args, opts);
} else if (opts.observable) {
return new Observable(observer => {
let pluginResult;
if (opts.destruct) {
pluginResult = callInstance(pluginObj, methodName, args, opts, (...args: any[]) => observer.next(args), (...args: any[]) => observer.error(args));
pluginResult = callInstance(
pluginObj,
methodName,
args,
opts,
(...args: any[]) => observer.next(args),
(...args: any[]) => observer.error(args)
);
} else {
pluginResult = callInstance(pluginObj, methodName, args, opts, observer.next.bind(observer), observer.error.bind(observer));
pluginResult = callInstance(
pluginObj,
methodName,
args,
opts,
observer.next.bind(observer),
observer.error.bind(observer)
);
}
if (pluginResult && pluginResult.error) {
@ -294,23 +420,47 @@ export function wrapInstance(pluginObj: any, methodName: string, opts: any = {})
return () => {
try {
if (opts.clearWithArgs) {
return callInstance(pluginObj, opts.clearFunction, args, opts, observer.next.bind(observer), observer.error.bind(observer));
return callInstance(
pluginObj,
opts.clearFunction,
args,
opts,
observer.next.bind(observer),
observer.error.bind(observer)
);
}
return callInstance(pluginObj, opts.clearFunction, []);
} catch (e) {
console.warn('Unable to clear the previous observable watch for', pluginObj.constructor.getPluginName(), methodName);
console.warn(
'Unable to clear the previous observable watch for',
pluginObj.constructor.getPluginName(),
methodName
);
console.warn(e);
}
};
});
} else if (opts.otherPromise) {
return getPromise((resolve: Function, reject: Function) => {
let result;
if (opts.destruct) {
result = callInstance(pluginObj, methodName, args, opts, (...args: any[]) => resolve(args), (...args: any[]) => reject(args));
result = callInstance(
pluginObj,
methodName,
args,
opts,
(...args: any[]) => resolve(args),
(...args: any[]) => reject(args)
);
} else {
result = callInstance(pluginObj, methodName, args, opts, resolve, reject);
result = callInstance(
pluginObj,
methodName,
args,
opts,
resolve,
reject
);
}
if (result && !!result.then) {
result.then(resolve, reject);
@ -318,14 +468,27 @@ export function wrapInstance(pluginObj: any, methodName: string, opts: any = {})
reject();
}
});
} else {
let pluginResult: any, rej: Function;
const p = getPromise((resolve: Function, reject: Function) => {
if (opts.destruct) {
pluginResult = callInstance(pluginObj, methodName, args, opts, (...args: any[]) => resolve(args), (...args: any[]) => reject(args));
pluginResult = callInstance(
pluginObj,
methodName,
args,
opts,
(...args: any[]) => resolve(args),
(...args: any[]) => reject(args)
);
} else {
pluginResult = callInstance(pluginObj, methodName, args, opts, resolve, reject);
pluginResult = callInstance(
pluginObj,
methodName,
args,
opts,
resolve,
reject
);
}
rej = reject;
});
@ -333,12 +496,10 @@ export function wrapInstance(pluginObj: any, methodName: string, opts: any = {})
// a warning that Cordova is undefined or the plugin is uninstalled, so there is no reason
// to error
if (pluginResult && pluginResult.error) {
p.catch(() => { });
p.catch(() => {});
typeof rej === 'function' && rej(pluginResult.error);
}
return p;
}
};
}

View File

@ -7,25 +7,27 @@ export const get = (element: Element | Window, path: string): any => {
const paths: string[] = path.split('.');
let obj: any = element;
for (let i: number = 0; i < paths.length; i++) {
if (!obj) { return null; }
if (!obj) {
return null;
}
obj = obj[paths[i]];
}
return obj;
};
/**
* @private
*/
export const getPromise = (callback: Function): Promise<any> => {
const tryNativePromise = () => {
if (window.Promise) {
return new Promise((resolve, reject) => {
callback(resolve, reject);
});
} else {
console.error('No Promise support or polyfill found. To enable Ionic Native support, please add the es6-promise polyfill before this script, or run with a library like Angular or on a recent browser.');
console.error(
'No Promise support or polyfill found. To enable Ionic Native support, please add the es6-promise polyfill before this script, or run with a library like Angular or on a recent browser.'
);
}
};
@ -44,14 +46,36 @@ export const getPlugin = (pluginRef: string): any => {
/**
* @private
*/
export const pluginWarn = (pluginName: string, plugin?: string, method?: string): void => {
export const pluginWarn = (
pluginName: string,
plugin?: string,
method?: string
): void => {
if (method) {
console.warn('Native: tried calling ' + pluginName + '.' + method + ', but the ' + pluginName + ' plugin is not installed.');
console.warn(
'Native: tried calling ' +
pluginName +
'.' +
method +
', but the ' +
pluginName +
' plugin is not installed.'
);
} else {
console.warn('Native: tried accessing the ' + pluginName + ' plugin but it\'s not installed.');
console.warn(
'Native: tried accessing the ' +
pluginName +
" plugin but it's not installed."
);
}
if (plugin) {
console.warn('Install the ' + pluginName + ' plugin: \'ionic cordova plugin add ' + plugin + '\'');
console.warn(
'Install the ' +
pluginName +
" plugin: 'ionic cordova plugin add " +
plugin +
"'"
);
}
};
@ -62,8 +86,18 @@ export const pluginWarn = (pluginName: string, plugin?: string, method?: string)
*/
export const cordovaWarn = (pluginName: string, method?: string): void => {
if (method) {
console.warn('Native: tried calling ' + pluginName + '.' + method + ', but Cordova is not available. Make sure to include cordova.js or run in a device/simulator');
console.warn(
'Native: tried calling ' +
pluginName +
'.' +
method +
', but Cordova is not available. Make sure to include cordova.js or run in a device/simulator'
);
} else {
console.warn('Native: tried accessing the ' + pluginName + ' plugin but Cordova is not available. Make sure to include cordova.js or run in a device/simulator');
console.warn(
'Native: tried accessing the ' +
pluginName +
' plugin but Cordova is not available. Make sure to include cordova.js or run in a device/simulator'
);
}
};