diff --git a/.gitignore b/.gitignore index 1e12dbb4f..ac58c285c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ .DS_Store node_modules/ .idea +.tmp +aot/ dist/ scripts/ionic-native-bower diff --git a/DEVELOPER.md b/DEVELOPER.md index e52ff352b..9cf7bf27b 100644 --- a/DEVELOPER.md +++ b/DEVELOPER.md @@ -12,6 +12,9 @@ First, let's start by creating a new plugin wrapper from template. // Make sure to capitalize the first letter, or use CamelCase if necessary. gulp plugin:create -n PluginName + +// add -m flag to get a minimal template to start with +gulp plugin:create -m -n PluginName ``` @@ -22,17 +25,18 @@ Let's take a look at the existing plugin wrapper for Geolocation to see what goe plugin: 'cordova-plugin-geolocation', pluginRef: 'navigator.geolocation' }) +@Injectable() export class Geolocation { @Cordova() - static getCurrentPosition(options?: GeolocationOptions): Promise { return } + getCurrentPosition(options?: GeolocationOptions): Promise { return; } @Cordova({ callbackOrder: 'reverse', observable: true, clearFunction: 'clearWatch' }) - static watchPosition(options?: GeolocationOptions): Observable { return } + watchPosition(options?: GeolocationOptions): Observable { return; } } ``` @@ -41,6 +45,7 @@ export class Geolocation { First and foremost, we want to create a class representing our plugin, in this case Geolocation. ``` +@Injectable() class Geolocation { } @@ -57,6 +62,7 @@ For example, the `@Plugin` decorator adds information about the plugin to our Ge plugin: 'cordova-plugin-geolocation', pluginRef: 'navigator.geolocation' }) +@Injectable() export class Geolocation { } @@ -74,7 +80,7 @@ Let's take a look at `getCurrentPosition` first. ``` @Cordova() - static getCurrentPosition(options?: GeolocationOptions): Promise { return } + getCurrentPosition(options?: GeolocationOptions): Promise { return } ``` It's just a stub. The `return` is only there to keep the TypeScript type-checker from complaining since we indicate that `getCurrentPosition` returns a `Promise`. @@ -91,7 +97,7 @@ Next, let's look at the `watchPosition` method. observable: true, clearFunction: 'clearWatch' }) - static watchPosition(options?: GeolocationOptions): Observable { return } + watchPosition(options?: GeolocationOptions): Observable { return } ``` The `@Cordova` decorator has a few more options now. @@ -102,58 +108,6 @@ The `@Cordova` decorator has a few more options now. `clearFunction` is used in conjunction with the `observable` option and indicates the function to be called when the Observable is disposed. -### Updating index.ts - -For new plugins, you will need to update `/src/index.ts` to properly export your plugin and make it available for use. - -1. Import the plugin class into `index.ts`: - -`import {PluginClassName} from ./plugins/filenameForPlugin` - -No need to put the `.ts` extension on the filename. - -2. Add the plugin class name to the list in the `export` object: - -``` -export { - ActionSheet, - AdMob, - AndroidFingerprintAuth, - YourPluginClassName, - ... -} -``` - -3. Add the plugin class name to the `window['IonicNative']` object: - -``` -window['IonicNative'] = { - ActionSheet: ActionSheet, - AdMob: AdMob, - AndroidFingerprintAuth: AndroidFingerprintAuth, - YourPluginClassName: YourPluginClassName, - ... -``` - -4. If your plugin exports any other objects outside of the plugin class, add an export statement for the file: - -`export * from './plugins/filenameForPlugin';` - -No need to put the `.ts` extension on the filename. - -For example, `googlemaps.ts` exports a const outside of the plugin's main `GoogleMap` class: - -``` -export const GoogleMapsAnimation = { - BOUNCE: 'BOUNCE', - DROP: 'DROP' -}; -``` - -To properly export `GoogleMapsAnimation`, `index.ts` is updated with: - -`export * from './plugins/googlemaps';` - ### Testing your changes You need to run `npm run build` in the `ionic-native` project, this will create a `dist` directory. Then, you must go to your ionic application folder and replace your current `node_modules/ionic-native/dist/` with the newly generated one. @@ -164,7 +118,7 @@ You need to run `npm run lint` to analyze the code and ensure it's consistency w ### 'Wrapping' Up -That's it! The only thing left to do is rigorously document the plugin and it's usage. Take a look at some of the other plugins for good documentation styles. +That's it! The only thing left to do is rigorously document the plugin and it's usage. Take a look at some of the other plugins for good documentation styles. ## Commit Message Format diff --git a/circle.yml b/circle.yml index 331652216..da298f405 100644 --- a/circle.yml +++ b/circle.yml @@ -1,6 +1,6 @@ machine: node: - version: 4.1.0 + version: 7.10.0 ruby: version: 2.1.2 @@ -17,7 +17,6 @@ dependencies: test: override: - - npm test - npm run build deployment: diff --git a/gulpfile.js b/gulpfile.js index 93d75ac45..3cd607b11 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -1,6 +1,5 @@ var gulp = require('gulp'); var minimist = require('minimist'); -var uglify = require('gulp-uglify'); var rename = require("gulp-rename"); var tslint = require('gulp-tslint'); var decamelize = require('decamelize'); @@ -17,16 +16,6 @@ var flags = minimist(process.argv.slice(2), flagConfig); /* Docs tasks */ require('./scripts/docs/gulp-tasks')(gulp, flags); - -gulp.task("minify:dist", function(){ - gulp.src('./dist/ionic.native.js') - .pipe(uglify()) - .pipe(rename({ - suffix: '.min' - })) - .pipe(gulp.dest('./dist')); -}); - gulp.task('lint', function() { gulp.src('src/**/*.ts') .pipe(tslint({ @@ -38,12 +27,21 @@ gulp.task('lint', function() { gulp.task('plugin:create', function(){ if(flags.n && flags.n !== ''){ - var src = flags.m?'./scripts/templates/wrap-min.tmpl':'./scripts/templates/wrap.tmpl'; + + const src = flags.m?'./scripts/templates/wrap-min.tmpl':'./scripts/templates/wrap.tmpl', + pluginName = flags.n, + pluginPackageName = decamelize(pluginName, '-'), + pluginNameSpaced = pluginName.replace(/(?!^)([A-Z])/g, ' $1'); + return gulp.src(src) - .pipe(replace('PluginName', flags.n)) - .pipe(rename(decamelize(flags.n, '-') + '.ts')) - .pipe(gulp.dest('./src/plugins/')); + .pipe(replace('PluginName', pluginName)) + .pipe(replace('Plugin Name', pluginNameSpaced)) + .pipe(rename('index.ts')) + .pipe(gulp.dest('./src/@ionic-native/plugins/' + pluginPackageName)); + } else { + console.log("Usage is: gulp plugin:create -n PluginName"); + } }); diff --git a/karma.conf.ts b/karma.conf.ts deleted file mode 100644 index 5b3106254..000000000 --- a/karma.conf.ts +++ /dev/null @@ -1,61 +0,0 @@ -const WATCH = process.argv.indexOf('--watch') > -1; - -module.exports = config => { - config.set({ - - // base path that will be used to resolve all patterns (eg. files, exclude) - basePath: './', - - // frameworks to use - // available frameworks: https://npmjs.org/browse/keyword/karma-adapter - frameworks: ['jasmine', 'browserify'], - - // list of files / patterns to load in the browser - files: [ - 'test/**/*.spec.ts' - ], - - // preprocess matching files before serving them to the browser - // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor - preprocessors: { - 'test/**/*.spec.ts': ['browserify'] - }, - - browserify: { - debug: true, - plugin: [ 'tsify' ], - extensions: ['.js', '.ts'] - }, - - phantomjsLauncher: { - // Have phantomjs exit if a ResourceError is encountered (useful if karma exits without killing phantom) - exitOnResourceError: true - }, - - // test results reporter to use - // possible values: 'dots', 'progress' - // available reporters: https://npmjs.org/browse/keyword/karma-reporter - reporters: ['dots'], - - // web server port - port: 9876, - - // enable / disable colors in the output (reporters and logs) - colors: true, - - // level of logging - // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG - logLevel: config.LOG_INFO, - - // enable / disable watching file and executing tests whenever any file changes - autoWatch: WATCH, - - // start these browsers - // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher - browsers: ['PhantomJS'], - - // Continuous Integration mode - // if true, Karma captures browsers, runs the tests and exits - singleRun: !WATCH - }); -}; diff --git a/package.json b/package.json index b9f37cc11..7da7622f4 100644 --- a/package.json +++ b/package.json @@ -1,73 +1,50 @@ { "name": "ionic-native", - "version": "2.9.0", + "version": "3.1.0-rc.6", "description": "Native plugin wrappers for Cordova and Ionic with TypeScript, ES6+, Promise and Observable support", - "main": "dist/es5/index.js", - "module": "dist/esm/index.js", - "typings": "dist/es5/index.d.ts", - "files": [ - "dist" - ], - "dependencies": { - "rxjs": "5.0.1" - }, + "license": "MIT", "devDependencies": { - "browserify": "^13.3.0", + "@angular/compiler": "2.4.8", + "@angular/compiler-cli": "2.4.8", + "@angular/core": "2.4.8", "canonical-path": "0.0.2", - "conventional-changelog-cli": "^1.2.0", - "conventional-github-releaser": "^1.1.3", - "cpr": "^2.0.2", - "cz-conventional-changelog": "^1.2.0", - "decamelize": "^1.2.0", - "dgeni": "^0.4.2", - "dgeni-packages": "^0.10.18", - "es6-shim": "~0.35.2", - "glob": "^7.1.1", - "gulp": "^3.9.1", - "gulp-rename": "^1.2.2", - "gulp-replace": "^0.5.4", - "gulp-tslint": "^6.1.2", - "gulp-uglify": "^2.0.0", - "jasmine-core": "~2.5.2", - "karma": "~1.3.0", - "karma-browserify": "~5.1.0", - "karma-jasmine": "~1.1.0", - "karma-phantomjs-launcher": "~1.0.2", + "child-process-promise": "2.2.0", + "conventional-changelog-cli": "1.2.0", + "cpr": "2.0.2", + "cz-conventional-changelog": "1.2.0", + "decamelize": "1.2.0", + "dgeni": "0.4.7", + "dgeni-packages": "0.16.10", + "fs-extra": "2.0.0", + "fs-extra-promise": "0.4.1", + "gulp": "3.9.1", + "gulp-rename": "1.2.2", + "gulp-replace": "0.5.4", + "gulp-tslint": "6.1.2", "lodash": "4.17.4", - "minimist": "^1.1.3", - "mkdirp": "^0.5.1", + "minimist": "1.1.3", "node-html-encoder": "0.0.2", "q": "1.4.1", - "semver": "^5.3.0", - "tsify": "~3.0.0", - "tslint": "^3.15.1", + "queue": "4.2.1", + "rimraf": "2.5.4", + "rxjs": "5.0.1", + "semver": "5.3.0", + "tslint": "3.15.1", "tslint-ionic-rules": "0.0.7", "typescript": "2.0.09", - "watchify": "~3.7.0" + "zone.js": "0.7.2" }, "scripts": { - "test": "karma start", - "test:watch": "npm test -- --watch", "start": "npm run test:watch", "lint": "gulp lint", - "build": "npm run lint && npm run build:js && npm run build:esm && npm run build:bundle && npm run build:minify", - "build:js": "tsc -p tsconfig-es5.json", - "build:esm": "tsc -p tsconfig-esm.json", - "build:bundle": "browserify dist/es5/index.js > dist/ionic.native.js", - "build:minify": "gulp minify:dist", - "shipit": "npm run build && npm publish && bash ./scripts/bower.sh", - "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0", - "plugin:create": "gulp plugin:create" + "build": "npm run clean && npm run lint && npm run build:core && npm run build:modules", + "build:core": "ngc -p scripts/build/tsconfig-core.json", + "build:modules": "node scripts/build/build.js", + "clean": "rimraf dist", + "shipit": "npm run build && gulp readmes && npm run npmpub", + "npmpub": "node scripts/build/publish.js", + "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0" }, - "repository": { - "type": "git", - "url": "https://github.com/driftyco/ionic-native.git" - }, - "license": "MIT", - "bugs": { - "url": "https://github.com/driftyco/ionic-native/issues" - }, - "homepage": "https://github.com/driftyco/ionic-native", "config": { "commitizen": { "path": "./node_modules/cz-conventional-changelog" diff --git a/scripts/bower.json b/scripts/bower.json deleted file mode 100644 index 678bac591..000000000 --- a/scripts/bower.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "ionic-native", - "description": "Native plugin wrappers for Cordova and Ionic with TypeScript, ES6+, Promise and Observable support", - "main": [ - "ionic.native.js" - ], - "authors": [ - "Max Lynch " - ], - "license": "MIT", - "keywords": [ - "ionic", - "native", - "html5", - "hybrid", - "mobile" - ], - "homepage": "https://github.com/driftyco/ionic-native-bower", - "ignore": [ - "**/.*", - "node_modules", - "bower_components", - "test", - "tests" - ] -} diff --git a/scripts/bower.sh b/scripts/bower.sh deleted file mode 100644 index cf70d3731..000000000 --- a/scripts/bower.sh +++ /dev/null @@ -1,28 +0,0 @@ -#!/bin/bash -set -e - - -# readJsonProp(jsonFile, property) -# - restriction: property needs to be on an own line! -function readJsonProp { - echo $(sed -En 's/.*"'$2'"[ ]*:[ ]*"(.*)".*/\1/p' $1) -} - -VERSION=$(readJsonProp "package.json" "version") - -echo "BOWERING IONIC-NATIVE VERSION $VERSION. FOR GREAT JUSTICE..." - -DIR="scripts/ionic-native-bower" -rm -rf $DIR -mkdir $DIR -cp dist/ionic.native.js dist/ionic.native.min.js $DIR -cd $DIR -git init -git remote add origin git@github.com:driftyco/ionic-native-bower.git -cp ../bower.json . -git add . -git commit -m "Bower release" -git tag -f -m v$VERSION v$VERSION -git push -f --tags origin master - -echo "BOWERING COMPLETED SOMEWHAT SUCCESSFULLY" diff --git a/scripts/build/build.js b/scripts/build/build.js new file mode 100644 index 000000000..c544e1b7d --- /dev/null +++ b/scripts/build/build.js @@ -0,0 +1,135 @@ +// Node module dependencies +const fs = require('fs-extra-promise').useFs(require('fs-extra')), + queue = require('queue'), + path = require('path'), + exec = require('child_process').exec; + +// Constants for the build process. Paths and JSON files templates +const ROOT = path.resolve(path.join(__dirname, '../../')), // root ionic-native directory + PLUGINS_PATH = path.resolve(ROOT, 'src/@ionic-native/plugins'), // path to plugins source files + CORE_PACKAGE_JSON = require(path.resolve(__dirname, 'core-package.json')), // core package.json + PLUGIN_PACKAGE_JSON = require(path.resolve(__dirname, 'plugin-package.json')), // plugin package.json template + PLUGIN_TS_CONFIG = require(path.resolve(__dirname, 'tsconfig-plugin.json')), // plugin tsconfig template + BUILD_TMP = path.resolve(ROOT, '.tmp'), // tmp directory path + BUILD_DIST_ROOT = path.resolve(ROOT, 'dist/packages-dist/@ionic-native'), // dist directory root path + BUILD_PLUGINS_DIST = path.resolve(BUILD_DIST_ROOT, 'plugins'), // plugins dist directory path + BUILD_CORE_DIST = path.resolve(BUILD_DIST_ROOT, 'core'); // core dist directory path + + +// dependency versions +const ANGULAR_VERSION = '2.4.8', + RXJS_VERSION = '5.0.1', + IONIC_NATIVE_VERSION = require(path.resolve(ROOT, 'package.json')).version; + +// package dependencies +const CORE_PEER_DEPS = { + 'rxjs': RXJS_VERSION +}; + +const PLUGIN_PEER_DEPS = { + '@ionic-native/core': IONIC_NATIVE_VERSION, + '@angular/core': ANGULAR_VERSION, + 'rxjs': RXJS_VERSION +}; + +// set peer dependencies for all plugins +PLUGIN_PACKAGE_JSON.peerDependencies = PLUGIN_PEER_DEPS; + + +// Delete dist directory and any temporary files +console.log('Removing old TMP directory'); +fs.removeSync(BUILD_TMP); +fs.removeSync(BUILD_PLUGINS_DIST); + + +// Create tmp/dist directories +console.log('Making new TMP directory'); +fs.mkdirpSync(BUILD_TMP); + + +// Prepare and copy the core module's package.json +console.log('Preparing core module package.json'); +CORE_PACKAGE_JSON.version = IONIC_NATIVE_VERSION; +CORE_PACKAGE_JSON.peerDependencies = CORE_PEER_DEPS; +fs.writeJsonSync(path.resolve(BUILD_CORE_DIST, 'package.json'), CORE_PACKAGE_JSON); + + +// Fetch a list of the plugins +const PLUGINS = fs.readdirSync(PLUGINS_PATH); + + +// Create a queue to process tasks +const QUEUE = queue({ + concurrency: require('os').cpus().length +}); + + +// Function to process a single plugin +const addPluginToQueue = pluginName => { + + QUEUE.push((callback) => { + + console.log(`Building plugin: ${pluginName}`); + + const PLUGIN_BUILD_DIR = path.resolve(BUILD_TMP, 'plugins', pluginName), + PLUGIN_SRC_PATH = path.resolve(PLUGINS_PATH, pluginName, 'index.ts'); + + let tsConfigPath; + + fs.mkdirpAsync(PLUGIN_BUILD_DIR) // create tmp build dir + .then(() => fs.mkdirpAsync(path.resolve(BUILD_PLUGINS_DIST, pluginName))) // create dist dir + .then(() => { + + // Write tsconfig.json + const tsConfig = JSON.parse(JSON.stringify(PLUGIN_TS_CONFIG)); + tsConfig.files = [PLUGIN_SRC_PATH]; + // tsConfig.compilerOptions.paths['@ionic-native/core'] = [BUILD_CORE_DIST]; + + tsConfigPath = path.resolve(PLUGIN_BUILD_DIR, 'tsconfig.json'); + + return fs.writeJsonAsync(tsConfigPath, tsConfig); + }) + .then(() => { + // clone package.json + const packageJson = JSON.parse(JSON.stringify(PLUGIN_PACKAGE_JSON)); + + packageJson.name = `@ionic-native/${pluginName}`; + packageJson.version = IONIC_NATIVE_VERSION; + + return fs.writeJsonAsync(path.resolve(BUILD_PLUGINS_DIST, pluginName, 'package.json'), packageJson); + }) + .then(() => { + + // compile the plugin + exec(`${ROOT}/node_modules/.bin/ngc -p ${tsConfigPath}`, (err, stdout, stderr) => { + + if (err) { + // oops! something went wrong. + callback(`\n\nBuilding ${pluginName} failed.`); + console.log(err); + return; + } + + // we're done with this plugin! + callback(); + + }); + + }) + .catch(callback); + + }); // QUEUE.push end + +}; + +PLUGINS.forEach(addPluginToQueue); + +QUEUE.start((err) => { + + if (err) { + console.log('Error building plugins. ', err); + } else { + console.log('Done processing plugins!'); + } + +}); diff --git a/scripts/build/core-package.json b/scripts/build/core-package.json new file mode 100644 index 000000000..c1fe2083b --- /dev/null +++ b/scripts/build/core-package.json @@ -0,0 +1,14 @@ +{ + "name": "@ionic-native/core", + "version": "{{VERSION}}", + "description": "Ionic Native - Native plugins for ionic apps", + "module": "index.js", + "typings": "index.d.ts", + "author": "ionic", + "license": "MIT", + "peerDependencies": {}, + "repository": { + "type": "git", + "url": "https://github.com/driftyco/ionic-native.git" + } +} diff --git a/scripts/build/plugin-package.json b/scripts/build/plugin-package.json new file mode 100644 index 000000000..191556ae4 --- /dev/null +++ b/scripts/build/plugin-package.json @@ -0,0 +1,14 @@ +{ + "name": "@ionic-native/{{PLUGIN}}", + "version": "{{VERSION}}", + "description": "Ionic Native - Native plugins for ionic apps", + "module": "index.js", + "typings": "index.d.ts", + "author": "ionic", + "license": "MIT", + "peerDependencies": {}, + "repository": { + "type": "git", + "url": "https://github.com/driftyco/ionic-native.git" + } +} diff --git a/scripts/build/publish.js b/scripts/build/publish.js new file mode 100644 index 000000000..cfb00c318 --- /dev/null +++ b/scripts/build/publish.js @@ -0,0 +1,56 @@ +// Node module dependencies +const fs = require('fs-extra-promise').useFs(require('fs-extra')), + queue = require('queue'), + path = require('path'), + exec = require('child-process-promise').exec; + + +const ROOT = path.resolve(path.join(__dirname, '../../')), + DIST = path.resolve(ROOT, 'dist', 'packages-dist', '@ionic-native'), + PLUGINS_ROOT = path.resolve(DIST, 'plugins'), + CORE = path.resolve(DIST, 'core'); + +const FLAGS = '--access public'; // add any flags here if you want... (example: --tag alpha) + +console.log('Publishing @ionic-native/core'); +exec(`npm publish ${CORE} ${FLAGS}`) + .then(() => { + + const PLUGINS = fs.readdirSync(PLUGINS_ROOT); + + const QUEUE = queue({ + concurrency: 10 + }); + + PLUGINS.forEach(pluginName => { + + QUEUE.push(done => { + + console.log(`Publishing plugin ${pluginName}`); + const pluginPath = path.resolve(PLUGINS_ROOT, pluginName); + + exec(`npm publish ${pluginPath} ${FLAGS}`) + .then(() => done()) + .catch(done); + + }); + + }); + + QUEUE.start((err) => { + + if (err) { + console.log('Error publishing ionic-native. ', err); + } else { + console.log('Done publishing ionic-native!'); + } + + }); + + }) + .catch(e => { + + console.log('Publish failed'); + console.log(e); + + }); diff --git a/scripts/build/tsconfig-core.json b/scripts/build/tsconfig-core.json new file mode 100644 index 000000000..7d9890ed1 --- /dev/null +++ b/scripts/build/tsconfig-core.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "baseUrl": ".", + "declaration": true, + "stripInternal": true, + "experimentalDecorators": true, + "emitDecoratorMetadata": true, + "module": "es2015", + "moduleResolution": "node", + "outDir": "../../dist/packages-dist/", + "rootDir": "../../src/", + "target": "es5", + "skipLibCheck": true, + "lib": ["es2015", "dom"] + }, + "files": [ + "../../src/@ionic-native/core/index.ts" + ], + "angularCompilerOptions": { + "genDir": "../../.tmp/core-aot" + } +} diff --git a/scripts/build/tsconfig-plugin.json b/scripts/build/tsconfig-plugin.json new file mode 100644 index 000000000..0de7d7fa7 --- /dev/null +++ b/scripts/build/tsconfig-plugin.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "baseUrl": ".", + "declaration": true, + "stripInternal": true, + "experimentalDecorators": true, + "emitDecoratorMetadata": true, + "module": "es2015", + "moduleResolution": "node", + "outDir": "../../../dist/packages-dist/", + "paths": { + "@ionic-native/core": ["../../../dist/packages-dist/@ionic-native/core"] + }, + "rootDir": "../../../src/", + "target": "es5", + "skipLibCheck": true, + "lib": ["es2015", "dom"] + }, + "files": [ + "../../../src/@ionic-native/plugins/{{PLUGIN}}/index.ts" + ] +} diff --git a/scripts/config.json b/scripts/config.json index dd051dc14..8b4b8a512 100644 --- a/scripts/config.json +++ b/scripts/config.json @@ -1,5 +1,6 @@ { "sitePath": "../ionic-site", "v2DocsDir": "docs/v2/native", - "docsDest": "../ionic-site/content/docs/v2/native" + "docsDest": "../ionic-site/content/docs/v2/native", + "pluginDir": "dist/packages-dist/@ionic-native/plugins" } diff --git a/scripts/docs/dgeni-config.js b/scripts/docs/dgeni-config.js index d79ca7faa..5b47e9f78 100644 --- a/scripts/docs/dgeni-config.js +++ b/scripts/docs/dgeni-config.js @@ -1,9 +1,8 @@ var Package = require('dgeni').Package; var jsdocPackage = require('dgeni-packages/jsdoc'); var nunjucksPackage = require('dgeni-packages/nunjucks'); -var typescriptPackage = require('./typescript-package'); -var linksPackage = require('./links-package'); -var gitPackage = require('dgeni-packages/git'); +var typescriptPackage = require('dgeni-packages/typescript'); +var linksPackage = require('dgeni-packages/links'); var path = require('path'); var semver = require('semver'); var fs = require('fs'); @@ -14,9 +13,7 @@ var projectPackage = require('../../package.json'); // Define the dgeni package for generating the docs module.exports = function(currentVersion) { - return new Package('ionic-v2-docs', - [jsdocPackage, nunjucksPackage, typescriptPackage, - linksPackage, gitPackage]) + return new Package('ionic-v2-docs', [jsdocPackage, nunjucksPackage, typescriptPackage, linksPackage]) // .processor(require('./processors/latest-version')) .processor(require('./processors/jekyll')) @@ -72,7 +69,7 @@ module.exports = function(currentVersion) { log.level = 'error'; //'silly', 'debug', 'info', 'warn', 'error' }) -.config(function(renderDocsProcessor, computePathsProcessor, versionInfo) { +.config(function(renderDocsProcessor, computePathsProcessor) { versions = []; // new version, add it to the versions list @@ -98,7 +95,6 @@ module.exports = function(currentVersion) { }; renderDocsProcessor.extraData.version = versionData; - renderDocsProcessor.extraData.versionInfo = versionInfo; computePathsProcessor.pathTemplates = [{ docTypes: ['class', 'var', 'function', 'let'], getOutputPath: function(doc) { @@ -117,10 +113,9 @@ module.exports = function(currentVersion) { readFilesProcessor.$enabled = false; readFilesProcessor.basePath = path.resolve(__dirname, '../..'); - readTypeScriptModules.basePath = path.resolve(path.resolve(__dirname, - '../..')); + readTypeScriptModules.basePath = path.resolve(__dirname, '../..'); readTypeScriptModules.sourceFiles = [ - 'src/index.ts' + './src/@ionic-native/plugins/**/*.ts' ]; }) @@ -148,7 +143,7 @@ module.exports = function(currentVersion) { // Configure file writing .config(function(writeFilesProcessor) { - writeFilesProcessor.outputFolder = config.sitePath; + writeFilesProcessor.outputFolder = '../ionic-site/'; }) // Configure rendering @@ -169,7 +164,8 @@ module.exports = function(currentVersion) { templateEngine.filters.push( require('./filters/capital'), require('./filters/code'), - require('./filters/dump') + require('./filters/dump'), + require('./filters/dashify') ); templateFinder.templateFolders.unshift(path.resolve(__dirname, 'templates')); diff --git a/scripts/docs/dgeni-readmes-config.js b/scripts/docs/dgeni-readmes-config.js new file mode 100644 index 000000000..2a58f85ea --- /dev/null +++ b/scripts/docs/dgeni-readmes-config.js @@ -0,0 +1,177 @@ +var Package = require('dgeni').Package; +var jsdocPackage = require('dgeni-packages/jsdoc'); +var nunjucksPackage = require('dgeni-packages/nunjucks'); +var typescriptPackage = require('dgeni-packages/typescript'); +var linksPackage = require('dgeni-packages/links'); +var path = require('path'); +var semver = require('semver'); +var fs = require('fs'); +var _ = require('lodash'); +var config = require('../config.json'); +var projectPackage = require('../../package.json'); + +// jscs:disable validateIndentation + +// Define the dgeni package for generating the docs +module.exports = function(currentVersion) { + + return new Package('ionic-v2-docs', [jsdocPackage, nunjucksPackage, typescriptPackage, linksPackage]) + +// .processor(require('./processors/latest-version')) +.processor(require('./processors/readmes')) +.processor(require('./processors/remove-private-members')) +.processor(require('./processors/hide-private-api')) +// .processor(require('./processors/collect-inputs-outputs')) + +// for debugging docs +// .processor(function test(){ +// return { +// +// $runBefore: ['rendering-docs'], +// $process: function(docs){ +// docs.forEach(function(doc){ +// if (doc.name == "Camera"){ +// +// // console.log(doc.tags); +// // doc.tags.forEach(function(tag){ +// // if(tag.tagName == 'classes'){ +// // +// // } +// // }); +// +// // doc.moduleDoc.exports.forEach(function(d,i){ +// // if(d.name === 'CameraOptions') { +// // console.log('Name: ' + d.name); +// // console.log('Type: ' + d.docType); +// // console.log('First member: ', d.members[0]); +// // } +// // }); +// +// +// // var exports = doc.exportSymbol.parent.exports; +// // for(var p in exports) { +// // if(p == 'CameraOptions') +// // { +// // var x = exports[p]; +// // console.log(x.members.quality); +// // } +// // } +// // doc.members.forEach(function(method){ +// // if (method.name === "getPicture") { +// // console.log(method); +// // } +// // }) +// } +// }) +// } +// } +// }) +.config(function(log) { + log.level = 'error'; //'silly', 'debug', 'info', 'warn', 'error' +}) + +.config(function(renderDocsProcessor, computePathsProcessor) { + + versions = []; + // new version, add it to the versions list + if (currentVersion != 'nightly' && !_.includes(versions, currentVersion)) { + versions.unshift(currentVersion); + } + //First semver valid version is latest + var latestVersion = _.find(versions, semver.valid); + versions = versions.map(function(version) { + // We don't separate by versions so always put the docs in the root + var folder = ''; + return { + href: '/' + config.v2DocsDir.replace('content/', ''), + folder: folder, + name: version + }; + }); + + var versionData = { + list: versions, + current: _.find(versions, {name: currentVersion}), + latest: _.find(versions, {name: latestVersion}) || _.first(versions) + }; + + renderDocsProcessor.extraData.version = versionData; + computePathsProcessor.pathTemplates = [{ + docTypes: ['class'], + getOutputPath: function(doc) { + return doc.originalModule.replace(config.pluginDir + '/', '') + .replace('/index', '') + '/README.md'; + } + }]; +}) + +//configure file reading +.config(function(readFilesProcessor, readTypeScriptModules) { + + // Don't run unwanted processors since we are not using the normal file reading processor + readFilesProcessor.$enabled = false; + readFilesProcessor.basePath = path.resolve(__dirname, '../..'); + + readTypeScriptModules.basePath = path.resolve(path.resolve(__dirname, '../..')); + readTypeScriptModules.sourceFiles = ['./src/@ionic-native/plugins/**/*.ts']; +}) + +.config(function(parseTagsProcessor) { + parseTagsProcessor.tagDefinitions = parseTagsProcessor.tagDefinitions + .concat(require('./tag-defs/tag-defs')); +}) + +// .config(function(parseTagsProcessor) { +// // We actually don't want to parse param docs in this package as we are +// // getting the data out using TS +// parseTagsProcessor.tagDefinitions.forEach(function(tagDef) { +// console.log(tagDef); +// if (tagDef.name === 'param') { +// tagDef.docProperty = 'paramData'; +// tagDef.transforms = []; +// } +// }); +// }) + +// Configure links +.config(function(getLinkInfo) { + getLinkInfo.useFirstAmbiguousLink = false; +}) + +// Configure file writing +.config(function(writeFilesProcessor) { + writeFilesProcessor.outputFolder = './dist/packages-dist/'; +}) + +// Configure rendering +.config(function(templateFinder, templateEngine) { + + // Nunjucks and Angular conflict in their template bindings so change the Nunjucks + // Also conflict with Jekyll + templateEngine.config.tags = { + variableStart: '<$', + variableEnd: '$>', + blockStart: '<@', + blockEnd: '@>', + commentStart: '<#', + commentEnd: '#>' + }; + + // add custom filters to nunjucks + templateEngine.filters.push( + require('./filters/capital'), + require('./filters/code'), + require('./filters/dump') + ); + + templateFinder.templateFolders.unshift(path.resolve(__dirname, 'templates')); + + // Specify how to match docs to templates. + templateFinder.templatePatterns = [ + '${ doc.template }', + '${ doc.docType }.template.md', + 'readme.template.md' + ]; +}); + +}; diff --git a/scripts/docs/filters/dashify.js b/scripts/docs/filters/dashify.js new file mode 100644 index 000000000..85cc7663c --- /dev/null +++ b/scripts/docs/filters/dashify.js @@ -0,0 +1,7 @@ +module.exports = { + name: 'dashify', + process: function(str) { + str || (str = ''); + return str.replace(/\s/g, '-'); + } +}; diff --git a/scripts/docs/gulp-tasks.js b/scripts/docs/gulp-tasks.js index 19d246581..58a3a8a69 100644 --- a/scripts/docs/gulp-tasks.js +++ b/scripts/docs/gulp-tasks.js @@ -7,7 +7,23 @@ module.exports = function(gulp) { try { var ionicPackage = require('./dgeni-config')(projectPackage.version); var dgeni = new Dgeni([ionicPackage]); - return dgeni.generate(); + return dgeni.generate().then(function(docs) { + console.log(docs.length + ' docs generated'); + }); + } catch (err) { + console.log(err.stack); + } + }); + + gulp.task('readmes', [], function() { + var Dgeni = require('dgeni'); + var semver = require('semver'); + try { + var ionicPackage = require('./dgeni-readmes-config')(projectPackage.version); + var dgeni = new Dgeni([ionicPackage]); + return dgeni.generate().then(function(docs) { + console.log(docs.length + ' README files generated'); + }); } catch (err) { console.log(err.stack); } diff --git a/scripts/docs/links-package/index.js b/scripts/docs/links-package/index.js deleted file mode 100644 index a3ffc7199..000000000 --- a/scripts/docs/links-package/index.js +++ /dev/null @@ -1,12 +0,0 @@ -var Package = require('dgeni').Package; - -module.exports = new Package('links', []) - -.factory(require('./inline-tag-defs/link')) -.factory(require('dgeni-packages/ngdoc/services/getAliases')) -.factory(require('dgeni-packages/ngdoc/services/getDocFromAlias')) -.factory(require('./services/getLinkInfo')) - -.config(function(inlineTagProcessor, linkInlineTagDef) { - inlineTagProcessor.inlineTagDefinitions.push(linkInlineTagDef); -}); diff --git a/scripts/docs/links-package/inline-tag-defs/link.js b/scripts/docs/links-package/inline-tag-defs/link.js deleted file mode 100644 index 89272c63c..000000000 --- a/scripts/docs/links-package/inline-tag-defs/link.js +++ /dev/null @@ -1,33 +0,0 @@ -var INLINE_LINK = /(\S+)(?:\s+([\s\S]+))?/; - -/** - * @dgService linkInlineTagDef - * @description - * Process inline link tags (of the form {@link some/uri Some Title}), replacing them with HTML anchors - * @kind function - * @param {Object} url The url to match - * @param {Function} docs error message - * @return {String} The html link information - * - * @property {boolean} relativeLinks Whether we expect the links to be relative to the originating doc - */ -module.exports = function linkInlineTagDef(getLinkInfo, createDocMessage, log) { - return { - name: 'link', - description: 'Process inline link tags (of the form {@link some/uri Some Title}), replacing them with HTML anchors', - handler: function(doc, tagName, tagDescription) { - - // Parse out the uri and title - return tagDescription.replace(INLINE_LINK, function(match, uri, title) { - - var linkInfo = getLinkInfo(uri, title, doc); - - if ( !linkInfo.valid ) { - log.warn(createDocMessage(linkInfo.error, doc)); - } - - return "" + linkInfo.title + ""; - }); - } - }; -}; \ No newline at end of file diff --git a/scripts/docs/links-package/services/getLinkInfo.js b/scripts/docs/links-package/services/getLinkInfo.js deleted file mode 100644 index 787ff0433..000000000 --- a/scripts/docs/links-package/services/getLinkInfo.js +++ /dev/null @@ -1,72 +0,0 @@ -var _ = require('lodash'); -var path = require('canonical-path'); - -/** - * @dgService getLinkInfo - * @description - * Get link information to a document that matches the given url - * @kind function - * @param {String} url The url to match - * @param {String} title An optional title to return in the link information - * @return {Object} The link information - * - * @property {boolean} relativeLinks Whether we expect the links to be relative to the originating doc - */ -module.exports = function getLinkInfo(getDocFromAlias, encodeCodeBlock, log) { - - return function getLinkInfoImpl(url, title, currentDoc) { - var linkInfo = { - url: url, - type: 'url', - valid: true, - title: title || url - }; - - if ( !url ) { - throw new Error('Invalid url'); - } - - var docs = getDocFromAlias(url, currentDoc); - - if ( !getLinkInfoImpl.useFirstAmbiguousLink && docs.length > 1 ) { - - linkInfo.valid = false; - linkInfo.errorType = 'ambiguous'; - linkInfo.error = 'Ambiguous link: "' + url + '".\n' + - docs.reduce(function(msg, doc) { return msg + '\n "' + doc.id + '" ('+ doc.docType + ') : (' + doc.path + ' / ' + doc.fileInfo.relativePath + ')'; }, 'Matching docs: '); - - } else if ( docs.length >= 1 ) { - - linkInfo.url = docs[0].path; - linkInfo.title = title || encodeCodeBlock(docs[0].name, true); - linkInfo.type = 'doc'; - - if ( getLinkInfoImpl.relativeLinks && currentDoc && currentDoc.path ) { - var currentFolder = path.dirname(currentDoc.path); - var docFolder = path.dirname(linkInfo.url); - var relativeFolder = path.relative(path.join('/', currentFolder), path.join('/', docFolder)); - linkInfo.url = path.join(relativeFolder, path.basename(linkInfo.url)); - log.debug(currentDoc.path, docs[0].path, linkInfo.url); - } - - } else if ( url.indexOf('#') > 0 ) { - var pathAndHash = url.split('#'); - linkInfo = getLinkInfoImpl(pathAndHash[0], title, currentDoc); - linkInfo.url = linkInfo.url + '#' + pathAndHash[1]; - return linkInfo; - - } else if ( url.indexOf('/') === -1 && url.indexOf('#') !== 0 ) { - - linkInfo.valid = false; - linkInfo.errorType = 'missing'; - linkInfo.error = 'Invalid link (does not match any doc): "' + url + '"'; - - } else { - - linkInfo.title = title || (( url.indexOf('#') === 0 ) ? url.substring(1) : path.basename(url, '.html')); - - } - - return linkInfo; - }; -}; \ No newline at end of file diff --git a/scripts/docs/processors/hide-private-api.js b/scripts/docs/processors/hide-private-api.js index 15e2b6eb2..bd475a46a 100644 --- a/scripts/docs/processors/hide-private-api.js +++ b/scripts/docs/processors/hide-private-api.js @@ -5,14 +5,14 @@ module.exports = function removePrivateApi() { $runBefore: ['rendering-docs'], $process: function(docs) { var publicDocs = []; - docs.forEach(function(doc){ - if(!doc.private){ + docs.forEach(function(doc){ + if (!doc.private && (!doc.tags || !doc.tags.tagsByName.get('hidden'))){ publicDocs.push(doc); return doc } - }) - docs = publicDocs; - return docs; + }); + docs = publicDocs; + return docs; } } }; diff --git a/scripts/docs/processors/jekyll.js b/scripts/docs/processors/jekyll.js index 0122b7afd..993224985 100644 --- a/scripts/docs/processors/jekyll.js +++ b/scripts/docs/processors/jekyll.js @@ -17,7 +17,7 @@ module.exports = function jekyll(renderDocsProcessor) { return (textA < textB) ? -1 : (textA > textB) ? 1 : 0; }); docs.forEach(function(doc, i) { - doc.outputPath = doc.outputPath.toLowerCase().replace(' ', '-'); + doc.outputPath = doc.outputPath.toLowerCase().replace(/\s/g, '-'); docs[i].URL = doc.outputPath.replace('docs/v2//', 'docs/v2/') .replace('/index.md', '') .replace('content/', ''); diff --git a/scripts/docs/processors/readmes.js b/scripts/docs/processors/readmes.js new file mode 100644 index 000000000..e5c1f458c --- /dev/null +++ b/scripts/docs/processors/readmes.js @@ -0,0 +1,25 @@ +module.exports = function jekyll(renderDocsProcessor) { + return { + name: 'readmes', + description: 'Create jekyll includes', + $runAfter: ['paths-computed'], + $runBefore: ['rendering-docs'], + $process: function(docs) { + var currentVersion = renderDocsProcessor.extraData.version.current.name; + + // pretty up and sort the docs object for menu generation + docs = docs.filter(function(doc) { + return (!!doc.name && !!doc.outputPath) || doc.docType === 'index-page'; + }); + + docs.forEach(function(doc, i) { + doc.npmId = doc.outputPath.replace('/README.md', '') + .replace('src/@ionic-native/plugins/',''); + doc.outputPath = doc.outputPath.replace('src/', ''); + }); + + // returning docs will replace docs object in the next process + return docs; + } + }; +}; diff --git a/scripts/docs/processors/remove-private-members.js b/scripts/docs/processors/remove-private-members.js index 59946a9d8..36fdd3303 100644 --- a/scripts/docs/processors/remove-private-members.js +++ b/scripts/docs/processors/remove-private-members.js @@ -6,16 +6,19 @@ module.exports = function removePrivateMembers() { $runBefore: ['rendering-docs'], $process: function(docs) { docs.forEach(function(doc) { + if (doc.members) { doc.members = doc.members.filter(function(member) { - return !member.tags.tagsByName.get('private'); + return !member.tags.tagsByName.get('hidden'); }); } + if (doc.statics) { doc.statics = doc.statics.filter(function(staticMethod) { - return !staticMethod.tags.tagsByName.get('private'); + return !staticMethod.tags.tagsByName.get('hidden'); }); } + }); return docs; diff --git a/scripts/docs/tag-defs/tag-defs.js b/scripts/docs/tag-defs/tag-defs.js index 5f01bfa2b..98a043ac8 100644 --- a/scripts/docs/tag-defs/tag-defs.js +++ b/scripts/docs/tag-defs/tag-defs.js @@ -6,6 +6,7 @@ module.exports = [ return typeof value !== 'undefined'; }}, {'name': 'usage'}, + {'name': 'hidden'}, // hide from docs {'name': 'classes'}, // related classes {'name': 'interfaces'} // related interfaces ]; diff --git a/scripts/docs/templates/common.template.html b/scripts/docs/templates/common.template.html index 77bf359a7..79efbd3c3 100644 --- a/scripts/docs/templates/common.template.html +++ b/scripts/docs/templates/common.template.html @@ -53,7 +53,7 @@ docType: "<$ doc.docType $>" <@- endmacro -@> <@ macro githubViewLink(doc) -@> -<$ doc.fileInfo.relativePath $> (line <$ doc.location.start.line+1 $>) +<$ doc.fileInfo.relativePath $> (line <$ doc.location.start.line+1 $>) <@- endmacro -@> <@ macro paramTable(params, isDirective) -@> @@ -224,7 +224,10 @@ docType: "<$ doc.docType $>"

<@ endif @> -
$ <@ if prop.install @><$ prop.install $><@ else @>ionic plugin add <$ prop.plugin $><@ endif -@>
+

+  $ <@ if prop.install @><$ prop.install $><@ else @>ionic plugin add <$ prop.plugin $><@ endif -@>
+  $ npm install --save @ionic-native/<$ prop.pluginRef $>
+

Repo: <$ prop.repo $> diff --git a/scripts/docs/templates/native_menu.template.html b/scripts/docs/templates/native_menu.template.html index abdcd033c..abe7a91c3 100644 --- a/scripts/docs/templates/native_menu.template.html +++ b/scripts/docs/templates/native_menu.template.html @@ -1,9 +1,9 @@ <@ for doc in docs @><@ if doc.URL and doc.private != true and doc.beta != true @> -

  • +
  • <$ doc.name $>
  • <@ endif @><@ endfor @> <@ for doc in docs @><@ if doc.URL and doc.private != true and doc.beta == true @> -
  • +
  • <$ doc.name $> β
  • <@ endif @><@ endfor @> diff --git a/scripts/docs/templates/readme.template.md b/scripts/docs/templates/readme.template.md new file mode 100644 index 000000000..44041c233 --- /dev/null +++ b/scripts/docs/templates/readme.template.md @@ -0,0 +1,38 @@ + + Improve this doc + + +# <$ doc.name $> + +<@- if doc.beta == true @> +

    + This plugin is still in beta stage and may not work as expected. Please + submit any issues to the plugin repo. +

    +<@ endif -@> + + +<@ for prop in doc.decorators[0].argumentInfo @> + +``` +$ <@ if prop.install @><$ prop.install $><@ else @>ionic plugin add <$ prop.plugin $><@ endif @> +$ npm install --save @ionic-native/<$ doc.npmId $> +``` + +## [Usage Documentation](https://ionicframework.com/docs/v2/native/<$ doc.fileInfo.relativePath|replace('/home/ubuntu/ionic-native/', '')|replace('//','/')|replace('index.ts','')|replace('src/@ionic-native/plugins/','') $>) + +Plugin Repo: [<$ prop.repo $>](<$ prop.repo $>) + +<$ doc.description $> + +<@- if prop.platforms @> + +## Supported platforms +<@ for platform in prop.platforms -@> +- <$ platform $> +<@ endfor @> + +<@ endif -@> + +<@ endfor @> diff --git a/scripts/docs/typescript-definition-package/index.js b/scripts/docs/typescript-definition-package/index.js deleted file mode 100644 index 532cfe5d3..000000000 --- a/scripts/docs/typescript-definition-package/index.js +++ /dev/null @@ -1,100 +0,0 @@ -var Package = require('dgeni').Package; -var jsdocPackage = require('dgeni-packages/jsdoc'); -var nunjucksPackage = require('dgeni-packages/nunjucks'); -var typescriptPackage = require('../typescript-package'); -var gitPackage = require('dgeni-packages/git'); -var path = require('canonical-path'); - -// Define the dgeni package for generating the docs -module.exports = new Package('angular-v2-docs', [jsdocPackage, nunjucksPackage, typescriptPackage, gitPackage]) - -// Register the processors -.processor(require('./processors/createTypeDefinitionFile')) - -.config(function(readFilesProcessor, inlineTagProcessor) { - readFilesProcessor.basePath = path.resolve(__dirname, '../..'); - // Don't run unwanted processors - readFilesProcessor.$enabled = false; - inlineTagProcessor.$enabled = false; -}) - - -// Configure the log service -.config(function(log) { - log.level = 'info'; -}) - - -.config(function(renderDocsProcessor, versionInfo) { - renderDocsProcessor.extraData.versionInfo = versionInfo; -}) - -.config(function(readFilesProcessor, inlineTagProcessor, readTypeScriptModules, createTypeDefinitionFile) { - - // Don't run unwanted processors - readFilesProcessor.$enabled = false; // We are not using the normal file reading processor - inlineTagProcessor.$enabled = false; // We are not actually processing the inline link tags - - // Configure file reading - readFilesProcessor.basePath = path.resolve(__dirname, '../..'); - readTypeScriptModules.sourceFiles = [ - 'angular2/angular2.ts', - 'angular2/router.ts' - ]; - readTypeScriptModules.basePath = path.resolve(path.resolve(__dirname, '../../modules')); - - createTypeDefinitionFile.typeDefinitions = [ - { - id: 'angular2/angular2', - modules: { - 'angular2/angular2': 'angular2/angular2', - } - }, - { - id: 'angular2/router', - modules: { - 'angular2/router': 'angular2/router' - } - } - ]; -}) - - -.config(function(parseTagsProcessor, getInjectables) { - // We actually don't want to parse param docs in this package as we are getting the data out using TS - parseTagsProcessor.tagDefinitions.forEach(function(tagDef) { - if (tagDef.name === 'param') { - tagDef.docProperty = 'paramData'; - tagDef.transforms = []; - } - }); - -}) - - -// Configure file writing -.config(function(writeFilesProcessor) { - writeFilesProcessor.outputFolder = 'dist/docs'; -}) - - -// Configure rendering -.config(function(templateFinder, templateEngine) { - - // Nunjucks and Angular conflict in their template bindings so change Nunjucks - templateEngine.config.tags = { - variableStart: '{$', - variableEnd: '$}' - }; - - templateFinder.templateFolders - .unshift(path.resolve(__dirname, 'templates')); - - templateFinder.templatePatterns = [ - '${ doc.template }', - '${ doc.id }.${ doc.docType }.template.html', - '${ doc.id }.template.html', - '${ doc.docType }.template.html', - 'common.template.html' - ]; -}); \ No newline at end of file diff --git a/scripts/docs/typescript-definition-package/mocks/mockPackage.js b/scripts/docs/typescript-definition-package/mocks/mockPackage.js deleted file mode 100644 index 692309100..000000000 --- a/scripts/docs/typescript-definition-package/mocks/mockPackage.js +++ /dev/null @@ -1,11 +0,0 @@ -var Package = require('dgeni').Package; - -module.exports = function mockPackage() { - - return new Package('mockPackage', [require('../')]) - - // provide a mock log service - .factory('log', function() { return require('dgeni/lib/mocks/log')(false); }) -// .factory('templateEngine', function() { return {}; }); - -}; diff --git a/scripts/docs/typescript-definition-package/processors/createTypeDefinitionFile.js b/scripts/docs/typescript-definition-package/processors/createTypeDefinitionFile.js deleted file mode 100644 index f3bc002ca..000000000 --- a/scripts/docs/typescript-definition-package/processors/createTypeDefinitionFile.js +++ /dev/null @@ -1,86 +0,0 @@ -var _ = require('lodash'); -var path = require('canonical-path'); - -module.exports = function createTypeDefinitionFile(log) { - - return { - $runAfter: ['processing-docs'], - $runBefore: ['docs-processed'], - $validate: { - dtsPath: { presence: true }, - dtsExtension: { presence: true }, - typeDefinitions: { presence: true } - }, - dtsPath: 'typings', - dtsExtension: '.d.ts', - typeDefinitions: [], - $process: function(docs) { - var dtsPath = this.dtsPath; - var dtsExtension = this.dtsExtension; - - // For each type definition that we wish to create we define a dgeni "doc" for it - var typeDefDocs = _.map(this.typeDefinitions, function(def) { - - var id = def.id + dtsExtension; - var docPath = path.join(dtsPath, id); - - return { - docType: 'type-definition', - id: id, - aliases: [id], - path: docPath, - outputPath: docPath, - // A type definition may include a number of top level modules - // And those modules could be aliased (such as 'angular2/angular2.api' -> 'angular2/angular2') - moduleDocs: _.transform(def.modules, function(moduleDocs, id, alias) { - moduleDocs[id] = { id: alias, doc: null }; - }) - }; - }); - - // Now add all the module docs to their corresponding type definition doc - _.forEach(docs, function(doc) { - _.forEach(typeDefDocs, function(typeDefDoc) { - if(typeDefDoc.moduleDocs[doc.id]) { - // Add a copy, because we are going to modify it - typeDefDoc.moduleDocs[doc.id].doc = doc; - } - }); - }); - - return _.filter(typeDefDocs, function(doc) { - _.forEach(doc.moduleDocs, function(modDoc, alias) { - if (!doc || !modDoc.doc) { - log.error('createTypeDefinitionFile processor: no such module "' + alias + '" (Did you forget to add it to the modules to load?)'); - doc = null; - return; - } - _.forEach(modDoc.doc.exports, function(exportDoc) { - - // Search for classes with a constructor marked as `@private` - if (exportDoc.docType === 'class' && exportDoc.constructorDoc && exportDoc.constructorDoc.private) { - - // Convert this class to an interface with no constructor - exportDoc.docType = 'interface'; - exportDoc.constructorDoc = null; - - if (exportDoc.heritage) { - // convert the heritage since interfaces use `extends` not `implements` - exportDoc.heritage = exportDoc.heritage.replace('implements', 'extends'); - } - - // Add the `declare var SomeClass extends InjectableReference` construct - modDoc.doc.exports.push({ - docType: 'var', - name: exportDoc.name, - id: exportDoc.id, - heritage: ': InjectableReference' - }); - } - }); - }); - return !!doc; - }); - } - }; -}; diff --git a/scripts/docs/typescript-definition-package/processors/createTypeDefinitionFile.spec.js b/scripts/docs/typescript-definition-package/processors/createTypeDefinitionFile.spec.js deleted file mode 100644 index 1bf15092d..000000000 --- a/scripts/docs/typescript-definition-package/processors/createTypeDefinitionFile.spec.js +++ /dev/null @@ -1,48 +0,0 @@ -var mockPackage = require('../mocks/mockPackage'); -var Dgeni = require('dgeni'); -var path = require('canonical-path'); -var _ = require('lodash'); - -describe('createTypeDefinitionFile processor', function() { - var dgeni, injector, processor; - - beforeEach(function() { - dgeni = new Dgeni([mockPackage()]); - injector = dgeni.configureInjector(); - processor = injector.get('createTypeDefinitionFile'); - - // Initialize the processor - processor.typeDefinitions = [{ - id: 'angular2/angular2', - modules: { 'angular2/angular2': 'angular2/angular2' } - }]; - }); - - - - describe('classes with private constructors', function() { - - it('should convert heritage from `implements` into `extends`', function() { - - // Create some mock docs for testing - var docs = [ - { - id: 'angular2/angular2', - exports: [ - { docType: 'class', heritage: 'implements Xyz', constructorDoc: { private: true } } - ] - } - ]; - - docs = processor.$process(docs); - - expect(docs.length).toEqual(1); - expect(docs[0].docType).toEqual('type-definition'); - - var moduleDoc = docs[0].moduleDocs['angular2/angular2'].doc; - expect(moduleDoc.exports.length).toEqual(2); - expect(moduleDoc.exports[0].heritage).toEqual('extends Xyz'); - }); - }); - -}); \ No newline at end of file diff --git a/scripts/docs/typescript-definition-package/templates/angular2/angular2.d.ts.template.html b/scripts/docs/typescript-definition-package/templates/angular2/angular2.d.ts.template.html deleted file mode 100644 index ce9778bfd..000000000 --- a/scripts/docs/typescript-definition-package/templates/angular2/angular2.d.ts.template.html +++ /dev/null @@ -1,17 +0,0 @@ -{% extends '../type-definition.template.html' %} -{% block staticDeclarations %} - -interface List extends Array {} -interface Map {} -interface StringMap extends Map {} - -declare module ng { - // See https://github.com/Microsoft/TypeScript/issues/1168 - class BaseException /* extends Error */ { - message: string; - stack: string; - toString(): string; - } - interface InjectableReference {} -} -{% endblock %} diff --git a/scripts/docs/typescript-definition-package/templates/type-definition.template.html b/scripts/docs/typescript-definition-package/templates/type-definition.template.html deleted file mode 100644 index 4ebceffaa..000000000 --- a/scripts/docs/typescript-definition-package/templates/type-definition.template.html +++ /dev/null @@ -1,72 +0,0 @@ - -{%- macro commentBlock(doc, level) -%} -{%- if doc.content | trim %} - -{% if level > 1 %}{$ '/**' | indent(level-1, true) | replace(r/\n$/, "") $}{% else %}/**{% endif %} -{$ doc.content | trim | replace(r/^/gm, "* ") | indent(level, true) | replace(r/\n$/, "") $} -{$ '*/' | indent(level, true) | replace(r/\n$/, "") $}{% endif -%} -{%- endmacro -%} - - -{%- macro memberInfo(member) -%} -{$ commentBlock(member, 5) $} - {$ member.name $}{% if member.optional %}?{% endif -%} -{% if member.typeParameters %}<{% for typeParam in member.typeParameters %}{$ typeParam $}{% if not loop.last %}, {% endif %}{% endfor %}>{% endif -%} -{%- if member.parameters -%}({% for param in member.parameters %}{$ param $}{% if not loop.last %}, {% endif %}{% endfor %}){%- endif -%} -{%- if member.returnType == 'Directive' %}: DirectiveAnnotation{%- elif member.returnType -%}: {$ member.returnType $}{%- else -%}: void -{%- endif -%}; -{%- endmacro -%} - - -// Type definitions for Angular v{$ versionInfo.currentVersion.full | replace(r/\+/, "_") $} -// Project: http://angular.io/ -// Definitions by: angular team -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -// *********************************************************** -// This file is generated by the Angular build process. -// Please do not create manual edits or send pull requests -// modifying this file. -// *********************************************************** -{% block staticDeclarations %}{% endblock %} -{% for alias, module in doc.moduleDocs %} -{$ commentBlock(module.doc, 1) $} -declare module ng { - - {%- for export in module.doc.exports -%} - {%- if export.content -%} - {$ commentBlock(export, 3) $} - {%- endif %} - {$ export.docType $} {$ export.name $}{$ export.typeParams $}{%- if export.heritage == ' extends Directive' %} extends DirectiveAnnotation{% else %}{$ export.heritage $}{% endif %} - {%- if export.docType == 'class' or export.docType == 'interface' %} { - {%- if export.newMember %} - {$ memberInfo(export.newMember) $} - {% endif %} - {%- if export.callMember %} - {$ memberInfo(export.callMember) $} - {% endif -%} - {%- for member in export.members %} - {$ memberInfo(member) $} - {%- endfor %} - } - - {%- elif export.docType == 'enum' %} { - {%- for member in export.members %} - {$ member $}{% if not loop.last %}, - {%- endif -%} - {%- endfor %} - } - - {%- else -%} - {% if export.parameters %}({% for param in export.parameters %}{$ param $}{% if not loop.last %}, {% endif %}{% endfor %}){%- endif %} - {%- if export.returnType %} : {$ export.returnType $} {% endif -%} - ; - {%- endif %} - {% endfor %} -} - -{% endfor %} - -declare module "angular2/angular2" { - export = ng; -} diff --git a/scripts/docs/typescript-package/index.js b/scripts/docs/typescript-package/index.js deleted file mode 100755 index 876c08085..000000000 --- a/scripts/docs/typescript-package/index.js +++ /dev/null @@ -1,74 +0,0 @@ -var basePackage = require('dgeni-packages/base'); -var Package = require('dgeni').Package; -var path = require('canonical-path'); - -// Define the dgeni package for generating the docs -module.exports = new Package('typescript-parsing', [basePackage]) - -// Register the services and file readers -.factory(require('./services/modules')) -.factory(require('./services/tsParser')) -.factory(require('./services/tsParser/createCompilerHost')) -.factory(require('./services/tsParser/getFileInfo')) -.factory(require('./services/tsParser/getExportDocType')) -.factory(require('./services/tsParser/getContent')) -.factory(require('./services/tsParser/getDirectiveInfo')) - -.factory(require('./services/convertPrivateClassesToInterfaces')) - -.factory('EXPORT_DOC_TYPES', function() { - return [ - 'class', - 'interface', - 'function', - 'var', - 'const', - 'let', - 'enum', - 'type-alias' - ]; -}) - - -// Register the processors -.processor(require('./processors/readTypeScriptModules')) - - -// Configure the log service -.config(function(log) { - log.level = 'warn'; -}) - - -// Configure ids and paths -.config(function(computeIdsProcessor, computePathsProcessor, EXPORT_DOC_TYPES) { - - computeIdsProcessor.idTemplates.push({ - docTypes: ['member'], - idTemplate: '${classDoc.id}.${name}', - getAliases: function(doc) { - return doc.classDoc.aliases.map(function(alias) { return alias + '.' + doc.name; }); - } - }); - - computePathsProcessor.pathTemplates.push({ - docTypes: ['member'], - pathTemplate: '${classDoc.path}#${name}', - getOutputPath: function() {} // These docs are not written to their own file, instead they are part of their class doc - }); - - var MODULES_DOCS_PATH = 'partials/modules'; - - computePathsProcessor.pathTemplates.push({ - docTypes: ['module'], - pathTemplate: '/${id}', - outputPathTemplate: MODULES_DOCS_PATH + '/${id}/index.html' - }); - - computePathsProcessor.pathTemplates.push({ - docTypes: EXPORT_DOC_TYPES, - pathTemplate: '${moduleDoc.path}/${name}', - outputPathTemplate: MODULES_DOCS_PATH + '/${path}/index.html' - }); - -}); diff --git a/scripts/docs/typescript-package/mocks/mockPackage.js b/scripts/docs/typescript-package/mocks/mockPackage.js deleted file mode 100755 index 834d53c95..000000000 --- a/scripts/docs/typescript-package/mocks/mockPackage.js +++ /dev/null @@ -1,11 +0,0 @@ -var Package = require('dgeni').Package; - -module.exports = function mockPackage() { - - return new Package('mockPackage', [require('../')]) - - // provide a mock log service - .factory('log', function() { return require('dgeni/lib/mocks/log')(false); }) - .factory('templateEngine', function() { return {}; }); - -}; diff --git a/scripts/docs/typescript-package/mocks/readTypeScriptModules/ignoreExportsMatching.ts b/scripts/docs/typescript-package/mocks/readTypeScriptModules/ignoreExportsMatching.ts deleted file mode 100755 index 476d4cc44..000000000 --- a/scripts/docs/typescript-package/mocks/readTypeScriptModules/ignoreExportsMatching.ts +++ /dev/null @@ -1,4 +0,0 @@ -export var __esModule = true; -export class OKToExport {} -export function _thisIsPrivate() {} -export var thisIsOK = '!'; \ No newline at end of file diff --git a/scripts/docs/typescript-package/mocks/readTypeScriptModules/interfaces.ts b/scripts/docs/typescript-package/mocks/readTypeScriptModules/interfaces.ts deleted file mode 100755 index a2d4be4fe..000000000 --- a/scripts/docs/typescript-package/mocks/readTypeScriptModules/interfaces.ts +++ /dev/null @@ -1,5 +0,0 @@ -export interface MyInterface { - optionalProperty? : string - >(param: T) : U - new (param: number) : MyInterface -} \ No newline at end of file diff --git a/scripts/docs/typescript-package/mocks/readTypeScriptModules/orderingOfMembers.ts b/scripts/docs/typescript-package/mocks/readTypeScriptModules/orderingOfMembers.ts deleted file mode 100755 index 2020ec7fa..000000000 --- a/scripts/docs/typescript-package/mocks/readTypeScriptModules/orderingOfMembers.ts +++ /dev/null @@ -1,6 +0,0 @@ -export class Test { - firstItem; - constructor() { this.doStuff(); } - otherMethod() {} - doStuff() {} -} \ No newline at end of file diff --git a/scripts/docs/typescript-package/mocks/readTypeScriptModules/privateModule.ts b/scripts/docs/typescript-package/mocks/readTypeScriptModules/privateModule.ts deleted file mode 100755 index d4c6ef610..000000000 --- a/scripts/docs/typescript-package/mocks/readTypeScriptModules/privateModule.ts +++ /dev/null @@ -1 +0,0 @@ -export var x = 10; \ No newline at end of file diff --git a/scripts/docs/typescript-package/mocks/readTypeScriptModules/publicModule.ts b/scripts/docs/typescript-package/mocks/readTypeScriptModules/publicModule.ts deleted file mode 100755 index 0fbae4ad2..000000000 --- a/scripts/docs/typescript-package/mocks/readTypeScriptModules/publicModule.ts +++ /dev/null @@ -1,3 +0,0 @@ -export { x as y} from './privateModule'; - -export abstract class AbstractClass {} \ No newline at end of file diff --git a/scripts/docs/typescript-package/mocks/tsParser/importedSrc.ts b/scripts/docs/typescript-package/mocks/tsParser/importedSrc.ts deleted file mode 100755 index 74a115e5f..000000000 --- a/scripts/docs/typescript-package/mocks/tsParser/importedSrc.ts +++ /dev/null @@ -1 +0,0 @@ -export var x = 100; \ No newline at end of file diff --git a/scripts/docs/typescript-package/mocks/tsParser/testSrc.ts b/scripts/docs/typescript-package/mocks/tsParser/testSrc.ts deleted file mode 100755 index 7b6d3f18d..000000000 --- a/scripts/docs/typescript-package/mocks/tsParser/testSrc.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** - * @module - * @description - * This is the module description - */ - -export * from 'importedSrc'; - -/** - * This is some random other comment - */ - -/** - * This is MyClass - */ -export class MyClass { - message: String; - - /** - * Create a new MyClass - * @param {String} name The name to say hello to - */ - constructor(name) { this.message = 'hello ' + name; } - - /** - * Return a greeting message - */ - greet() { return this.message; } -} - -/** - * An exported function - */ -export var myFn = (val: number) => return val * 2; \ No newline at end of file diff --git a/scripts/docs/typescript-package/processors/readTypeScriptModules.js b/scripts/docs/typescript-package/processors/readTypeScriptModules.js deleted file mode 100755 index aa80c7a15..000000000 --- a/scripts/docs/typescript-package/processors/readTypeScriptModules.js +++ /dev/null @@ -1,454 +0,0 @@ -var glob = require('glob'); -var path = require('canonical-path'); -var _ = require('lodash'); -var ts = require('typescript'); - -module.exports = function readTypeScriptModules(tsParser, modules, getFileInfo, - getDirectiveInfo, - getExportDocType, getContent, - createDocMessage, log) { - - return { - $runAfter: ['files-read'], - $runBefore: ['parsing-tags'], - - $validate: { - sourceFiles: {presence: true}, - basePath: {presence: true}, - hidePrivateMembers: {inclusion: [true, false]}, - sortClassMembers: {inclusion: [true, false]}, - ignoreExportsMatching: {} - }, - - // A collection of globs that identify those modules for which we should create docs - sourceFiles: [], - // The base path from which to load the source files - basePath: '.', - // We can ignore members of classes that are private - hidePrivateMembers: true, - // We leave class members sorted in order of declaration - sortClassMembers: false, - // We can provide a collection of strings or regexes to ignore exports whose export names match - ignoreExportsMatching: ['___esModule'], - - $process: function(docs) { - - // Convert ignoreExportsMatching to an array of regexes - var ignoreExportsMatching = convertToRegexCollection(this.ignoreExportsMatching); - - var hidePrivateMembers = this.hidePrivateMembers; - var sortClassMembers = this.sortClassMembers; - - var basePath = path.resolve(this.basePath); - var filesPaths = expandSourceFiles(this.sourceFiles, basePath); - var parseInfo = tsParser.parse(filesPaths, this.basePath); - var moduleSymbols = parseInfo.moduleSymbols; - - // Iterate through each of the modules that were parsed and generate a module doc - // as well as docs for each module's exports. - moduleSymbols.forEach(function(moduleSymbol) { - - var moduleDoc = createModuleDoc(moduleSymbol, basePath); - - // Add this module doc to the module lookup collection and the docs collection - modules[moduleDoc.id] = moduleDoc; - docs.push(moduleDoc); - - // Iterate through this module's exports and generate a doc for each - moduleSymbol.exportArray.forEach(function(exportSymbol) { - - // Ignore exports starting with an underscore - if (anyMatches(ignoreExportsMatching, exportSymbol.name)) return; - - // If the symbol is an Alias then for most things we want the original resolved symbol - var resolvedExport = exportSymbol.resolvedSymbol || exportSymbol; - - // If the resolved symbol contains no declarations then it is invalid - // (probably an abstract class) - // For the moment we are just going to ignore such exports - // TODO: find a way of generating docs for them - if (!resolvedExport.declarations) return; - - var exportDoc = createExportDoc(exportSymbol.name, resolvedExport, moduleDoc, basePath, parseInfo.typeChecker); - log.debug('>>>> EXPORT: ' + exportDoc.name + ' (' + exportDoc.docType + ') from ' + moduleDoc.id); - - // Add this export doc to its module doc - moduleDoc.exports.push(exportDoc); - docs.push(exportDoc); - - exportDoc.members = []; - exportDoc.statics = []; - - // Generate docs for each of the export's members - if (resolvedExport.flags & ts.SymbolFlags.HasMembers) { - - for(var memberName in resolvedExport.members) { - // FIXME(alexeagle): why do generic type params appear in members? - if (memberName === 'T') { - continue; - } - log.silly('>>>>>> member: ' + memberName + ' from ' + exportDoc.id + ' in ' + moduleDoc.id); - var memberSymbol = resolvedExport.members[memberName]; - var memberDoc = createMemberDoc(memberSymbol, exportDoc, basePath, parseInfo.typeChecker); - - // We special case the constructor and sort the other members alphabetically - if (memberSymbol.flags & ts.SymbolFlags.Constructor) { - exportDoc.constructorDoc = memberDoc; - docs.push(memberDoc); - } else if (!hidePrivateMembers || memberSymbol.name.charAt(0) !== '_') { - docs.push(memberDoc); - exportDoc.members.push(memberDoc); - } else if (memberSymbol.name === '__call' && memberSymbol.flags & ts.SymbolFlags.Signature) { - docs.push(memberDoc); - exportDoc.callMember = memberDoc; - } else if (memberSymbol.name === '__new' && memberSymbol.flags & ts.SymbolFlags.Signature) { - docs.push(memberDoc); - exportDoc.newMember = memberDoc; - } - } - } - - if (exportDoc.docType === 'enum') { - for(var memberName in resolvedExport.exports) { - log.silly('>>>>>> member: ' + memberName + ' from ' + exportDoc.id + ' in ' + moduleDoc.id); - var memberSymbol = resolvedExport.exports[memberName]; - var memberDoc = createMemberDoc(memberSymbol, exportDoc, basePath, parseInfo.typeChecker); - docs.push(memberDoc); - exportDoc.members.push(memberDoc); - } - } else if (resolvedExport.flags & ts.SymbolFlags.HasExports) { - for (var exported in resolvedExport.exports) { - if (exported === 'prototype') continue; - if (hidePrivateMembers && exported.charAt(0) === '_') continue; - var memberSymbol = resolvedExport.exports[exported]; - var memberDoc = createMemberDoc(memberSymbol, exportDoc, basePath, parseInfo.typeChecker); - memberDoc.isStatic = true; - docs.push(memberDoc); - exportDoc.statics.push(memberDoc); - } - } - - if (sortClassMembers) { - exportDoc.members.sort(function(a, b) { - if (a.name > b.name) return 1; - if (a.name < b.name) return -1; - return 0; - }); - exportDoc.statics.sort(function(a, b) { - if (a.name > b.name) return 1; - if (a.name < b.name) return -1; - return 0; - }); - } - }); - }); - } - }; - - - function createModuleDoc(moduleSymbol, basePath) { - var id = moduleSymbol.name.replace(/^"|"$/g, ''); - var name = id.split('/').pop(); - var moduleDoc = { - docType: 'module', - name: name, - id: id, - aliases: [id, name], - moduleTree: moduleSymbol, - content: getContent(moduleSymbol), - exports: [], - fileInfo: getFileInfo(moduleSymbol, basePath), - location: getLocation(moduleSymbol) - }; - return moduleDoc; - } - - function createExportDoc(name, exportSymbol, moduleDoc, basePath, typeChecker) { - var typeParamString = ''; - var heritageString = ''; - var typeDefinition = ''; - - exportSymbol.declarations.forEach(function(decl) { - var sourceFile = ts.getSourceFileOfNode(decl); - - if (decl.typeParameters) { - typeParamString = '<' + getText(sourceFile, decl.typeParameters) + '>'; - } - - if (decl.symbol.flags & ts.SymbolFlags.TypeAlias) { - typeDefinition = getText(sourceFile, decl.type); - } - - if (decl.heritageClauses) { - decl.heritageClauses.forEach(function(heritage) { - - if (heritage.token == ts.SyntaxKind.ExtendsKeyword) { - heritageString += " extends"; - heritage.types.forEach(function(typ, idx) { - heritageString += (idx > 0 ? ',' : '') + typ.getFullText(); - }); - } - - if (heritage.token == ts.SyntaxKind.ImplementsKeyword) { - heritageString += " implements"; - heritage.types.forEach(function(typ, idx) { - heritageString += (idx > 0 ? ', ' : '') + typ.getFullText(); - }); - } - }); - } - }); - - //Make sure duplicate aliases aren't created, so "Ambiguous link" warnings are prevented - var aliasNames = [name, moduleDoc.id + '/' + name]; - if (typeParamString) { - aliasNames.push(name + typeParamString); - aliasNames.push(moduleDoc.id + '/' + name + typeParamString); - } - - var exportDoc = { - docType: getExportDocType(exportSymbol), - exportSymbol: exportSymbol, - name: name, - id: moduleDoc.id + '/' + name, - typeParams: typeParamString, - heritage: heritageString, - decorators: getDecorators(exportSymbol), - aliases: aliasNames, - moduleDoc: moduleDoc, - content: getContent(exportSymbol), - fileInfo: getFileInfo(exportSymbol, basePath), - location: getLocation(exportSymbol), - directiveInfo: getDirectiveInfo(exportSymbol) - }; - - if (exportDoc.docType === 'var' || exportDoc.docType === 'const' || exportDoc.docType === 'let') { - exportDoc.symbolTypeName = exportSymbol.valueDeclaration.type && - exportSymbol.valueDeclaration.type.typeName && - exportSymbol.valueDeclaration.type.typeName.text; - } - - if (exportDoc.docType === 'type-alias') { - exportDoc.returnType = getReturnType(typeChecker, exportSymbol); - } - - if(exportSymbol.flags & ts.SymbolFlags.Function) { - exportDoc.parameters = getParameters(typeChecker, exportSymbol); - } - if(exportSymbol.flags & ts.SymbolFlags.Value) { - exportDoc.returnType = getReturnType(typeChecker, exportSymbol); - } - if (exportSymbol.flags & ts.SymbolFlags.TypeAlias) { - exportDoc.typeDefinition = typeDefinition; - } - - // Compute the original module name from the relative file path - exportDoc.originalModule = exportDoc.fileInfo.relativePath - .replace(new RegExp('\.' + exportDoc.fileInfo.extension + '$'), ''); - - return exportDoc; - } - - function createMemberDoc(memberSymbol, classDoc, basePath, typeChecker) { - var memberDoc = { - docType: 'member', - classDoc: classDoc, - name: memberSymbol.name, - decorators: getDecorators(memberSymbol), - content: getContent(memberSymbol), - fileInfo: getFileInfo(memberSymbol, basePath), - location: getLocation(memberSymbol) - }; - - memberDoc.typeParameters = getTypeParameters(typeChecker, memberSymbol); - - if(memberSymbol.flags & (ts.SymbolFlags.Signature) ) { - memberDoc.parameters = getParameters(typeChecker, memberSymbol); - memberDoc.returnType = getReturnType(typeChecker, memberSymbol); - switch(memberDoc.name) { - case '__call': - memberDoc.name = ''; - break; - case '__new': - memberDoc.name = 'new'; - break; - } - } - - if (memberSymbol.flags & ts.SymbolFlags.Method) { - // NOTE: we use the property name `parameters` here so we don't conflict - // with the `params` property that will be updated by dgeni reading the - // `@param` tags from the docs - memberDoc.parameters = getParameters(typeChecker, memberSymbol); - } - - if (memberSymbol.flags & ts.SymbolFlags.Constructor) { - memberDoc.parameters = getParameters(typeChecker, memberSymbol); - memberDoc.name = 'constructor'; - } - - if(memberSymbol.flags & ts.SymbolFlags.Value) { - memberDoc.returnType = getReturnType(typeChecker, memberSymbol); - } - - if(memberSymbol.flags & ts.SymbolFlags.Optional) { - memberDoc.optional = true; - } - - return memberDoc; - } - - - function getDecorators(symbol) { - - var declaration = symbol.valueDeclaration || symbol.declarations[0]; - var sourceFile = ts.getSourceFileOfNode(declaration); - - var decorators = declaration.decorators && declaration.decorators.map(function(decorator) { - decorator = decorator.expression; - return { - name: decorator.expression ? decorator.expression.text : decorator.text, - arguments: decorator.arguments && decorator.arguments.map(function(argument) { - return getText(sourceFile, argument).trim(); - }), - argumentInfo: decorator.arguments && decorator.arguments.map(function(argument) { - return parseArgument(argument); - }), - expression: decorator - }; - }); - return decorators; - } - - function parseProperties(properties) { - var result = {}; - _.forEach(properties, function(property) { - result[property.name.text] = parseArgument(property.initializer); - }); - return result; - } - - function parseArgument(argument) { - if (argument.text) return argument.text; - if (argument.properties) return parseProperties(argument.properties); - if (argument.elements) return argument.elements.map(function(element) { return element.text; }); - var sourceFile = ts.getSourceFileOfNode(argument); - var text = getText(sourceFile, argument).trim(); - return text; - } - - function getParameters(typeChecker, symbol) { - var declaration = symbol.valueDeclaration || symbol.declarations[0]; - var sourceFile = ts.getSourceFileOfNode(declaration); - if (!declaration.parameters) { - var location = getLocation(symbol); - throw new Error('missing declaration parameters for "' + symbol.name + - '" in ' + sourceFile.fileName + - ' at line ' + location.start.line); - } - return declaration.parameters.map(function(parameter) { - var paramText = ''; - if (parameter.dotDotDotToken) { - paramText += '...'; - } - paramText += getText(sourceFile, parameter.name); - if (parameter.questionToken || parameter.initializer) { - paramText += '?'; - } - if (parameter.type) { - paramText += ':' + getType(sourceFile, parameter.type); - } else { - paramText += ': any'; - if (parameter.dotDotDotToken) { - paramText += '[]'; - } - } - return paramText.trim(); - }); - } - - function getTypeParameters(typeChecker, symbol) { - var declaration = symbol.valueDeclaration || symbol.declarations[0]; - var sourceFile = ts.getSourceFileOfNode(declaration); - if (!declaration.typeParameters) return; - var typeParams = declaration.typeParameters.map(function(type) { - return getText(sourceFile, type).trim(); - }); - return typeParams; - } - - function getReturnType(typeChecker, symbol) { - var declaration = symbol.valueDeclaration || symbol.declarations[0]; - var sourceFile = ts.getSourceFileOfNode(declaration); - if (declaration.type) { - return getType(sourceFile, declaration.type).trim(); - } else if (declaration.initializer) { - // The symbol does not have a "type" but it is being initialized - // so we can deduce the type of from the initializer (mostly). - if (declaration.initializer.expression) { - return declaration.initializer.expression.text.trim(); - } else { - return getType(sourceFile, declaration.initializer).trim(); - } - } - } - - - function expandSourceFiles(sourceFiles, basePath) { - var filePaths = []; - sourceFiles.forEach(function(sourcePattern) { - filePaths = filePaths.concat(glob.sync(sourcePattern, { cwd: basePath })); - }); - return filePaths; - } - - - function getText(sourceFile, node) { - return sourceFile.text.substring(node.pos, node.end); - } - - - // Strip any local renamed imports from the front of types - function getType(sourceFile, type) { - var text = getText(sourceFile, type); - while (text.indexOf(".") >= 0) { - // Keep namespaced symbols in RxNext - if (text.match(/^\s*RxNext\./)) break; - // handle the case List -> List - text = text.replace(/([^.<]*)\.([^>]*)/, "$2"); - } - return text; - } - - function getLocation(symbol) { - var node = symbol.valueDeclaration || symbol.declarations[0]; - var sourceFile = ts.getSourceFileOfNode(node); - var location = { - start: ts.getLineAndCharacterOfPosition(sourceFile, node.pos), - end: ts.getLineAndCharacterOfPosition(sourceFile, node.end) - }; - return location; - } - -}; - -function convertToRegexCollection(items) { - if (!items) return []; - - // Must be an array - if (!_.isArray(items)) { - items = [items]; - } - - // Convert string to exact matching regexes - return items.map(function(item) { - return _.isString(item) ? new RegExp('^' + item + '$') : item; - }); -} - -function anyMatches(regexes, item) { - for(var i=0; i']); - expect(exportedInterface.newMember).toBeDefined(); - expect(exportedInterface.newMember.parameters).toEqual(['param: number']); - expect(exportedInterface.newMember.returnType).toEqual('MyInterface'); - }); - }); - - - describe('ordering of members', function() { - it('should order class members in order of appearance (by default)', function() { - processor.sourceFiles = ['orderingOfMembers.ts']; - var docs = []; - processor.$process(docs); - var classDoc = _.find(docs, { docType: 'class' }); - expect(classDoc.docType).toEqual('class'); - expect(getNames(classDoc.members)).toEqual([ - 'firstItem', - 'otherMethod', - 'doStuff', - ]); - }); - - - it('should not order class members if not sortClassMembers is false', function() { - processor.sourceFiles = ['orderingOfMembers.ts']; - processor.sortClassMembers = false; - var docs = []; - processor.$process(docs); - var classDoc = _.find(docs, { docType: 'class' }); - expect(classDoc.docType).toEqual('class'); - expect(getNames(classDoc.members)).toEqual([ - 'firstItem', - 'otherMethod', - 'doStuff' - ]); - }); - }); -}); - -function getNames(collection) { - return collection.map(function(item) { return item.name; }); -} \ No newline at end of file diff --git a/scripts/docs/typescript-package/services/convertPrivateClassesToInterfaces.js b/scripts/docs/typescript-package/services/convertPrivateClassesToInterfaces.js deleted file mode 100755 index 69afdea89..000000000 --- a/scripts/docs/typescript-package/services/convertPrivateClassesToInterfaces.js +++ /dev/null @@ -1,31 +0,0 @@ -var _ = require('lodash'); - -module.exports = function convertPrivateClassesToInterfaces() { - return function(exportDocs, addInjectableReference) { - _.forEach(exportDocs, function(exportDoc) { - - // Search for classes with a constructor marked as `@internal` - if (exportDoc.docType === 'class' && exportDoc.constructorDoc && exportDoc.constructorDoc.internal) { - - // Convert this class to an interface with no constructor - exportDoc.docType = 'interface'; - exportDoc.constructorDoc = null; - - if (exportDoc.heritage) { - // convert the heritage since interfaces use `extends` not `implements` - exportDoc.heritage = exportDoc.heritage.replace('implements', 'extends'); - } - - if (addInjectableReference) { - // Add the `declare var SomeClass extends InjectableReference` construct - exportDocs.push({ - docType: 'var', - name: exportDoc.name, - id: exportDoc.id, - returnType: 'InjectableReference' - }); - } - } - }); - }; -}; diff --git a/scripts/docs/typescript-package/services/convertPrivateClassesToInterfaces.spec.js b/scripts/docs/typescript-package/services/convertPrivateClassesToInterfaces.spec.js deleted file mode 100755 index bc4ed7411..000000000 --- a/scripts/docs/typescript-package/services/convertPrivateClassesToInterfaces.spec.js +++ /dev/null @@ -1,76 +0,0 @@ -var mockPackage = require('../mocks/mockPackage'); -var Dgeni = require('dgeni'); -var _ = require('lodash'); - -describe('readTypeScriptModules', function() { - var dgeni, injector, convertPrivateClassesToInterfaces; - - beforeEach(function() { - dgeni = new Dgeni([mockPackage()]); - injector = dgeni.configureInjector(); - convertPrivateClassesToInterfaces = injector.get('convertPrivateClassesToInterfaces'); - }); - - it('should convert private class docs to interface docs', function() { - var docs = [ - { - docType: 'class', - name: 'privateClass', - id: 'privateClass', - constructorDoc: { internal: true } - } - ]; - convertPrivateClassesToInterfaces(docs, false); - expect(docs[0].docType).toEqual('interface'); - }); - - - it('should not touch non-private class docs', function() { - var docs = [ - { - docType: 'class', - name: 'privateClass', - id: 'privateClass', - constructorDoc: { } - } - ]; - convertPrivateClassesToInterfaces(docs, false); - expect(docs[0].docType).toEqual('class'); - }); - - - it('should convert the heritage since interfaces use `extends` not `implements`', function() { - var docs = [ - { - docType: 'class', - name: 'privateClass', - id: 'privateClass', - constructorDoc: { internal: true }, - heritage: 'implements parentInterface' - } - ]; - convertPrivateClassesToInterfaces(docs, false); - expect(docs[0].heritage).toEqual('extends parentInterface'); - }); - - - it('should add new injectable reference types, if specified, to the passed in collection', function() { - var docs = [ - { - docType: 'class', - name: 'privateClass', - id: 'privateClass', - constructorDoc: { internal: true }, - heritage: 'implements parentInterface' - } - ]; - convertPrivateClassesToInterfaces(docs, true); - expect(docs[1]).toEqual({ - docType : 'var', - name : 'privateClass', - id : 'privateClass', - returnType : 'InjectableReference' - }); - }); - -}); diff --git a/scripts/docs/typescript-package/services/modules.js b/scripts/docs/typescript-package/services/modules.js deleted file mode 100755 index 760139022..000000000 --- a/scripts/docs/typescript-package/services/modules.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = function modules() { - return {}; -}; diff --git a/scripts/docs/typescript-package/services/tsParser/createCompilerHost.js b/scripts/docs/typescript-package/services/tsParser/createCompilerHost.js deleted file mode 100755 index c9d3d368b..000000000 --- a/scripts/docs/typescript-package/services/tsParser/createCompilerHost.js +++ /dev/null @@ -1,80 +0,0 @@ -var ts = require('typescript'); -var fs = require('fs'); -var path = require('canonical-path'); - -// We need to provide our own version of CompilerHost because we want to set the -// base directory and specify what extensions to consider when trying to load a source -// file -module.exports = function createCompilerHost(log) { - - return function createCompilerHost(options, baseDir, extensions) { - - return { - getSourceFile: function(fileName, languageVersion, onError) { - var text, resolvedPath, resolvedPathWithExt; - - // Strip off the extension and resolve relative to the baseDir - baseFilePath = fileName.replace(/\.[^.]+$/, ''); - resolvedPath = path.resolve(baseDir, baseFilePath); - - // Iterate through each possible extension and return the first source file that is actually found - for(var i=0; i} Returns a promise that resolves when something happens */ @Cordova() - static functionName(arg1: string, arg2: number): Promise { + functionName(arg1: string, arg2: number): Promise { return; // We add return; here to avoid any IDE / Compiler errors } diff --git a/src/@ionic-native/core/bootstrap.ts b/src/@ionic-native/core/bootstrap.ts new file mode 100644 index 000000000..a8557a182 --- /dev/null +++ b/src/@ionic-native/core/bootstrap.ts @@ -0,0 +1,23 @@ +declare var window; + +export function checkReady() { + const DEVICE_READY_TIMEOUT = 5000; + + // To help developers using cordova, we listen for the device ready event and + // log an error if it didn't fire in a reasonable amount of time. Generally, + // when this happens, developers should remove and reinstall plugins, since + // an inconsistent plugin is often the culprit. + const before = Date.now(); + + let didFireReady = false; + document.addEventListener('deviceready', () => { + 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.`); + } + }, DEVICE_READY_TIMEOUT); +} diff --git a/src/@ionic-native/core/decorators.ts b/src/@ionic-native/core/decorators.ts new file mode 100644 index 000000000..797b9382d --- /dev/null +++ b/src/@ionic-native/core/decorators.ts @@ -0,0 +1,344 @@ +import { instanceAvailability, checkAvailability, wrap, wrapInstance, overrideFunction } from './plugin'; +import { getPlugin, getPromise } from './util'; +import { Observable } from 'rxjs/Observable'; + +export interface PluginConfig { + /** + * Plugin name, this should match the class name + */ + pluginName: string; + /** + * Plugin NPM package name + */ + plugin: string; + /** + * Plugin object reference + */ + pluginRef?: string; + /** + * Github repository URL + */ + repo?: string; + /** + * Custom install command + */ + install?: string; + /** + * Available installation variables + */ + installVariables?: string[]; + /** + * Supported platforms + */ + platforms?: string[]; +} + +export interface CordovaOptions { + /** + * Set to true if the wrapped method is a sync function + */ + sync?: boolean; + /** + * Callback order. Set to reverse if the success/error callbacks are the first 2 arguments that the wrapped method takes. + */ + callbackOrder?: 'reverse'; + /** + * Callback style + */ + callbackStyle?: 'node' | 'object'; + /** + * Set a custom index for the success callback function. This doesn't work if callbackOrder or callbackStyle are set. + */ + successIndex?: number; + /** + * Set a custom index for the error callback function. This doesn't work if callbackOrder or callbackStyle are set. + */ + errorIndex?: number; + /** + * Success function property name. This must be set if callbackStyle is set to object. + */ + successName?: string; + /** + * Error function property name. This must be set if callbackStyle is set to object. + */ + errorName?: string; + /** + * Set to true to return an observable + */ + observable?: boolean; + /** + * If observable is set to true, this can be set to a different function name that will cancel the observable. + */ + clearFunction?: string; + /** + * This can be used if clearFunction is set. Set this to true to call the clearFunction with the same arguments used in the initial function. + */ + clearWithArgs?: boolean; + /** + * Creates an observable that wraps a global event. Replaces document.addEventListener + */ + eventObservable?: boolean; + /** + * Event name, this must be set if eventObservable is set to true + */ + event?: string; + /** + * Element to attach the event listener to, this is optional, defaults to `window` + */ + element?: any; + /** + * Set to true if the wrapped method returns a promise + */ + otherPromise?: boolean; + /** + * Supported platforms + */ + platforms?: string[]; +} + +export interface CordovaCheckOptions { + sync?: boolean; + observable?: boolean; +} + +export interface CordovaFiniteObservableOptions extends CordovaOptions { + /** + * Function that gets a result returned from plugin's success callback, and decides whether it is last value and observable should complete. + */ + resultFinalPredicate?: (result: any) => boolean; + /** + * Function that gets called after resultFinalPredicate, and removes service data that indicates end of stream from the result. + */ + resultTransform?: (result: any) => any; +} + +/** + * @private + */ +export function InstanceCheck(opts: CordovaCheckOptions = {}) { + return (pluginObj: Object, methodName: string, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor => { + 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(() => {}); + } + + return getPromise(() => {}); + + } + } + }; + }; +} + +/** + * Executes function only if plugin is available + * @private + */ +export function CordovaCheck(opts: CordovaCheckOptions = {}) { + return (pluginObj: Object, methodName: string, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor => { + return { + value: function(...args: any[]): any { + if (checkAvailability(pluginObj) === true) { + return descriptor.value.apply(this, args); + } else { + if (opts.sync) { + return; + } else if (opts.observable) { + return new Observable(() => {}); + } + return getPromise(() => {}); + } + } + }; + }; +} + + +/** + * @private + * + * Class decorator specifying Plugin metadata. Required for all plugins. + * + * @usage + * ```typescript + * @Plugin({ + * pluginName: 'MyPlugin', + * plugin: 'cordova-plugin-myplugin', + * pluginRef: 'window.myplugin' + * }) + * export class MyPlugin { + * + * // Plugin wrappers, properties, and functions go here ... + * + * } + * ``` + */ +export function Plugin(config: PluginConfig) { + return function(cls) { + + // Add these fields to the class + for (let k in config) { + cls[k] = config[k]; + } + + cls['installed'] = function(printWarning?: boolean) { + return !!getPlugin(config.pluginRef); + }; + + cls['getPlugin'] = function() { + return getPlugin(config.pluginRef); + }; + + cls['checkInstall'] = function() { + return checkAvailability(cls) === true; + }; + + cls['getPluginName'] = function() { + return config.pluginName; + }; + cls['getPluginRef'] = function() { + return config.pluginRef; + }; + cls['getPluginInstallName'] = function() { + return config.plugin; + }; + cls['getPluginRepo'] = function() { + return config.repo; + }; + cls['getSupportedPlatforms'] = function() { + return config.platforms; + }; + + return cls; + }; +} + +/** + * @private + * + * Wrap a stub function in a call to a Cordova plugin, checking if both Cordova + * and the required plugin are installed. + */ +export function Cordova(opts: CordovaOptions = {}) { + return (target: Object, methodName: string, descriptor: TypedPropertyDescriptor) => { + return { + value: function(...args: any[]) { + return wrap(this, methodName, opts).apply(this, args); + } + }; + }; +} + +/** + * @private + * + * Wrap an instance method + */ +export function CordovaInstance(opts: any = {}) { + return (target: Object, methodName: string) => { + return { + value: function(...args: any[]) { + return wrapInstance(this, methodName, opts).apply(this, args); + } + }; + }; +} + +/** + * @private + * + * + * Before calling the original method, ensure Cordova and the plugin are installed. + */ +export function CordovaProperty(target: any, key: string) { + Object.defineProperty(target, key, { + get: () => { + if (checkAvailability(target, key) === true) { + return getPlugin(target.constructor.getPluginRef())[key]; + } else { + return null; + } + }, + set: (value) => { + if (checkAvailability(target, key) === true) { + getPlugin(target.constructor.getPluginRef())[key] = value; + } + } + }); +} + +/** + * @private + * @param target + * @param key + * @constructor + */ +export function InstanceProperty(target: any, key: string) { + Object.defineProperty(target, key, { + get: function(){ + return this._objectInstance[key]; + }, + set: function(value){ + this._objectInstance[key] = value; + } + }); +} + +/** + * @private + * + * Wrap a stub function in a call to a Cordova plugin, checking if both Cordova + * and the required plugin are installed. + */ +export function CordovaFunctionOverride(opts: any = {}) { + return (target: Object, methodName: string, descriptor: TypedPropertyDescriptor) => { + return { + value: function(...args: any[]) { + return overrideFunction(this, methodName, opts); + } + }; + }; +} + + +/** + * @private + * + * Wraps method that returns an observable that can be completed. Provided opts.resultFinalPredicate dictates when the observable completes. + * + */ +export function CordovaFiniteObservable(opts: CordovaFiniteObservableOptions = {}) { + if (opts.observable === false) { + throw new Error('CordovaFiniteObservable decorator can only be used on methods that returns observable. Please provide correct option.'); + } + opts.observable = true; + return (target: Object, methodName: string, descriptor: TypedPropertyDescriptor) => { + return { + value: function(...args: any[]) { + let wrappedObservable: Observable = wrap(this, methodName, opts).apply(this, args); + return new Observable((observer) => { + let wrappedSubscription = wrappedObservable.subscribe({ + next: (x) => { + observer.next(opts.resultTransform ? opts.resultTransform(x) : x); + if (opts.resultFinalPredicate && opts.resultFinalPredicate(x)) { + observer.complete(); + } + }, + error: (err) => { observer.error(err); }, + complete: () => { observer.complete(); } + }); + return () => { + wrappedSubscription.unsubscribe(); + }; + }); + } + }; + }; +} diff --git a/src/@ionic-native/core/index.ts b/src/@ionic-native/core/index.ts new file mode 100644 index 000000000..483a69500 --- /dev/null +++ b/src/@ionic-native/core/index.ts @@ -0,0 +1,3 @@ +export * from './plugin'; +export * from './decorators'; +export * from './util'; diff --git a/src/@ionic-native/core/plugin.ts b/src/@ionic-native/core/plugin.ts new file mode 100644 index 000000000..f09f91ccf --- /dev/null +++ b/src/@ionic-native/core/plugin.ts @@ -0,0 +1,309 @@ +import { get, getPlugin, getPromise, cordovaWarn, pluginWarn } from './util'; +import { checkReady } from './bootstrap'; +import { CordovaOptions } from './decorators'; + +import { Observable } from 'rxjs/Observable'; +import 'rxjs/add/observable/fromEvent'; + +checkReady(); + +declare var window; +declare var Promise; + + +/** + * Checks if plugin/cordova is available + * @return {boolean | { error: string } } + * @private + */ +export function checkAvailability(pluginRef: string, methodName?: string, pluginName?: string); +export function checkAvailability(pluginObj: any, methodName?: string, pluginName?: string); +export function checkAvailability(plugin: any, methodName?: string, pluginName?: string): boolean | { error: string } { + + let pluginRef, pluginInstance, pluginPackage; + + if (typeof plugin === 'string') { + pluginRef = plugin; + } else { + pluginRef = plugin.constructor.getPluginRef(); + pluginName = plugin.constructor.getPluginName(); + pluginPackage = plugin.constructor.getPluginInstallName(); + } + + pluginInstance = getPlugin(pluginRef); + + if (!pluginInstance || (!!methodName && pluginInstance[methodName] === 'undefined')) { + if (!window.cordova) { + cordovaWarn(pluginName, methodName); + return { + error: 'cordova_not_available' + }; + } + + pluginWarn(pluginName, pluginPackage, methodName); + return { + error: 'plugin_not_installed' + }; + } + + return true; +} + +/** + * Checks if _objectInstance exists and has the method/property + * @private + */ +export function instanceAvailability(pluginObj: any, methodName?: string): boolean { + return pluginObj._objectInstance && (!methodName || pluginObj._objectInstance[methodName] !== 'undefined'); +} + +function setIndex(args: any[], opts: any = {}, resolve?: Function, reject?: Function): any { + // ignore resolve and reject in case sync + if (opts.sync) { + return args; + } + + // If the plugin method expects myMethod(success, err, options) + if (opts.callbackOrder === 'reverse') { + // Get those arguments in the order [resolve, reject, ...restOfArgs] + args.unshift(reject); + args.unshift(resolve); + } else if (opts.callbackStyle === 'node') { + args.push((err, result) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + } 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') { + const setSuccessIndex = () => { + // If we've specified a success/error index + if (opts.successIndex > args.length) { + args[opts.successIndex] = resolve; + } else { + args.splice(opts.successIndex, 0, resolve); + } + }; + + const setErrorIndex = () => { + // We don't want that the reject cb gets spliced into the position of an optional argument that has not been defined and thus causing non expected behaviour. + if (opts.errorIndex > args.length) { + args[opts.errorIndex] = reject; // insert the reject fn at the correct specific index + } else { + args.splice(opts.errorIndex, 0, reject); // otherwise just splice it into the array + } + }; + + if (opts.successIndex > opts.errorIndex) { + setErrorIndex(); + setSuccessIndex(); + } else { + setSuccessIndex(); + setErrorIndex(); + } + + + } else { + // Otherwise, let's tack them on to the end of the argument list + // which is 90% of cases + args.push(resolve); + args.push(reject); + } + return args; +} + +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); + + const availabilityCheck = checkAvailability(pluginObj, methodName); + + if (availabilityCheck === true) { + const pluginInstance = getPlugin(pluginObj.constructor.getPluginRef()); + return pluginInstance[methodName].apply(pluginInstance, args); + } else { + return availabilityCheck; + } + +} + +function wrapPromise(pluginObj: any, methodName: string, args: any[], opts: any = {}) { + let pluginResult, rej; + const p = getPromise((resolve, reject) => { + pluginResult = callCordovaPlugin(pluginObj, methodName, args, opts, resolve, reject); + rej = reject; + }); + // Angular throws an error on unhandled rejection, but in this case we have already printed + // a warning that Cordova is undefined or the plugin is uninstalled, so there is no reason + // to error + if (pluginResult && pluginResult.error) { + p.catch(() => { }); + rej(pluginResult.error); + } + return p; +} + +function wrapOtherPromise(pluginObj: any, methodName: string, args: any[], opts: any= {}) { + return getPromise((resolve, reject) => { + let pluginResult = callCordovaPlugin(pluginObj, methodName, args, opts); + if (pluginResult && pluginResult.error) { + reject(pluginResult.error); + } + pluginResult.then(resolve).catch(reject); + }); +} + +function wrapObservable(pluginObj: any, methodName: string, args: any[], opts: any = {}) { + return new Observable(observer => { + let pluginResult = callCordovaPlugin(pluginObj, methodName, args, opts, observer.next.bind(observer), observer.error.bind(observer)); + if (pluginResult && pluginResult.error) { + observer.error(pluginResult.error); + observer.complete(); + } + return () => { + try { + if (opts.clearFunction) { + if (opts.clearWithArgs) { + return callCordovaPlugin(pluginObj, opts.clearFunction, args, opts, observer.next.bind(observer), observer.error.bind(observer)); + } + return get(window, pluginObj.constructor.getPluginRef())[opts.clearFunction].call(pluginObj, pluginResult); + } + } catch (e) { + console.warn('Unable to clear the previous observable watch for', pluginObj.constructor.getPluginName(), methodName); + console.error(e); + } + }; + }); +} + +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); + } + +} + +/** + * Wrap the event with an observable + * @private + * @param event even name + * @param element The element to attach the event listener to + * @returns {Observable} + */ +export function wrapEventObservable(event: string, element: any = window): Observable { + return Observable.fromEvent(element, event); +} + +/** + * Certain plugins expect the user to override methods in the plugin. For example, + * window.cordova.plugins.backgroundMode.onactivate = function() { ... }. + * + * Unfortunately, this is brittle and would be better wrapped as an Observable. overrideFunction + * does just this. + * @private + */ +export function overrideFunction(pluginObj: any, methodName: string, args: any[], opts: any = {}): Observable { + return new Observable(observer => { + + const availabilityCheck = checkAvailability(pluginObj, methodName); + + if (availabilityCheck === true) { + const pluginInstance = getPlugin(pluginObj.constructor.getPluginRef()); + pluginInstance[methodName] = observer.next.bind(observer); + return () => pluginInstance[methodName] = () => {}; + } else { + observer.error(availabilityCheck); + observer.complete(); + } + + }); +} + + +/** + * @private + */ +export const wrap = function(pluginObj: any, methodName: string, opts: CordovaOptions = {}) { + return (...args) => { + if (opts.sync) { + // Sync doesn't wrap the plugin with a promise or observable, it returns the result as-is + return callCordovaPlugin(pluginObj, methodName, args, opts); + } else if (opts.observable) { + return wrapObservable(pluginObj, methodName, args, opts); + } else if (opts.eventObservable && opts.event) { + return wrapEventObservable(opts.event, opts.element); + } else if (opts.otherPromise) { + return wrapOtherPromise(pluginObj, methodName, args, opts); + } else { + return wrapPromise(pluginObj, methodName, args, opts); + } + }; +}; + +/** + * @private + */ +export function wrapInstance(pluginObj: any, methodName: string, opts: any = {}) { + return (...args) => { + if (opts.sync) { + + return callInstance(pluginObj, methodName, args, opts); + + } else if (opts.observable) { + + return new Observable(observer => { + let pluginResult = callInstance(pluginObj, methodName, args, opts, observer.next.bind(observer), observer.error.bind(observer)); + + if (pluginResult && pluginResult.error) { + observer.error(pluginResult.error); + observer.complete(); + } + + return () => { + try { + if (opts.clearWithArgs) { + return pluginObj._objectInstance[opts.clearFunction].apply(pluginObj._objectInstance, args); + } + return pluginObj._objectInstance[opts.clearFunction].call(pluginObj, pluginResult); + } catch (e) { + console.warn('Unable to clear the previous observable watch for', pluginObj.constructor.getPluginName(), methodName); + console.error(e); + } + }; + }); + + } else if (opts.otherPromise) { + + return getPromise((resolve, reject) => { + let result = callInstance(pluginObj, methodName, args, opts, resolve, reject); + if (result && !result.error) { + result.then(resolve, reject); + } + }); + + } else { + + let pluginResult, rej; + const p = getPromise((resolve, reject) => { + pluginResult = callInstance(pluginObj, methodName, args, opts, resolve, reject); + rej = reject; + }); + if (pluginResult && pluginResult.error) { + p.catch(() => { }); + rej(pluginResult.error); + } + return p; + + } + }; +} diff --git a/src/@ionic-native/core/util.ts b/src/@ionic-native/core/util.ts new file mode 100644 index 000000000..cfc43e5f1 --- /dev/null +++ b/src/@ionic-native/core/util.ts @@ -0,0 +1,68 @@ +declare var window: any; + +/** + * @private + */ +export function get(obj, path) { + path = path.split('.'); + for (let i = 0; i < path.length; i++) { + if (!obj) { return null; } + obj = obj[path[i]]; + } + return obj; +} + + +/** + * @private + */ +export function getPromise(cb) { + + const tryNativePromise = () => { + if (window.Promise) { + return new Promise((resolve, reject) => { + cb(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 2 or on a recent browser.'); + } + }; + + return tryNativePromise(); +} + +/** + * @private + * @param pluginRef + * @returns {null|*} + */ +export function getPlugin(pluginRef: string): any { + return get(window, pluginRef); +}; + +/** + * @private + */ +export const pluginWarn = function(pluginName: string, plugin?: string, method?: string) { + if (method) { + 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.'); + } + if (plugin) { + console.warn('Install the ' + pluginName + ' plugin: \'ionic plugin add ' + plugin + '\''); + } +}; + +/** + * @private + * @param pluginName + * @param method + */ +export const cordovaWarn = function(pluginName: string, method?: string) { + 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'); + } 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'); + } +}; diff --git a/src/plugins/actionsheet.ts b/src/@ionic-native/plugins/action-sheet/index.ts similarity index 66% rename from src/plugins/actionsheet.ts rename to src/@ionic-native/plugins/action-sheet/index.ts index aaff5808a..fda207bb5 100644 --- a/src/plugins/actionsheet.ts +++ b/src/@ionic-native/plugins/action-sheet/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin, CordovaProperty } from '@ionic-native/core'; export interface ActionSheetOptions { @@ -53,15 +54,24 @@ export interface ActionSheetOptions { * * @usage * ```typescript - * import { ActionSheet } from 'ionic-native'; + * import { ActionSheet, ActionSheetOptions } from '@ionic-native/action-sheet'; + * + * constructor(private actionSheet: ActionSheet) { } + * + * ... + * * * let buttonLabels = ['Share via Facebook', 'Share via Twitter']; - * ActionSheet.show({ - * 'title': 'What do you want with this image?', - * 'buttonLabels': buttonLabels, - * 'addCancelButtonWithLabel': 'Cancel', - * 'addDestructiveButtonWithLabel' : 'Delete' - * }).then((buttonIndex: number) => { + * + * const options: ActionSheetOptions = { + * title: 'What do you want with this image?', + * buttonLabels: buttonLabels, + * addCancelButtonWithLabel: 'Cancel', + * addDestructiveButtonWithLabel: 'Delete', + * androidTheme: this.actionSheet.ANDROID_THEMES.THEME_HOLO_DARK + * }; + * + * this.actionSheet.show(options).then((buttonIndex: number) => { * console.log('Button pressed: ' + buttonIndex); * }); * ``` @@ -75,8 +85,18 @@ export interface ActionSheetOptions { repo: 'https://github.com/EddyVerbruggen/cordova-plugin-actionsheet', platforms: ['Android', 'iOS', 'Windows Phone 8'] }) +@Injectable() export class ActionSheet { + @CordovaProperty + ANDROID_THEMES: { + THEME_TRADITIONAL: number; + THEME_HOLO_DARK: number; + THEME_HOLO_LIGHT: number; + THEME_DEVICE_DEFAULT_DARK: number; + THEME_DEVICE_DEFAULT_LIGHT: number; + }; + /** * Show a native ActionSheet component. See below for options. * @param options {ActionSheetOptions} Options See table below @@ -84,7 +104,7 @@ export class ActionSheet { * button pressed (1 based, so 1, 2, 3, etc.) */ @Cordova() - static show(options?: ActionSheetOptions): Promise { return; } + show(options?: ActionSheetOptions): Promise { return; } /** @@ -92,6 +112,5 @@ export class ActionSheet { * @returns {Promise} Returns a Promise that resolves when the actionsheet is closed */ @Cordova() - static hide(options?: any): Promise { return; } - + hide(options?: any): Promise { return; } } diff --git a/src/plugins/admob.ts b/src/@ionic-native/plugins/ad-mob/index.ts similarity index 75% rename from src/plugins/admob.ts rename to src/@ionic-native/plugins/ad-mob/index.ts index 930f6addf..6eebf66ee 100644 --- a/src/plugins/admob.ts +++ b/src/@ionic-native/plugins/ad-mob/index.ts @@ -1,7 +1,8 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; -export type AdMobAdSize = 'SMART_BANNER' | 'BANNER' | 'MEDIUM_RECTANGLE' | 'FULL_BANNER' | 'LEADERBOARD' | 'SKYSCRAPER' | 'CUSTOM'; +export type AdSize = 'SMART_BANNER' | 'BANNER' | 'MEDIUM_RECTANGLE' | 'FULL_BANNER' | 'LEADERBOARD' | 'SKYSCRAPER' | 'CUSTOM'; export interface AdMobOptions { @@ -13,7 +14,7 @@ export interface AdMobOptions { /** * Banner Ad Size, defaults to `SMART_BANNER`. IT can be: `SMART_BANNER`, `BANNER`, `MEDIUM_RECTANGLE`, `FULL_BANNER`, `LEADERBOARD`, `SKYSCRAPER`, or `CUSTOM` */ - adSize?: AdMobAdSize; + adSize?: AdSize; /** * Banner width, valid when `adSize` is set to `CUSTOM` @@ -63,11 +64,11 @@ export interface AdMobOptions { /** * Set extra color style for Ad */ - adExtras?: AdMobAdExtras; + adExtras?: AdExtras; } -export interface AdMobAdExtras { +export interface AdExtras { color_bg: string; @@ -89,23 +90,25 @@ export interface AdMobAdExtras { * Plugin for Google Ads, including AdMob / DFP (doubleclick for publisher) and mediations to other Ad networks. * @usage * ```typescript - * import { AdMob } from 'ionic-native'; + * import { AdMob, AdMobOptions, AdSize, AdExtras } from '@ionic-native/ad-mob'; + * + * constructor(private admob: AdMob){} * * ionViewDidLoad() { - * AdMob.onAdDismiss() + * this.admob.onAdDismiss() * .subscribe(() => { console.log('User dismissed ad'); }); * } * * onClick() { - * AdMob.prepareInterstitial('YOUR_ADID') - * .then(() => { AdMob.showInterstitial(); }); + * this.admob.prepareInterstitial('YOUR_ADID') + * .then(() => { this.admob.showInterstitial(); }); * } * * ``` * * @interfaces * AdMobOptions - * AdMobAdExtras + * AdExtras */ @Plugin({ pluginName: 'AdMob', @@ -114,12 +117,22 @@ export interface AdMobAdExtras { repo: 'https://github.com/floatinghotpot/cordova-admob-pro', platforms: ['Android', 'iOS', 'Windows Phone 8'] }) +@Injectable() export class AdMob { - /** - * @private - */ - static AD_POSITION = { + AD_POSITION: { + NO_CHANGE: number; + TOP_LEFT: number; + TOP_CENTER: number; + TOP_RIGHT: number; + LEFT: number; + CENTER: number; + RIGHT: number; + BOTTOM_LEFT: number; + BOTTOM_CENTER: number; + BOTTOM_RIGHT: number; + POS_XY: number; + } = { NO_CHANGE: 0, TOP_LEFT: 1, TOP_CENTER: 2, @@ -139,7 +152,7 @@ export class AdMob { * @returns {Promise} Returns a Promise that resolves when the banner is created */ @Cordova() - static createBanner(adIdOrOptions: string | AdMobOptions): Promise { return; } + createBanner(adIdOrOptions: string | AdMobOptions): Promise { return; } /** * Destroy the banner, remove it from screen. @@ -147,7 +160,7 @@ export class AdMob { @Cordova({ sync: true }) - static removeBanner(): void { } + removeBanner(): void { } /** * Show banner at position @@ -156,7 +169,7 @@ export class AdMob { @Cordova({ sync: true }) - static showBanner(position: number): void { } + showBanner(position: number): void { } /** * Show banner at custom position @@ -166,7 +179,7 @@ export class AdMob { @Cordova({ sync: true }) - static showBannerAtXY(x: number, y: number): void { } + showBannerAtXY(x: number, y: number): void { } /** * Hide the banner, remove it from screen, but can show it later @@ -174,7 +187,7 @@ export class AdMob { @Cordova({ sync: true }) - static hideBanner(): void { } + hideBanner(): void { } /** * Prepare interstitial banner @@ -182,7 +195,7 @@ export class AdMob { * @returns {Promise} Returns a Promise that resolves when interstitial is prepared */ @Cordova() - static prepareInterstitial(adIdOrOptions: string | AdMobOptions): Promise { return; } + prepareInterstitial(adIdOrOptions: string | AdMobOptions): Promise { return; } /** * Show interstitial ad when it's ready @@ -190,7 +203,7 @@ export class AdMob { @Cordova({ sync: true }) - static showInterstitial(): void { } + showInterstitial(): void { } /** * Prepare a reward video ad @@ -198,7 +211,7 @@ export class AdMob { * @returns {Promise} Returns a Promise that resolves when the ad is prepared */ @Cordova() - static prepareRewardVideoAd(adIdOrOptions: string | AdMobOptions): Promise { return; } + prepareRewardVideoAd(adIdOrOptions: string | AdMobOptions): Promise { return; } /** * Show a reward video ad @@ -206,7 +219,7 @@ export class AdMob { @Cordova({ sync: true }) - static showRewardVideoAd(): void { } + showRewardVideoAd(): void { } /** * Sets the values for configuration and targeting @@ -214,14 +227,14 @@ export class AdMob { * @returns {Promise} Returns a Promise that resolves when the options have been set */ @Cordova() - static setOptions(options: AdMobOptions): Promise { return; } + setOptions(options: AdMobOptions): Promise { return; } /** * Get user ad settings * @returns {Promise} Returns a promise that resolves with the ad settings */ @Cordova() - static getAdSettings(): Promise { return; } + getAdSettings(): Promise { return; } /** * Triggered when failed to receive Ad @@ -231,7 +244,7 @@ export class AdMob { eventObservable: true, event: 'onAdFailLoad' }) - static onAdFailLoad(): Observable { return; } + onAdFailLoad(): Observable { return; } /** * Triggered when Ad received @@ -241,7 +254,7 @@ export class AdMob { eventObservable: true, event: 'onAdLoaded' }) - static onAdLoaded(): Observable { return; } + onAdLoaded(): Observable { return; } /** * Triggered when Ad will be showed on screen @@ -251,7 +264,7 @@ export class AdMob { eventObservable: true, event: 'onAdPresent' }) - static onAdPresent(): Observable { return; } + onAdPresent(): Observable { return; } /** * Triggered when user click the Ad, and will jump out of your App @@ -261,7 +274,7 @@ export class AdMob { eventObservable: true, event: 'onAdLeaveApp' }) - static onAdLeaveApp(): Observable { return; } + onAdLeaveApp(): Observable { return; } /** * Triggered when dismiss the Ad and back to your App @@ -271,6 +284,6 @@ export class AdMob { eventObservable: true, event: 'onAdDismiss' }) - static onAdDismiss(): Observable { return; } + onAdDismiss(): Observable { return; } } diff --git a/src/plugins/alipay.ts b/src/@ionic-native/plugins/alipay/index.ts similarity index 79% rename from src/plugins/alipay.ts rename to src/@ionic-native/plugins/alipay/index.ts index f81800f63..74fd39d21 100644 --- a/src/plugins/alipay.ts +++ b/src/@ionic-native/plugins/alipay/index.ts @@ -1,9 +1,6 @@ -import { Plugin, Cordova } from './plugin'; -/** - * @link https://doc.open.alipay.com/docs/doc.htm?spm=a219a.7629140.0.0.wlOhAE&treeId=193&articleId=105465&docType=1 - * - * All values need be urlencoded. - */ +import { Plugin, Cordova } from '@ionic-native/core'; +import { Injectable } from '@angular/core'; + export interface AlipayOrder { /** * appId assigned by Alipay @@ -42,7 +39,7 @@ export interface AlipayOrder { sign: string; /** - * Timestamp, formated like "yyyy-MM-dd HH:mm:ss", e.g. 2014-07-24 03:07:50 + * Timestamp, formated like "yyyy-MM-dd HH:mm:ss", e.g. 2014-07-24 03:07:50 */ timestamp: string; @@ -65,20 +62,23 @@ export interface AlipayOrder { /** * @name Alipay * @description - * This plugin is used for Alipay APP support. Integrated with the latest SDK. + * This plugin is used for Alipay APP support. Integrated with the latest SDK. * * Requires Cordova plugin: `cordova-alipay-base`. For more info, please see the [Alipay plugin docs](https://github.com/xueron/cordova-alipay-base). * * @usage * ``` - * import { Alipay } from 'ionic-native'; - * + * import { Alipay, AlipayOrder } from '@ionic-native/alipay'; + * + * constructor(private alipay: Alipay) { + * * // Should get from server side with sign. - * let alipayOrder = { - ... + * const alipayOrder: AlipayOrder = { + * ... * }; * - * Alipay.pay(alipayOrder) + * + * this.alipay.pay(alipayOrder) * .then(result => { * console.log(result); // Success * }) @@ -86,6 +86,9 @@ export interface AlipayOrder { * console.log(error); // Failed * }); * + * } + * + * * ``` * * @interfaces @@ -99,6 +102,7 @@ export interface AlipayOrder { platforms: ['Android', 'iOS'], install: 'ionic plugin add https://github.com/xueron/cordova-alipay-base --variable APP_ID=your_app_id' }) +@Injectable() export class Alipay { /** * Open Alipay to perform App pay @@ -106,6 +110,6 @@ export class Alipay { * @returns {Promise} Returns a Promise that resolves with the success return, or rejects with an error. */ @Cordova() - static pay(order: AlipayOrder): Promise { return; } + pay(order: AlipayOrder): Promise { return; } } diff --git a/src/plugins/android-fingerprint-auth.ts b/src/@ionic-native/plugins/android-fingerprint-auth/index.ts similarity index 69% rename from src/plugins/android-fingerprint-auth.ts rename to src/@ionic-native/plugins/android-fingerprint-auth/index.ts index 31083f83e..8ba69e5dc 100644 --- a/src/plugins/android-fingerprint-auth.ts +++ b/src/@ionic-native/plugins/android-fingerprint-auth/index.ts @@ -1,6 +1,8 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; -export interface AndroidFingerprintAuthOptions { + +export interface AFAAuthOptions { /** * Required @@ -63,20 +65,56 @@ export interface AndroidFingerprintAuthOptions { } +export interface AFADecryptOptions { + /** + * Biometric authentication + */ + withFingerprint: boolean; + /** + * Authentication using backup credential activity + */ + withBackup: boolean; + /** + * FingerprintAuth.CipherMode.DECRYPT + * Decrypted password + */ + password: string; +} + +export interface AFAEncryptResponse { + /** + * Biometric authentication + */ + withFingerprint: boolean; + /** + * Authentication using backup credential activity + */ + withBackup: boolean; + /** + * base64encoded string representation of user credentials + */ + token: string; +} + /** * @name Android Fingerprint Auth * @description * This plugin will open a native dialog fragment prompting the user to authenticate using their fingerprint. If the device has a secure lockscreen (pattern, PIN, or password), the user may opt to authenticate using that method as a backup. * @usage * ```typescript - * import { AndroidFingerprintAuth } from 'ionic-native'; + * import { AndroidFingerprintAuth, AFAAuthOptions } from '@ionic-native/android-fingerprint-auth'; * - * AndroidFingerprintAuth.isAvailable() + * constructor(private androidFingerprintAuth: AndroidFingerprintAuth) { } + * + * ... + * + * + * this.androidFingerprintAuth.isAvailable() * .then((result)=> { * if(result.isAvailable){ * // it is available * - * AndroidFingerprintAuth.encrypt({ clientId: "myAppName", username: "myUsername", password: "myPassword" }) + * this.androidFingerprintAuth.encrypt({ clientId: "myAppName", username: "myUsername", password: "myPassword" }) * .then(result => { * if (result.withFingerprint) { * console.log("Successfully encrypted credentials."); @@ -98,7 +136,9 @@ export interface AndroidFingerprintAuthOptions { * .catch(error => console.error(error)); * ``` * @interfaces - * AndroidFingerprintAuthOptions + * AFAAuthOptions + * AFAEncryptResponse + * AFADecryptOptions */ @Plugin({ pluginName: 'AndroidFingerprintAuth', @@ -106,62 +146,36 @@ export interface AndroidFingerprintAuthOptions { pluginRef: 'FingerprintAuth', repo: 'https://github.com/mjwheatley/cordova-plugin-android-fingerprint-auth' }) +@Injectable() export class AndroidFingerprintAuth { /** * Opens a native dialog fragment to use the device hardware fingerprint scanner to authenticate against fingerprints registered for the device. - * @param options {AndroidFingerprintAuthOptions} Options + * @param options {AFAAuthOptions} Options * @returns {Promise} */ @Cordova() - static encrypt(options: AndroidFingerprintAuthOptions): Promise<{ - /** - * Biometric authentication - */ - withFingerprint: boolean; - /** - * Authentication using backup credential activity - */ - withBackup: boolean; - /** - * base64encoded string representation of user credentials - */ - token: string; - }> {return; } + encrypt(options: AFAAuthOptions): Promise {return; } /** * Opens a native dialog fragment to use the device hardware fingerprint scanner to authenticate against fingerprints registered for the device. - * @param options {AndroidFingerprintAuthOptions} Options + * @param options {AFAAuthOptions} Options * @returns {Promise} */ @Cordova() - static decrypt(options: AndroidFingerprintAuthOptions): Promise<{ - /** - * Biometric authentication - */ - withFingerprint: boolean; - /** - * Authentication using backup credential activity - */ - withBackup: boolean; - /** - * FingerprintAuth.CipherMode.DECRYPT - * Decrypted password - */ - password: string; - }> {return; } + decrypt(options: AFAAuthOptions): Promise {return; } /** * Check if service is available * @returns {Promise} Returns a Promise that resolves if fingerprint auth is available on the device */ @Cordova() - static isAvailable(): Promise<{isAvailable: boolean}> { return; } + isAvailable(): Promise<{isAvailable: boolean}> { return; } /** * Delete the cipher used for encryption and decryption by username * @returns {Promise} Returns a Promise that resolves if the cipher was successfully deleted */ @Cordova() - static delete(options: {clientId: string; username: string; }): Promise<{deleted: boolean}> { return; } + delete(options: {clientId: string; username: string; }): Promise<{deleted: boolean}> { return; } } diff --git a/src/plugins/appavailability.ts b/src/@ionic-native/plugins/app-availability/index.ts similarity index 68% rename from src/plugins/appavailability.ts rename to src/@ionic-native/plugins/app-availability/index.ts index 0b96b1d72..f31230a04 100644 --- a/src/plugins/appavailability.ts +++ b/src/@ionic-native/plugins/app-availability/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; /** * @name App Availability @@ -9,18 +10,22 @@ import { Cordova, Plugin } from './plugin'; * * @usage * ```typescript - * import { AppAvailability, Device } from 'ionic-native'; + * import { AppAvailability } from '@ionic-native/app-availability'; + * import { Platform } from 'ionic-angular'; * + * constructor(private appAvailability: AppAvailability, private platform: Platform) { } + * + * ... * * let app; * - * if (Device.platform === 'iOS') { + * if (this.platform.is('ios')) { * app = 'twitter://'; - * } else if (Device.platform === 'Android') { + * } else if (this.platform.is('android')) { * app = 'com.twitter.android'; * } * - * AppAvailability.check(app) + * this.appAvailability.check(app) * .then( * (yes: string) => console.log(app + ' is available'), * (no: string) => console.log(app + ' is NOT available') @@ -34,6 +39,7 @@ import { Cordova, Plugin } from './plugin'; repo: 'https://github.com/ohh2ahh/AppAvailability', platforms: ['Android', 'iOS'] }) +@Injectable() export class AppAvailability { /** @@ -42,6 +48,6 @@ export class AppAvailability { * @returns {Promise} */ @Cordova() - static check(app: string): Promise { return; } + check(app: string): Promise { return; } } diff --git a/src/plugins/apppreferences.ts b/src/@ionic-native/plugins/app-preferences/index.ts similarity index 75% rename from src/plugins/apppreferences.ts rename to src/@ionic-native/plugins/app-preferences/index.ts index fee70060d..69242fa80 100644 --- a/src/plugins/apppreferences.ts +++ b/src/@ionic-native/plugins/app-preferences/index.ts @@ -1,18 +1,23 @@ -import { Cordova, Plugin } from './plugin'; +import { Cordova, Plugin } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; +import { Injectable } from '@angular/core'; /** - * @name AppPreferences + * @name App Preferences * @description * This plugin allows you to read and write app preferences * * @usage + * ```typescript + * import { AppPreferences } from '@ionic-native/app-preferences'; + * + * constructor(private appPreferences: AppPreferences) { + * + * this.appPreferences.fetch('key').then((res) => { console.log(res); }); + * + * } * ``` - * import { AppPreferences } from 'ionic-native'; * - * AppPreferences.fetch('key').then((res) => { console.log(res); }); - * - *``` */ @Plugin({ pluginName: 'AppPreferences', @@ -20,6 +25,7 @@ import { Observable } from 'rxjs/Observable'; pluginRef: 'plugins.appPreferences', // the variable reference to call the plugin, example: navigator.geolocation repo: 'https://github.com/apla/me.apla.cordova.app-preferences', // the github repository URL for the plugin }) +@Injectable() export class AppPreferences { /** @@ -33,7 +39,7 @@ export class AppPreferences { sync: true, callbackOrder: 'reverse' }) - static fetch(dict: string, key?: string): Promise { return; } + fetch(dict: string, key?: string): Promise { return; } /** * Set a preference value @@ -46,7 +52,7 @@ export class AppPreferences { @Cordova({ callbackOrder: 'reverse' }) - static store(dict: string, key: string, value?: string): Promise { + store(dict: string, key: string, value?: string): Promise { return; } @@ -60,7 +66,7 @@ export class AppPreferences { @Cordova({ callbackOrder: 'reverse' }) - static remove(dict: string, key?: string): Promise { return; } + remove(dict: string, key?: string): Promise { return; } /** * Clear preferences @@ -70,7 +76,7 @@ export class AppPreferences { @Cordova({ callbackOrder: 'reverse' }) - static clearAll(): Promise { return; } + clearAll(): Promise { return; } /** * Show native preferences interface @@ -80,7 +86,7 @@ export class AppPreferences { @Cordova({ callbackOrder: 'reverse' }) - static show(): Promise { return; } + show(): Promise { return; } /** * Show native preferences interface @@ -91,7 +97,7 @@ export class AppPreferences { @Cordova({ observable: true }) - static watch(subscribe: boolean): Observable { return; } + watch(subscribe: boolean): Observable { return; } /** * Return named configuration context @@ -103,12 +109,12 @@ export class AppPreferences { @Cordova({ platforms: ['Android'] }) - static suite(suiteName: string): Object { return; } + suite(suiteName: string): Object { return; } @Cordova({ platforms: ['iOS'] }) - static iosSuite(suiteName: string): Object { return; } + iosSuite(suiteName: string): Object { return; } /** * Return cloud synchronized configuration context @@ -118,7 +124,7 @@ export class AppPreferences { @Cordova({ platforms: ['iOS', 'Windows', 'Windows Phone 8'] }) - static cloudSync(): Object { return; } + cloudSync(): Object { return; } /** * Return default configuration context @@ -128,6 +134,6 @@ export class AppPreferences { @Cordova({ platforms: ['iOS', 'Windows', 'Windows Phone 8'] }) - static defaults(): Object { return; } + defaults(): Object { return; } } diff --git a/src/plugins/apprate.ts b/src/@ionic-native/plugins/app-rate/index.ts similarity index 84% rename from src/plugins/apprate.ts rename to src/@ionic-native/plugins/app-rate/index.ts index 46ae11df1..cb1b57c70 100644 --- a/src/plugins/apprate.ts +++ b/src/@ionic-native/plugins/app-rate/index.ts @@ -1,4 +1,6 @@ -import { Cordova, CordovaProperty, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, CordovaProperty, Plugin } from '@ionic-native/core'; + declare var window; @@ -47,7 +49,7 @@ export interface AppRatePreferences { /** * App Store URLS */ - storeAppURL?: AppRateStoreAppUrls; + storeAppURL?: AppUrls; } @@ -65,7 +67,7 @@ export interface AppRateCallbacks { } -export interface AppRateStoreAppUrls { +export interface AppUrls { /** * application id in AppStore @@ -103,20 +105,24 @@ export interface AppRateStoreAppUrls { * * @usage * ```typescript - * import { AppRate } from 'ionic-native'; + * import { AppRate } from '@ionic-native/app-rate'; * - * AppRate.preferences.storeAppURL = { + * constructor(private appRate: AppRate) { } + * + * ... + * + * this.appRate.preferences.storeAppURL = { * ios: '', * android: 'market://details?id=', * windows: 'ms-windows-store://review/?ProductId=' * }; * - * AppRate.promptForRating(false); + * this.appRate.promptForRating(false); * ``` * * @interfaces * AppRatePreferences - * AppRateStoreAppUrls + * AppUrls * AppRateCallbacks * */ @@ -127,6 +133,7 @@ export interface AppRateStoreAppUrls { repo: 'https://github.com/pushandplay/cordova-plugin-apprate', platforms: ['Android', 'iOS', 'Windows (experimental)'] }) +@Injectable() export class AppRate { /** @@ -134,13 +141,13 @@ export class AppRate { * See table below for options */ @CordovaProperty - static preferences: AppRatePreferences; + preferences: AppRatePreferences; /** * Prompts the user for rating * @param {boolean} immediately Show the rating prompt immediately. */ @Cordova() - static promptForRating(immediately: boolean): void { }; + promptForRating(immediately: boolean): void { }; } diff --git a/src/plugins/app-update.ts b/src/@ionic-native/plugins/app-update/index.ts similarity index 68% rename from src/plugins/app-update.ts rename to src/@ionic-native/plugins/app-update/index.ts index 181075216..05e4080f8 100644 --- a/src/plugins/app-update.ts +++ b/src/@ionic-native/plugins/app-update/index.ts @@ -1,7 +1,8 @@ -import { Plugin, Cordova } from './plugin'; +import { Plugin, Cordova } from '@ionic-native/core'; +import { Injectable } from '@angular/core'; /** - * @name AppUpdate + * @name App Update * @description * This plugin does self-update for android * @@ -19,11 +20,16 @@ import { Plugin, Cordova } from './plugin'; * Then use the following code: * * ``` - * import { AppUpdate } from 'ionic-native'; + * import { AppUpdate } from '@ionic-native/app-update'; + * + * constructor(private appUpdate: AppUpdate) { + * + * const updateUrl = 'http://your-remote-api.com/update.xml'; + * this.appUpdate.checkAppUpdate(updateUrl); + * + * } * - * let updateUrl = 'http://your-remote-api.com/update.xml'; * - * AppUpdate.checkAppUpdate(updateUrl); * ``` * * The plugin will compare the app version and update it automatically if the API has a newer version to install. @@ -35,6 +41,7 @@ import { Plugin, Cordova } from './plugin'; repo: 'https://github.com/vaenow/cordova-plugin-app-update', platforms: ['Android'] }) +@Injectable() export class AppUpdate { /** * Check and update @@ -44,6 +51,6 @@ export class AppUpdate { @Cordova({ callbackOrder: 'reverse' }) - static checkAppUpdate(updateUrl: string): Promise { return; } + checkAppUpdate(updateUrl: string): Promise { return; } } diff --git a/src/plugins/appversion.ts b/src/@ionic-native/plugins/app-version/index.ts similarity index 62% rename from src/plugins/appversion.ts rename to src/@ionic-native/plugins/app-version/index.ts index 130715719..2c09da5f2 100644 --- a/src/plugins/appversion.ts +++ b/src/@ionic-native/plugins/app-version/index.ts @@ -1,4 +1,7 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; + + /** * @name App Version @@ -9,13 +12,18 @@ import { Cordova, Plugin } from './plugin'; * * @usage * ```typescript - * import { AppVersion } from 'ionic-native'; + * import { AppVersion } from '@ionic-native/app-version'; + * + * constructor(private appVersion: AppVersion) { } + * + * ... * * - * AppVersion.getAppName(); - * AppVersion.getPackageName(); - * AppVersion.getVersionCode(); - * AppVersion.getVersionNumber(); + * this.appVersion.getAppName(); + * this.appVersion.getPackageName(); + * this.appVersion.getVersionCode(); + * this.appVersion.getVersionNumber(); + * * ``` */ @Plugin({ @@ -25,6 +33,7 @@ import { Cordova, Plugin } from './plugin'; repo: 'https://github.com/whiteoctober/cordova-plugin-app-version', platforms: ['Android', 'iOS'] }) +@Injectable() export class AppVersion { /** @@ -32,27 +41,27 @@ export class AppVersion { * @returns {Promise} */ @Cordova() - static getAppName(): Promise { return; } + getAppName(): Promise { return; } /** * Returns the package name of the app * @returns {Promise} */ @Cordova() - static getPackageName(): Promise { return; } + getPackageName(): Promise { return; } /** * Returns the build identifier of the app * @returns {Promise} */ @Cordova() - static getVersionCode(): Promise { return; } + getVersionCode(): Promise { return; } /** * Returns the version of the app * @returns {Promise} */ @Cordova() - static getVersionNumber(): Promise { return; } + getVersionNumber(): Promise { return; } } diff --git a/src/@ionic-native/plugins/appodeal/index.ts b/src/@ionic-native/plugins/appodeal/index.ts new file mode 100644 index 000000000..37c41ff27 --- /dev/null +++ b/src/@ionic-native/plugins/appodeal/index.ts @@ -0,0 +1,519 @@ +import { Plugin, Cordova } from '@ionic-native/core'; +import { Observable } from 'rxjs'; +import { Injectable } from '@angular/core'; + +/** + * @name Appodeal + * @description + * Plugin to serve ads through native Appodeal SDKs + * + * @usage + * ``` + * import { Appodeal } from '@ionic-native/appodeal'; + * + * constructor(private appodeal: Appodeal) { + * + * const appKey = ''; + * appodeal.initialize(appKey, appodeal.AD_TYPES.REWARDED_VIDEO); + * appodeal.show(appodeal.AD_TYPES.REWARDED_VIDEO); + * + * } + * + * + * + * ``` + */ +@Plugin({ + pluginName: 'Appodeal', + plugin: 'https://github.com/appodeal/appodeal-cordova-plugin', + pluginRef: 'Appodeal', + repo: 'https://github.com/appodeal/appodeal-cordova-plugin.git', + platforms: [ 'ios', 'android' ] +}) +@Injectable() +export class Appodeal { + // available types of advertisements + readonly AD_TYPES = { + INTERSTITIAL: 1, + SKIPPABLE_VIDEO: 2, + BANNER: 4, + BANNER_BOTTOM: 8, + BANNER_TOP: 16, + REWARDED_VIDEO: 128, + NON_SKIPPABLE_VIDEO: 256 + }; + + /** + * initialize Appodeal SDK + * @param {string} appKey + * @param {number} adType + */ + @Cordova() + initialize(appKey: string, adType: number): void {}; + + /** + * check if SDK has been initialized + * @returns {Promise} + */ + @Cordova() + isInitialized(): Promise { return; }; + + /** + * show ad of specified type + * @param {number} adType + * @returns {Promise} + */ + @Cordova() + show(adType: number): Promise { return; }; + + /** + * show ad of specified type with placement options + * @param {number} adType + * @param {any} placement + * @returns {Promise} + */ + @Cordova() + showWithPlacement( + adType: number, + placement: any + ): Promise { return; }; + + /** + * hide ad of specified type + * @param {number} adType + */ + @Cordova() + hide(adType: number): void {}; + + /** + * confirm use of ads of specified type + * @param {number} adType + */ + @Cordova() + confirm(adType: number): void {}; + + /** + * check if ad of specified type has been loaded + * @param {number} adType + * @returns {Promise} + */ + @Cordova() + isLoaded(adType: number): Promise { return; }; + + /** + * check if ad of specified + * @param {number} adType + * @returns {Promise} + */ + @Cordova() + isPrecache(adType: number): Promise { return; }; + + /** + * + * @param {number} adType + * @param autoCache + */ + @Cordova() + setAutoCache(adType: number, autoCache: any): void {}; + + /** + * forcefully cache an ad by type + * @param {number} adType + */ + @Cordova() + cache(adType: number): void {}; + + /** + * + * @param {boolean} set + */ + @Cordova() + setOnLoadedTriggerBoth(set: boolean): void {}; + + /** + * enable or disable Smart Banners + * @param {boolean} enabled + */ + @Cordova() + setSmartBanners(enabled: boolean): void {}; + + /** + * enable or disable banner backgrounds + * @param {boolean} enabled + */ + @Cordova() + setBannerBackground(enabled: boolean): void {}; + + /** + * enable or disable banner animations + * @param {boolean} enabled + */ + @Cordova() + setBannerAnimation(enabled: boolean): void {}; + + /** + * + * @param value + */ + @Cordova() + set728x90Banners(value: any): void {}; + + /** + * enable or disable logging + * @param {boolean} logging + */ + @Cordova() + setLogging(logging: boolean): void {}; + + /** + * enable or disable testing mode + * @param {boolean} testing + */ + @Cordova() + setTesting(testing: boolean): void {}; + + /** + * reset device ID + */ + @Cordova() + resetUUID(): void {}; + + /** + * get version of Appdeal SDK + */ + @Cordova() + getVersion(): Promise { return; }; + + /** + * + * @param {string} network + * @param {number} adType + */ + @Cordova() + disableNetwork(network?: string, adType?: number): void {}; + + /** + * + * @param {string} network + * @param {number} adType + */ + @Cordova() + disableNetworkType(network?: string, adType?: number): void {}; + + /** + * disable Location permissions for Appodeal SDK + */ + @Cordova() + disableLocationPermissionCheck(): void {}; + + /** + * disable Storage permissions for Appodeal SDK + */ + @Cordova() + disableWriteExternalStoragePermissionCheck(): void {}; + + /** + * enable event listeners + * @param {boolean} enabled + */ + @Cordova() + enableInterstitialCallbacks(enabled: boolean): void {}; + + /** + * enable event listeners + * @param {boolean} enabled + */ + @Cordova() + enableSkippableVideoCallbacks(enabled: boolean): void {}; + + /** + * enable event listeners + * @param {boolean} enabled + */ + @Cordova() + enableNonSkippableVideoCallbacks(enabled: boolean): void {}; + + /** + * enable event listeners + * @param {boolean} enabled + */ + @Cordova() + enableBannerCallbacks(enabled: boolean): void {}; + + /** + * enable event listeners + * @param {boolean} enabled + */ + @Cordova() + enableRewardedVideoCallbacks(enabled: boolean): void {}; + + /** + * + * @param {string} name - name of rule + * @param {boolean} value + */ + @Cordova() + setCustomBooleanRule(name: string, value: boolean): void {}; + + /** + * + * @param {string} name - name of rule + * @param {number} value + */ + @Cordova() + setCustomIntegerRule(name: string, value: number): void {}; + + /** + * set rule with float value + * @param {string} name + * @param {number} value + */ + @Cordova() + setCustomDoubleRule(name: string, value: number): void {}; + + /** + * set rule with string value + * @param {string} name - name of rule + * @param {string} value + */ + @Cordova() + setCustomStringRule(name: string, value: string): void {}; + + /** + * set ID preference in Appodeal for current user + * @param id + */ + @Cordova() + setUserId(id: any): void {}; + + /** + * set Email preference in Appodeal for current user + * @param email + */ + @Cordova() + setEmail(email: any): void {}; + + /** + * set Birthday preference in Appodeal for current user + * @param birthday + */ + @Cordova() + setBirthday(birthday: any): void {}; + + /** + * et Age preference in Appodeal for current user + * @param age + */ + @Cordova() + setAge(age: any): void {}; + + /** + * set Gender preference in Appodeal for current user + * @param gender + */ + @Cordova() + setGender(gender: any): void {}; + + /** + * set Occupation preference in Appodeal for current user + * @param occupation + */ + @Cordova() + setOccupation(occupation: any): void {}; + + /** + * set Relation preference in Appodeal for current user + * @param relation + */ + @Cordova() + setRelation(relation: any): void {}; + + /** + * set Smoking preference in Appodeal for current user + * @param smoking + */ + @Cordova() + setSmoking(smoking: any): void {}; + + /** + * set Alcohol preference in Appodeal for current user + * @param alcohol + */ + @Cordova() + setAlcohol(alcohol: any): void {}; + + /** + * set Interests preference in Appodeal for current user + * @param interests + */ + @Cordova() + setInterests(interests: any): void {}; + + @Cordova({ + eventObservable: true, + event: 'onInterstitialLoaded', + element: document + }) + onInterstitialLoaded(): Observable { return; } + + @Cordova({ + eventObservable: true, + event: 'onInterstitialFailedToLoad', + element: document + }) + onInterstitialFailedToLoad(): Observable { return; } + + @Cordova({ + eventObservable: true, + event: 'onInterstitialShown', + element: document + }) + onInterstitialShown(): Observable { return; } + + @Cordova({ + eventObservable: true, + event: 'onInterstitialClicked', + element: document + }) + onInterstitialClicked(): Observable { return; } + + @Cordova({ + eventObservable: true, + event: 'onInterstitialClosed', + element: document + }) + onInterstitialClosed(): Observable { return; } + + @Cordova({ + eventObservable: true, + event: 'onSkippableVideoLoaded', + element: document + }) + onSkippableVideoLoaded(): Observable { return; } + + @Cordova({ + eventObservable: true, + event: 'onSkippableVideoFailedToLoad', + element: document + }) + onSkippableVideoFailedToLoad(): Observable { return; } + + @Cordova({ + eventObservable: true, + event: 'onSkippableVideoShown', + element: document + }) + onSkippableVideoShown(): Observable { return; } + + @Cordova({ + eventObservable: true, + event: 'onSkippableVideoFinished', + element: document + }) + onSkippableVideoFinished(): Observable { return; } + + @Cordova({ + eventObservable: true, + event: 'onSkippableVideoClosed', + element: document + }) + onSkippableVideoClosed(): Observable { return; } + + @Cordova({ + eventObservable: true, + event: 'onRewardedVideoLoaded', + element: document + }) + onRewardedVideoLoaded(): Observable { return; } + + @Cordova({ + eventObservable: true, + event: 'onRewardedVideoFailedToLoad', + element: document + }) + onRewardedVideoFailedToLoad(): Observable { return; } + + @Cordova({ + eventObservable: true, + event: 'onRewardedVideoShown', + element: document + }) + onRewardedVideoShown(): Observable { return; } + + @Cordova({ + eventObservable: true, + event: 'onRewardedVideoFinished', + element: document + }) + onRewardedVideoFinished(): Observable { return; } + + @Cordova({ + eventObservable: true, + event: 'onRewardedVideoClosed', + element: document + }) + onRewardedVideoClosed(): Observable { return; } + + @Cordova({ + eventObservable: true, + event: 'onNonSkippableVideoLoaded', + element: document + }) + onNonSkippableVideoLoaded(): Observable { return; } + + @Cordova({ + eventObservable: true, + event: 'onNonSkippableVideoFailedToLoad', + element: document + }) + onNonSkippableVideoFailedToLoad(): Observable { return; } + + @Cordova({ + eventObservable: true, + event: 'onNonSkippableVideoShown', + element: document + }) + onNonSkippableVideoShown(): Observable { return; } + + @Cordova({ + eventObservable: true, + event: 'onNonSkippableVideoFinished', + element: document + }) + onNonSkippableVideoFinished(): Observable { return; } + + @Cordova({ + eventObservable: true, + event: 'onNonSkippableVideoClosed', + element: document + }) + onNonSkippableVideoClosed(): Observable { return; } + + @Cordova({ + eventObservable: true, + event: 'onBannerClicked', + element: document + }) + onBannerClicked(): Observable { return; } + + @Cordova({ + eventObservable: true, + event: 'onBannerFailedToLoad', + element: document + }) + onBannerFailedToLoad(): Observable { return; } + + @Cordova({ + eventObservable: true, + event: 'onBannerLoaded', + element: document + }) + onBannerLoaded(): Observable { return; } + + @Cordova({ + eventObservable: true, + event: 'onBannerShown', + element: document + }) + onBannerShown(): Observable { return; } +} diff --git a/src/plugins/background-fetch.ts b/src/@ionic-native/plugins/background-fetch/index.ts similarity index 59% rename from src/plugins/background-fetch.ts rename to src/@ionic-native/plugins/background-fetch/index.ts index 8bb71ef9e..c91bc6ae8 100644 --- a/src/plugins/background-fetch.ts +++ b/src/@ionic-native/plugins/background-fetch/index.ts @@ -1,4 +1,5 @@ -import {Cordova, Plugin} from './plugin'; +import { Cordova, Plugin } from '@ionic-native/core'; +import { Injectable } from '@angular/core'; declare var window; @@ -13,7 +14,7 @@ export interface BackgroundFetchConfig { /** - * @name BackgroundFetch + * @name Background Fetch * @description * iOS Background Fetch Implementation. See: https://developer.apple.com/reference/uikit/uiapplication#1657399 * iOS Background Fetch is basically an API which wakes up your app about every 15 minutes (during the user's prime-time hours) and provides your app exactly 30s of background running-time. This plugin will execute your provided callbackFn whenever a background-fetch event occurs. There is no way to increase the rate which a fetch-event occurs and this plugin sets the rate to the most frequent possible value of UIApplicationBackgroundFetchIntervalMinimum -- iOS determines the rate automatically based upon device usage and time-of-day (ie: fetch-rate is about ~15min during prime-time hours; less frequently when the user is presumed to be sleeping, at 3am for example). @@ -22,35 +23,32 @@ export interface BackgroundFetchConfig { * @usage * * ```typescript - * import { BackgroundFetch } from 'ionic-native'; + * import { BackgroundFetch, BackgroundFetchConfig } from '@ionic-native/background-fetch'; * * - * // When device is ready : - * platform.ready().then(() => { + * constructor(private backgroundFetch: BackgroundFetch) { * - * let config = { + * const config: BackgroundFetchConfig = { * stopOnTerminate: false, // Set true to cease background-fetch from operating after user "closes" the app. Defaults to true. * }; * - * BackgroundFetch.configure(() => { - console.log('[js] BackgroundFetch initiated'); - - // perform some ajax request to server here - - You MUST called #finish so that native-side can signal completion of the background-thread to the os. - BackgroundFetch.finish(); - - * }, (error) => { - * console.log('- BackgroundFetch failed', error); - * }, config); + * backgroundFetch.configure(config) + * .then(() => { + * console.log('Background Fetch initialized'); * - * }); + * this.backgroundFetch.finish(); * - * // Start the background-fetch API. Your callbackFn provided to #configure will be executed each time a background-fetch event occurs. NOTE the #configure method automatically calls #start. You do not have to call this method after you #configure the plugin - * BackgroundFetch.start(); + * }) + * .catch(e => console.log('Error initializing background fetch', e)); * - * // Stop the background-fetch API from firing fetch events. Your callbackFn provided to #configure will no longer be executed. - * BackgroundFetch.stop(); + * // Start the background-fetch API. Your callbackFn provided to #configure will be executed each time a background-fetch event occurs. NOTE the #configure method automatically calls #start. You do not have to call this method after you #configure the plugin + * backgroundFetch.start(); + * + * // Stop the background-fetch API from firing fetch events. Your callbackFn provided to #configure will no longer be executed. + * backgroundFetch.stop(); + * + * + * } * * ``` * @interfaces @@ -64,25 +62,20 @@ export interface BackgroundFetchConfig { repo: 'https://github.com/transistorsoft/cordova-plugin-background-fetch', platforms: ['iOS'] }) +@Injectable() export class BackgroundFetch { /** * Configures the plugin's fetch callbackFn * - * @param {Function} callbackFn This callback will fire each time an iOS background-fetch event occurs (typically every 15 min). - * @param {Function} errorCallback The failureFn will be called if the device doesn't support background-fetch. * @param {BackgroundFetchConfig} config Configuration for plugin - * @return Location object, which tries to mimic w3c Coordinates interface. - * See http://dev.w3.org/geo/api/spec-source.html#coordinates_interface - * Callback to be executed every time a geolocation is recorded in the background. + * @return {Promise} */ @Cordova({ - sync: true + callbackOrder: 'reverse' }) - static configure(callbackFn: Function, errorCallback: Function, config: BackgroundFetchConfig): any { return; } - - + configure(config: BackgroundFetchConfig): Promise { return; } /** * Start the background-fetch API. @@ -90,18 +83,21 @@ export class BackgroundFetch { * @returns {Promise} */ @Cordova() - static start(): Promise { return; } + start(): Promise { return; } /** * Stop the background-fetch API from firing fetch events. Your callbackFn provided to #configure will no longer be executed. * @returns {Promise} */ @Cordova() - static stop(): Promise { return; } + stop(): Promise { return; } /** * You MUST call this method in your fetch callbackFn provided to #configure in order to signal to iOS that your fetch action is complete. iOS provides only 30s of background-time for a fetch-event -- if you exceed this 30s, iOS will kill your app. */ - @Cordova() - static finish() { } + @Cordova({ + sync: true + }) + finish(): void { } + } diff --git a/src/plugins/background-geolocation.ts b/src/@ionic-native/plugins/background-geolocation/index.ts similarity index 83% rename from src/plugins/background-geolocation.ts rename to src/@ionic-native/plugins/background-geolocation/index.ts index 73ab534b3..c6126306f 100644 --- a/src/plugins/background-geolocation.ts +++ b/src/@ionic-native/plugins/background-geolocation/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; declare var window; @@ -255,23 +256,23 @@ export interface BackgroundGeolocationConfig { } /** - * @name BackgroundGeolocation + * @name Background Geolocation * @description * This plugin provides foreground and background geolocation with battery-saving "circular region monitoring" and "stop detection". For * more detail, please see https://github.com/mauron85/cordova-plugin-background-geolocation * * @usage * + * BackgroundGeolocation must be called within app.ts and or before Geolocation. Otherwise the platform will not ask you for background tracking permission. + * * ```typescript - * import { BackgroundGeolocation } from 'ionic-native'; + * import { BackgroundGeolocation, BackgroundGeolocationConfig } from '@ionic-native/background-geolocation'; * + * constructor(private backgroundGeolocation: BackgroundGeolocation) { } * - * // When device is ready : - * platform.ready().then(() => { - * // IMPORTANT: BackgroundGeolocation must be called within app.ts and or before Geolocation. Otherwise the platform will not ask you for background tracking permission. + * ... * - * // BackgroundGeolocation is highly configurable. See platform specific configuration options - * let config = { + * const config: BackgroundGeolocationConfig = { * desiredAccuracy: 10, * stationaryRadius: 20, * distanceFilter: 30, @@ -279,24 +280,23 @@ export interface BackgroundGeolocationConfig { * stopOnTerminate: false, // enable this to clear background location settings when the app terminates * }; * - * BackgroundGeolocation.configure((location) => { - console.log('[js] BackgroundGeolocation callback: ' + location.latitude + ',' + location.longitude); - - // IMPORTANT: You must execute the finish method here to inform the native plugin that you're finished, - // and the background-task may be completed. You must do this regardless if your HTTP request is successful or not. - // IF YOU DON'T, ios will CRASH YOUR APP for spending too much time in the background. - BackgroundGeolocation.finish(); // FOR IOS ONLY - - * }, (error) => { - * console.log('BackgroundGeolocation error'); - * }, config); + * this.backgroundGeolocation.configure(config) + * .subscribe((location: BackgroundGeolocationResponse) => { * - * // Turn ON the background-geolocation system. The user will be tracked whenever they suspend the app. - * BackgroundGeolocation.start(); - * }) + * console.log(location); + * + * // IMPORTANT: You must execute the finish method here to inform the native plugin that you're finished, + * // and the background-task may be completed. You must do this regardless if your HTTP request is successful or not. + * // IF YOU DON'T, ios will CRASH YOUR APP for spending too much time in the background. + * BackgroundGeolocation.finish(); // FOR IOS ONLY + * + * }); + * + * // start recording location + * this.backgroundGeolocation.start(); * * // If you wish to turn OFF background-tracking, call the #stop method. - * BackgroundGeolocation.stop(); + * this.backgroundGeolocation.stop(); * * ``` * @interfaces @@ -310,6 +310,7 @@ export interface BackgroundGeolocationConfig { repo: 'https://github.com/mauron85/cordova-plugin-background-geolocation', platforms: ['iOS', 'Android', 'Windows Phone 8'] }) +@Injectable() export class BackgroundGeolocation { /**
 @@ -321,7 +322,7 @@ export class BackgroundGeolocation { * * @enum {number}
 */ - static LocationProvider: any = { + LocationProvider: any = { ANDROID_DISTANCE_FILTER_PROVIDER: 0, ANDROID_ACTIVITY_PROVIDER: 1 }; @@ -339,7 +340,7 @@ export class BackgroundGeolocation { * * enum {number}
 */ - static Accuracy: any = { + Accuracy: any = { HIGH: 0, MEDIUM: 10, LOW: 100, @@ -355,7 +356,7 @@ export class BackgroundGeolocation { * * @enum {number}
 */ - static Mode: any = { + Mode: any = { BACKGROUND: 0, FOREGROUND: 1 }; @@ -364,13 +365,13 @@ export class BackgroundGeolocation { * Configure the plugin. * * @param options {BackgroundGeolocationConfig} options An object of type Config - * @return {Observable} + * @return {Observable} */ @Cordova({ callbackOrder: 'reverse', observable: true }) - static configure(options: BackgroundGeolocationConfig): Observable { return; } + configure(options: BackgroundGeolocationConfig): Observable { return; } /** * Turn ON the background-geolocation system. @@ -378,14 +379,14 @@ export class BackgroundGeolocation { * @returns {Promise} */ @Cordova() - static start(): Promise { return; } + start(): Promise { return; } /** * Turn OFF background-tracking * @returns {Promise} */ @Cordova() - static stop(): Promise { return; } + stop(): Promise { return; } /** * Inform the native plugin that you're finished, the background-task may be completed @@ -394,7 +395,7 @@ export class BackgroundGeolocation { @Cordova({ platforms: ['iOS', 'Windows Phone'] }) - static finish(): Promise { return; } + finish(): Promise { return; } /** * Force the plugin to enter "moving" or "stationary" state @@ -404,7 +405,7 @@ export class BackgroundGeolocation { @Cordova({ platforms: ['iOS', 'Windows Phone'] }) - static changePace(isMoving: boolean): Promise { return; } + changePace(isMoving: boolean): Promise { return; } /** * Setup configuration @@ -414,7 +415,7 @@ export class BackgroundGeolocation { @Cordova({ callbackOrder: 'reverse' }) - static setConfig(options: BackgroundGeolocationConfig): Promise { return; } + setConfig(options: BackgroundGeolocationConfig): Promise { return; } /** * Returns current stationaryLocation if available. null if not @@ -423,7 +424,7 @@ export class BackgroundGeolocation { @Cordova({ platforms: ['iOS', 'Windows Phone'] }) - static getStationaryLocation(): Promise { return; } + getStationaryLocation(): Promise { return; } /** * Add a stationary-region listener. Whenever the devices enters "stationary-mode", @@ -433,7 +434,7 @@ export class BackgroundGeolocation { @Cordova({ platforms: ['iOS', 'Windows Phone'] }) - static onStationary(): Promise { return; } + onStationary(): Promise { return; } /** * Check if location is enabled on the device @@ -442,19 +443,19 @@ export class BackgroundGeolocation { @Cordova({ platforms: ['Android'] }) - static isLocationEnabled(): Promise { return; } + isLocationEnabled(): Promise { return; } /** * Display app settings to change permissions */ @Cordova({sync: true}) - static showAppSettings(): void { } + showAppSettings(): void { } /** * Display device location settings */ @Cordova({sync: true}) - static showLocationSettings(): void { } + showLocationSettings(): void { } /** * Method can be used to detect user changes in location services settings. @@ -465,7 +466,7 @@ export class BackgroundGeolocation { @Cordova({ platforms: ['Android'] }) - static watchLocationMode(): Promise { return; } + watchLocationMode(): Promise { return; } /** * Stop watching for location mode changes. @@ -474,7 +475,7 @@ export class BackgroundGeolocation { @Cordova({ platforms: ['Android'] }) - static stopWatchingLocationMode(): Promise { return; } + stopWatchingLocationMode(): Promise { return; } /** * Method will return all stored locations. @@ -488,14 +489,14 @@ export class BackgroundGeolocation { @Cordova({ platforms: ['Android'] }) - static getLocations(): Promise { return; } + getLocations(): Promise { return; } /**
 * Method will return locations, which has not been yet posted to server. NOTE: Locations does contain locationId.
 * @returns {Promise} */ @Cordova() - static getValidLocations(): Promise { return; } + getValidLocations(): Promise { return; } /** * Delete stored location by given locationId. @@ -505,7 +506,7 @@ export class BackgroundGeolocation { @Cordova({ platforms: ['Android'] }) - static deleteLocation(locationId: number): Promise { return; } + deleteLocation(locationId: number): Promise { return; } /** * Delete all stored locations. @@ -514,7 +515,7 @@ export class BackgroundGeolocation { @Cordova({ platforms: ['Android'] }) - static deleteAllLocations(): Promise { return; } + deleteAllLocations(): Promise { return; } /** * Normally plugin will handle switching between BACKGROUND and FOREGROUND mode itself. @@ -532,7 +533,7 @@ export class BackgroundGeolocation { @Cordova({ platforms: ['iOS'] }) - static switchMode(modeId: number): Promise { return; } + switchMode(modeId: number): Promise { return; } /**
 * Return all logged events. Useful for plugin debugging. Parameter limit limits number of returned entries.
 @@ -542,6 +543,6 @@ export class BackgroundGeolocation { * @returns {Promise} */ @Cordova() - static getLogEntries(limit: number): Promise { return; } + getLogEntries(limit: number): Promise { return; } } diff --git a/src/plugins/backgroundmode.ts b/src/@ionic-native/plugins/background-mode/index.ts similarity index 54% rename from src/plugins/backgroundmode.ts rename to src/@ionic-native/plugins/background-mode/index.ts index eecea9120..4b28ddca0 100644 --- a/src/plugins/backgroundmode.ts +++ b/src/@ionic-native/plugins/background-mode/index.ts @@ -1,6 +1,8 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; + /** * Configurations items that can be updated. */ @@ -34,20 +36,24 @@ export interface BackgroundModeConfiguration { } /** -* @name Background Mode -* @description -* Cordova plugin to prevent the app from going to sleep while in background. -* Requires Cordova plugin: cordova-plugin-background-mode. For more info about plugin, vist: https://github.com/katzer/cordova-plugin-background-mode -*@usage -* ```typescript -* import { BackgroundMode } from 'ionic-native'; -* -* BackgroundMode.enable(); -* ``` + * @name Background Mode + * @description + * Cordova plugin to prevent the app from going to sleep while in background. + * Requires Cordova plugin: cordova-plugin-background-mode. For more info about plugin, vist: https://github.com/katzer/cordova-plugin-background-mode + *@usage + * ```typescript + * import { BackgroundMode } from '@ionic-native/background-mode'; + * + * constructor(private backgroundMode: BackgroundMode) { } + * + * ... + * + * this.backgroundMode.enable(); + * ``` * * @interfaces * BackgroundModeConfiguration -*/ + */ @Plugin({ pluginName: 'BackgroundMode', plugin: 'cordova-plugin-background-mode', @@ -55,61 +61,62 @@ export interface BackgroundModeConfiguration { repo: 'https://github.com/katzer/cordova-plugin-background-mode', platforms: ['Android', 'iOS', 'Windows Phone 8'] }) +@Injectable() export class BackgroundMode { /** - * Enable the background mode. - * Once called, prevents the app from being paused while in background. - */ + * Enable the background mode. + * Once called, prevents the app from being paused while in background. + */ @Cordova({ sync: true }) - static enable(): void { } + enable(): void { } /** - * Disable the background mode. - * Once the background mode has been disabled, the app will be paused when in background. - */ + * Disable the background mode. + * Once the background mode has been disabled, the app will be paused when in background. + */ @Cordova() - static disable(): Promise { return; } + disable(): Promise { return; } /** - * Checks if background mode is enabled or not. - * @returns {boolean} returns a boolean that indicates if the background mode is enabled. - */ + * Checks if background mode is enabled or not. + * @returns {boolean} returns a boolean that indicates if the background mode is enabled. + */ @Cordova({ sync: true }) - static isEnabled(): boolean { return; } + isEnabled(): boolean { return; } /** - * Can be used to get the information if the background mode is active. - * @returns {boolean} returns a boolean that indicates if the background mode is active. - */ + * Can be used to get the information if the background mode is active. + * @returns {boolean} returns a boolean that indicates if the background mode is active. + */ @Cordova({ sync: true }) - static isActive(): boolean { return; } + isActive(): boolean { return; } /** - * Override the default title, ticker and text. - * Available only for Android platform. - * @param {Configure} options List of option to configure. See table below - */ + * Override the default title, ticker and text. + * Available only for Android platform. + * @param {Configure} options List of option to configure. See table below + */ @Cordova({ platforms: ['Android'] }) - static setDefaults(options?: BackgroundModeConfiguration): Promise { return; } + setDefaults(options?: BackgroundModeConfiguration): Promise { return; } /** - * Modify the displayed information. - * Available only for Android platform. - * @param {Configure} options Any options you want to update. See table below. - */ + * Modify the displayed information. + * Available only for Android platform. + * @param {Configure} options Any options you want to update. See table below. + */ @Cordova({ platforms: ['Android'] }) - static configure(options?: BackgroundModeConfiguration): Promise { return; } + configure(options?: BackgroundModeConfiguration): Promise { return; } /** * Listen for events that the plugin fires. Available events are `enable`, `disable`, `activate`, `deactivate` and `failure`. @@ -121,7 +128,7 @@ export class BackgroundMode { clearFunction: 'un', clearWithArgs: true }) - static on(event: string): Observable { return; } + on(event: string): Observable { return; } /** * Android allows to programmatically move from foreground to background. @@ -130,7 +137,7 @@ export class BackgroundMode { platforms: ['Android'], sync: true }) - static moveToBackground(): void {} + moveToBackground(): void {} /** * Android allows to programmatically move from background to foreground. @@ -139,7 +146,7 @@ export class BackgroundMode { platforms: ['Android'], sync: true }) - static moveToForeground(): void {} + moveToForeground(): void {} /** * Override the back button on Android to go to background instead of closing the app. @@ -148,7 +155,7 @@ export class BackgroundMode { platforms: ['Android'], sync: true }) - static overrideBackButton(): void {} + overrideBackButton(): void {} /** * Exclude the app from the recent task list works on Android 5.0+. @@ -157,7 +164,7 @@ export class BackgroundMode { platforms: ['Android'], sync: true }) - static excludeFromTaskList(): void {} + excludeFromTaskList(): void {} /** * The method works async instead of isActive() or isEnabled(). @@ -165,7 +172,7 @@ export class BackgroundMode { @Cordova({ platforms: ['Android'] }) - static isScreenOff(): Promise { return; } + isScreenOff(): Promise { return; } /** * Turn screen on @@ -174,7 +181,7 @@ export class BackgroundMode { platforms: ['Android'], sync: true }) - static wakeUp(): void {} + wakeUp(): void {} /** * Turn screen on and show app even locked @@ -183,6 +190,6 @@ export class BackgroundMode { platforms: ['Android'], sync: true }) - static unlock(): void {} + unlock(): void {} } diff --git a/src/plugins/backlight.ts b/src/@ionic-native/plugins/backlight/index.ts similarity index 63% rename from src/plugins/backlight.ts rename to src/@ionic-native/plugins/backlight/index.ts index ec1c55746..31f3ccd30 100644 --- a/src/plugins/backlight.ts +++ b/src/@ionic-native/plugins/backlight/index.ts @@ -1,4 +1,6 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; + /** * @beta @@ -8,13 +10,17 @@ import { Plugin, Cordova } from './plugin'; * * @usage * ``` - * import { Backlight } from 'ionic-native'; + * import { Backlight } from '@ionic-native/backlight'; + * + * constructor(private backlight: Backlight) { } + * + * ... * * // Turn backlight on - * Backlight.on().then(() => console.log('backlight on')); + * this.backlight.on().then(() => console.log('backlight on')); * * // Turn backlight off - * Backlight.off().then(() => console.log('backlight off')); + * this.backlight.off().then(() => console.log('backlight off')); * * ``` */ @@ -25,6 +31,7 @@ import { Plugin, Cordova } from './plugin'; repo: 'https://github.com/mebibou/cordova-plugin-backlight', platforms: ['Android'] }) +@Injectable() export class Backlight { /** @@ -32,13 +39,13 @@ export class Backlight { * @return {Promise} Returns a promise that resolves when the backlight is on */ @Cordova() - static on(): Promise { return; } + on(): Promise { return; } /** * This function turns backlight off * @return {Promise} Returns a promise that resolves when the backlight is off */ @Cordova() - static off(): Promise { return; } + off(): Promise { return; } } diff --git a/src/plugins/badge.ts b/src/@ionic-native/plugins/badge/index.ts similarity index 72% rename from src/plugins/badge.ts rename to src/@ionic-native/plugins/badge/index.ts index 675d60486..225046978 100644 --- a/src/plugins/badge.ts +++ b/src/@ionic-native/plugins/badge/index.ts @@ -1,4 +1,6 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; + /** * @name Badge @@ -9,12 +11,15 @@ import { Cordova, Plugin } from './plugin'; * * @usage * ```typescript - * import { Badge } from 'ionic-native'; + * import { Badge } from '@ionic-native/badge'; * + * constructor(private badge: Badge) { } * - * Badge.set(10); - * Badge.increase(1); - * Badge.clear(); + * ... + * + * this.badge.set(10); + * this.badge.increase(1); + * this.badge.clear(); * ``` */ @Plugin({ @@ -24,6 +29,7 @@ import { Cordova, Plugin } from './plugin'; repo: 'https://github.com/katzer/cordova-plugin-badge', platforms: ['Android', 'iOS', 'Browser', 'Windows', 'Amazon FireOS', 'Windows Phone 8'] }) +@Injectable() export class Badge { /** @@ -31,7 +37,7 @@ export class Badge { * @returns {Promise} */ @Cordova() - static clear(): Promise { return; } + clear(): Promise { return; } /** * Set the badge of the app icon. @@ -39,14 +45,14 @@ export class Badge { * @returns {Promise} */ @Cordova() - static set(badgeNumber: number): Promise { return; } + set(badgeNumber: number): Promise { return; } /** * Get the badge of the app icon. * @returns {Promise} */ @Cordova() - static get(): Promise { return; } + get(): Promise { return; } /** * Increase the badge number. @@ -54,7 +60,7 @@ export class Badge { * @returns {Promise} */ @Cordova() - static increase(increaseBy: number): Promise { return; } + increase(increaseBy: number): Promise { return; } /** * Decrease the badge number. @@ -62,20 +68,20 @@ export class Badge { * @returns {Promise} */ @Cordova() - static decrease(decreaseBy: number): Promise { return; } + decrease(decreaseBy: number): Promise { return; } /** * Determine if the app has permission to show badges. * @returns {Promise} */ @Cordova() - static hasPermission(): Promise { return; } + hasPermission(): Promise { return; } /** * Register permission to set badge notifications * @returns {Promise} */ @Cordova() - static registerPermission(): Promise { return; } + registerPermission(): Promise { return; } } diff --git a/src/plugins/barcodescanner.ts b/src/@ionic-native/plugins/barcode-scanner/index.ts similarity index 83% rename from src/plugins/barcodescanner.ts rename to src/@ionic-native/plugins/barcode-scanner/index.ts index caa68153c..13ba7908c 100644 --- a/src/plugins/barcodescanner.ts +++ b/src/@ionic-native/plugins/barcode-scanner/index.ts @@ -1,4 +1,6 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; + export interface BarcodeScannerOptions { @@ -63,10 +65,14 @@ export interface BarcodeScannerOptions { * * @usage * ```typescript - * import { BarcodeScanner } from 'ionic-native'; + * import { BarcodeScanner } from '@ionic-native/barcode-scanner'; + * + * constructor(private barcodeScanner: BarcodeScanner) { } + * + * ... * * - * BarcodeScanner.scan().then((barcodeData) => { + * this.barcodeScanner.scan().then((barcodeData) => { * // Success! Barcode data is here * }, (err) => { * // An error occurred @@ -82,12 +88,15 @@ export interface BarcodeScannerOptions { repo: 'https://github.com/phonegap/phonegap-plugin-barcodescanner', platforms: ['Android', 'iOS', 'Windows Phone 8', 'Windows 10', 'Windows 8', 'BlackBerry 10', 'Browser'] }) +@Injectable() export class BarcodeScanner { - /** - * @private - */ - static Encode: any = { + Encode: { + TEXT_TYPE: string; + EMAIL_TYPE: string; + PHONE_TYPE: string; + SMS_TYPE: string; + } = { TEXT_TYPE: 'TEXT_TYPE', EMAIL_TYPE: 'EMAIL_TYPE', PHONE_TYPE: 'PHONE_TYPE', @@ -102,7 +111,7 @@ export class BarcodeScanner { @Cordova({ callbackOrder: 'reverse' }) - static scan(options?: BarcodeScannerOptions): Promise { return; } + scan(options?: BarcodeScannerOptions): Promise { return; } /** * Encodes data into a barcode. @@ -112,6 +121,6 @@ export class BarcodeScanner { * @returns {Promise} */ @Cordova() - static encode(type: string, data: any): Promise { return; } + encode(type: string, data: any): Promise { return; } } diff --git a/src/plugins/base64togallery.ts b/src/@ionic-native/plugins/base64-to-gallery/index.ts similarity index 72% rename from src/plugins/base64togallery.ts rename to src/@ionic-native/plugins/base64-to-gallery/index.ts index 4038e8402..0e78238a2 100644 --- a/src/plugins/base64togallery.ts +++ b/src/@ionic-native/plugins/base64-to-gallery/index.ts @@ -1,14 +1,20 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; /** * @name Base64 To Gallery * @description This plugin allows you to save base64 data as a png image into the device * @usage * ```typescript - * import { Base64ToGallery } from 'ionic-native'; + * import { Base64ToGallery } from '@ionic-native/base64-to-gallery'; + * + * constructor(private base64ToGallery: Base64ToGallery) { } * * - * Base64ToGallery.base64ToGallery(base64Data, 'img_').then( + * ... + * + * + * this.base64ToGallery.base64ToGallery(base64Data, { prefix: '_img' }).then( * res => console.log('Saved image to gallery ', res), * err => console.log('Error saving image to gallery ', err) * ); @@ -21,6 +27,7 @@ import { Cordova, Plugin } from './plugin'; repo: 'https://github.com/Nexxa/cordova-base64-to-gallery', platforms: ['Android', 'iOS', 'Windows Phone 8'] }) +@Injectable() export class Base64ToGallery { /** @@ -33,7 +40,7 @@ export class Base64ToGallery { successIndex: 2, errorIndex: 3 }) - static base64ToGallery(data: string, options?: {prefix?: string; mediaScanner?: boolean}): Promise { + base64ToGallery(data: string, options?: {prefix?: string; mediaScanner?: boolean}): Promise { return; } diff --git a/src/plugins/batterystatus.ts b/src/@ionic-native/plugins/battery-status/index.ts similarity index 78% rename from src/plugins/batterystatus.ts rename to src/@ionic-native/plugins/battery-status/index.ts index d8d90ced2..72fbf385f 100644 --- a/src/plugins/batterystatus.ts +++ b/src/@ionic-native/plugins/battery-status/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; export interface BatteryStatusResponse { @@ -22,11 +23,15 @@ export interface BatteryStatusResponse { * * @usage * ```typescript - * import { BatteryStatus } from 'ionic-native'; + * import { BatteryStatus } from '@ionic-native/battery-status'; + * + * constructor(private batteryStatus: BatteryStatus) { } + * + * ... * * * // watch change in battery status - * let subscription = BatteryStatus.onChange().subscribe( + * let subscription = this.batteryStatus.onChange().subscribe( * (status: StatusObject) => { * console.log(status.level, status.isPlugged); * } @@ -46,6 +51,7 @@ export interface BatteryStatusResponse { repo: 'https://github.com/apache/cordova-plugin-battery-status', platforms: ['Amazon Fire OS', 'iOS', 'Android', 'BlackBerry 10', 'Windows Phone 7', 'Windows Phone 8', 'Windows', 'Firefox OS', 'Browser'] }) +@Injectable() export class BatteryStatus { /** @@ -56,7 +62,7 @@ export class BatteryStatus { eventObservable: true, event: 'batterystatus' }) - static onChange(): Observable { return; } + onChange(): Observable { return; } /** * Watch when the battery level goes low @@ -66,7 +72,7 @@ export class BatteryStatus { eventObservable: true, event: 'batterylow' }) - static onLow(): Observable { return; } + onLow(): Observable { return; } /** * Watch when the battery level goes to critial @@ -76,6 +82,6 @@ export class BatteryStatus { eventObservable: true, event: 'batterycritical' }) - static onCritical(): Observable { return; } + onCritical(): Observable { return; } } diff --git a/src/plugins/ble.ts b/src/@ionic-native/plugins/ble/index.ts similarity index 93% rename from src/plugins/ble.ts rename to src/@ionic-native/plugins/ble/index.ts index 99882d67b..3a9d45db6 100644 --- a/src/plugins/ble.ts +++ b/src/@ionic-native/plugins/ble/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; /** @@ -20,6 +21,14 @@ import { Observable } from 'rxjs/Observable'; * * @usage * + * ```typescript + * + * import { BLE } from '@ionic-native/ble'; + * + * constructor(private ble: BLE) { } + * + * ``` + * * ## Peripheral Data * * Peripheral Data is passed to the success callback when scanning and connecting. Limited data is passed when scanning. @@ -166,6 +175,7 @@ import { Observable } from 'rxjs/Observable'; repo: 'https://github.com/don/cordova-plugin-ble-central', platforms: ['iOS', 'Android'] }) +@Injectable() export class BLE { /** @@ -184,7 +194,7 @@ export class BLE { @Cordova({ observable: true }) - static scan(services: string[], seconds: number): Observable { return; } + scan(services: string[], seconds: number): Observable { return; } /** * Scan and discover BLE peripherals until `stopScan` is called. @@ -207,7 +217,7 @@ export class BLE { clearFunction: 'stopScan', clearWithArgs: false }) - static startScan(services: string[]): Observable { return; } + startScan(services: string[]): Observable { return; } /** * Scans for BLE devices. This function operates similarly to the `startScan` function, but allows you to specify extra options (like allowing duplicate device reports). @@ -220,7 +230,7 @@ export class BLE { clearFunction: 'stopScan', clearWithArgs: false }) - static startScanWithOptions(services: string[], options: {reportDuplicates?: boolean} | any): Observable { return; } + startScanWithOptions(services: string[], options: {reportDuplicates?: boolean} | any): Observable { return; } /** * Stop a scan started by `startScan`. @@ -237,7 +247,7 @@ export class BLE { * @return returns a Promise. */ @Cordova() - static stopScan(): Promise { return; } + stopScan(): Promise { return; } /** * Connect to a peripheral. @@ -258,7 +268,7 @@ export class BLE { clearFunction: 'disconnect', clearWithArgs: true }) - static connect(deviceId: string): Observable { return; } + connect(deviceId: string): Observable { return; } /** * Disconnect from a peripheral. @@ -272,7 +282,7 @@ export class BLE { * @return Returns a Promise */ @Cordova() - static disconnect(deviceId: string): Promise { return; } + disconnect(deviceId: string): Promise { return; } /** * Read the value of a characteristic. @@ -283,7 +293,7 @@ export class BLE { * @return Returns a Promise */ @Cordova() - static read( + read( deviceId: string, serviceUUID: string, characteristicUUID: string @@ -318,7 +328,7 @@ export class BLE { * @return Returns a Promise */ @Cordova() - static write( + write( deviceId: string, serviceUUID: string, characteristicUUID: string, @@ -335,7 +345,7 @@ export class BLE { * @return Returns a Promise */ @Cordova() - static writeWithoutResponse( + writeWithoutResponse( deviceId: string, serviceUUID: string, characteristicUUID: string, @@ -362,7 +372,7 @@ export class BLE { clearFunction: 'stopNotification', clearWithArgs: true }) - static startNotification( + startNotification( deviceId: string, serviceUUID: string, characteristicUUID: string @@ -377,7 +387,7 @@ export class BLE { * @returns {Promise} */ @Cordova() - static stopNotification( + stopNotification( deviceId: string, serviceUUID: string, characteristicUUID: string @@ -397,7 +407,7 @@ export class BLE { * @returns {Promise} */ @Cordova() - static isConnected(deviceId: string): Promise { return; } + isConnected(deviceId: string): Promise { return; } /** * Report if bluetooth is enabled. @@ -405,7 +415,7 @@ export class BLE { * @returns {Promise} Returns a Promise that resolves if Bluetooth is enabled, and rejects if disabled. */ @Cordova() - static isEnabled(): Promise { return; } + isEnabled(): Promise { return; } /** * Open System Bluetooth settings (Android only). @@ -413,7 +423,7 @@ export class BLE { * @returns {Promise} */ @Cordova() - static showBluetoothSettings(): Promise { return; } + showBluetoothSettings(): Promise { return; } /** * Enable Bluetooth on the device (Android only). @@ -421,7 +431,7 @@ export class BLE { * @returns {Promise} */ @Cordova() - static enable(): Promise { return; } + enable(): Promise { return; } /** * Read the RSSI value on the device connection. diff --git a/src/plugins/bluetoothserial.ts b/src/@ionic-native/plugins/bluetooth-serial/index.ts similarity index 77% rename from src/plugins/bluetoothserial.ts rename to src/@ionic-native/plugins/bluetooth-serial/index.ts index beda36de5..e83385306 100644 --- a/src/plugins/bluetoothserial.ts +++ b/src/@ionic-native/plugins/bluetooth-serial/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; /** @@ -6,14 +7,16 @@ import { Observable } from 'rxjs/Observable'; * @description This plugin enables serial communication over Bluetooth. It was written for communicating between Android or iOS and an Arduino. * @usage * ```typescript - * import { BluetoothSerial } from 'ionic-native'; + * import { BluetoothSerial } from '@ionic-native/bluetooth-serial'; + * + * constructor(private bluetoothSerial: BluetoothSerial) { } * * * // Write a string - * BluetoothSerial.write("hello world").then(success, failure); + * this.bluetoothSerial.write("hello world").then(success, failure); * * // Array of int or bytes - * BluetoothSerial.write([186, 220, 222]).then(success, failure); + * this.bluetoothSerial.write([186, 220, 222]).then(success, failure); * * // Typed Array * var data = new Uint8Array(4); @@ -21,10 +24,10 @@ import { Observable } from 'rxjs/Observable'; * data[1] = 0x42; * data[2] = 0x43; * data[3] = 0x44; - * BluetoothSerial.write(data).then(success, failure); + * this.bluetoothSerial.write(data).then(success, failure); * * // Array Buffer - * BluetoothSerial.write(data.buffer).then(success, failure); + * this.bluetoothSerial.write(data.buffer).then(success, failure); * ``` */ @Plugin({ @@ -34,6 +37,7 @@ import { Observable } from 'rxjs/Observable'; pluginRef: 'bluetoothSerial', platforms: ['Android', 'iOS', 'Windows Phone', 'Browser'] }) +@Injectable() export class BluetoothSerial { /** @@ -46,7 +50,7 @@ export class BluetoothSerial { observable: true, clearFunction: 'disconnect' }) - static connect(macAddress_or_uuid: string): Observable { return; } + connect(macAddress_or_uuid: string): Observable { return; } /** * Connect insecurely to a Bluetooth device @@ -58,14 +62,14 @@ export class BluetoothSerial { observable: true, clearFunction: 'disconnect' }) - static connectInsecure(macAddress: string): Observable { return; } + connectInsecure(macAddress: string): Observable { return; } /** * Disconnect from the connected device * @returns {Promise} */ @Cordova() - static disconnect(): Promise { return; } + disconnect(): Promise { return; } /** * Writes data to the serial port @@ -75,7 +79,7 @@ export class BluetoothSerial { @Cordova({ platforms: ['Android', 'iOS', 'Windows Phone'] }) - static write(data: any): Promise { return; } + write(data: any): Promise { return; } /** * Gets the number of bytes of data available @@ -83,7 +87,7 @@ export class BluetoothSerial { */ @Cordova({ platforms: ['Android', 'iOS', 'Windows Phone'] - }) static available(): Promise { return; } + }) available(): Promise { return; } /** * Reads data from the buffer @@ -92,7 +96,7 @@ export class BluetoothSerial { @Cordova({ platforms: ['Android', 'iOS', 'Windows Phone'] }) - static read(): Promise { return; } + read(): Promise { return; } /** * Reads data from the buffer until it reaches a delimiter @@ -102,7 +106,7 @@ export class BluetoothSerial { @Cordova({ platforms: ['Android', 'iOS', 'Windows Phone'] }) - static readUntil(delimiter: string): Promise { return; } + readUntil(delimiter: string): Promise { return; } /** * Subscribe to be notified when data is received @@ -114,7 +118,7 @@ export class BluetoothSerial { observable: true, clearFunction: 'unsubscribe' }) - static subscribe(delimiter: string): Observable { return; } + subscribe(delimiter: string): Observable { return; } /** * Subscribe to be notified when data is received @@ -125,7 +129,7 @@ export class BluetoothSerial { observable: true, clearFunction: 'unsubscribeRawData' }) - static subscribeRawData(): Observable { return; } + subscribeRawData(): Observable { return; } /** * Clears data in buffer @@ -134,7 +138,7 @@ export class BluetoothSerial { @Cordova({ platforms: ['Android', 'iOS', 'Windows Phone'] }) - static clear(): Promise { return; } + clear(): Promise { return; } /** * Lists bonded devices @@ -143,7 +147,7 @@ export class BluetoothSerial { @Cordova({ platforms: ['Android', 'iOS', 'Windows Phone'] }) - static list(): Promise { return; } + list(): Promise { return; } /** * Reports if bluetooth is enabled @@ -152,7 +156,7 @@ export class BluetoothSerial { @Cordova({ platforms: ['Android', 'iOS', 'Windows Phone'] }) - static isEnabled(): Promise { return; } + isEnabled(): Promise { return; } /** * Reports the connection status @@ -161,7 +165,7 @@ export class BluetoothSerial { @Cordova({ platforms: ['Android', 'iOS', 'Windows Phone'] }) - static isConnected(): Promise { return; } + isConnected(): Promise { return; } /** * Reads the RSSI from the connected peripheral @@ -170,7 +174,7 @@ export class BluetoothSerial { @Cordova({ platforms: ['Android', 'iOS', 'Windows Phone'] }) - static readRSSI(): Promise { return; } + readRSSI(): Promise { return; } /** * Show the Bluetooth settings on the device @@ -179,7 +183,7 @@ export class BluetoothSerial { @Cordova({ platforms: ['Android', 'iOS', 'Windows Phone'] }) - static showBluetoothSettings(): Promise { return; } + showBluetoothSettings(): Promise { return; } /** * Enable Bluetooth on the device @@ -188,7 +192,7 @@ export class BluetoothSerial { @Cordova({ platforms: ['Android', 'iOS', 'Windows Phone'] }) - static enable(): Promise { return; } + enable(): Promise { return; } /** * Discover unpaired devices @@ -197,7 +201,7 @@ export class BluetoothSerial { @Cordova({ platforms: ['Android', 'iOS', 'Windows Phone'] }) - static discoverUnpaired(): Promise { return; } + discoverUnpaired(): Promise { return; } /** * Subscribe to be notified on Bluetooth device discovery. Discovery process must be initiated with the `discoverUnpaired` function. @@ -208,7 +212,7 @@ export class BluetoothSerial { observable: true, clearFunction: 'clearDeviceDiscoveredListener' }) - static setDeviceDiscoveredListener(): Observable { return; } + setDeviceDiscoveredListener(): Observable { return; } /** * Sets the human readable device name that is broadcasted to other devices @@ -218,7 +222,7 @@ export class BluetoothSerial { platforms: ['Android'], sync: true }) - static setName(newName: string): void { } + setName(newName: string): void { } /** * Makes the device discoverable by other devices @@ -228,6 +232,6 @@ export class BluetoothSerial { platforms: ['Android'], sync: true }) - static setDiscoverable(discoverableDuration: number): void { } + setDiscoverable(discoverableDuration: number): void { } } diff --git a/src/plugins/brightness.ts b/src/@ionic-native/plugins/brightness/index.ts similarity index 74% rename from src/plugins/brightness.ts rename to src/@ionic-native/plugins/brightness/index.ts index cc323dc49..29c5eb658 100644 --- a/src/plugins/brightness.ts +++ b/src/@ionic-native/plugins/brightness/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; /** * @name Brightness @@ -9,11 +10,14 @@ import { Cordova, Plugin } from './plugin'; * * @usage * ```typescript - * import { Brightness } from 'ionic-native'; + * import { Brightness } from '@ionic-native/brightness'; * + * constructor(private brightness: Brightness) { } + * + * ... * * let brightnessValue: number = 0.8; - * Brightness.setBrightness(brightnessValue); + * this.brightness.setBrightness(brightnessValue); * ``` * */ @@ -24,6 +28,7 @@ import { Cordova, Plugin } from './plugin'; repo: 'https://github.com/mgcrea/cordova-plugin-brightness', platforms: ['Android', 'iOS'] }) +@Injectable() export class Brightness { /** @@ -33,7 +38,7 @@ export class Brightness { * @returns {Promise} Returns a Promise that resolves if setting brightness was successful. */ @Cordova() - static setBrightness(value: number): Promise { return; } + setBrightness(value: number): Promise { return; } /** * Reads the current brightness of the device display. @@ -42,12 +47,12 @@ export class Brightness { * brightness value of the device display (floating number between 0 and 1). */ @Cordova() - static getBrightness(): Promise { return; } + getBrightness(): Promise { return; } /** * Keeps the screen on. Prevents the device from setting the screen to sleep. */ @Cordova() - static setKeepScreenOn(value: boolean): void { } + setKeepScreenOn(value: boolean): void { } } diff --git a/src/plugins/broadcaster.ts b/src/@ionic-native/plugins/broadcaster/index.ts similarity index 64% rename from src/plugins/broadcaster.ts rename to src/@ionic-native/plugins/broadcaster/index.ts index 8262637ca..4c7424422 100644 --- a/src/plugins/broadcaster.ts +++ b/src/@ionic-native/plugins/broadcaster/index.ts @@ -1,4 +1,5 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; /** @@ -8,13 +9,17 @@ import { Observable } from 'rxjs/Observable'; * * @usage * ``` - * import { Broadcaster } from 'ionic-native'; + * import { Broadcaster } from '@ionic-native/broadcaster'; + * + * constructor(private broadcaster: Broadcaster) { } + * + * ... * * // Listen to events from Native - * Broadcaster.addEventListener('eventName').then((event) => console.log(event)); + * this.broadcaster.addEventListener('eventName').then((event) => console.log(event)); * * // Send event to Native - * Broadcaster.fireNativeEvent('eventName', {}).then(() => console.log('success')); + * this.broadcaster.fireNativeEvent('eventName', {}).then(() => console.log('success')); * * ``` */ @@ -25,6 +30,7 @@ import { Observable } from 'rxjs/Observable'; repo: 'https://github.com/bsorrentino/cordova-broadcaster', platforms: ['Android', 'iOS'] }) +@Injectable() export class Broadcaster { /** @@ -37,7 +43,7 @@ export class Broadcaster { clearFunction: 'removeEventListener', clearWithArgs: true }) - static addEventListener(eventName: string): Observable { return; } + addEventListener(eventName: string): Observable { return; } /** * This function sends data to the native code @@ -46,6 +52,6 @@ export class Broadcaster { * @return {Promise} Returns a promise that resolves when an event is successfully fired */ @Cordova() - static fireNativeEvent(eventName: string, eventData: any): Promise { return; } + fireNativeEvent(eventName: string, eventData: any): Promise { return; } } diff --git a/src/plugins/browser-tab.ts b/src/@ionic-native/plugins/browser-tab/index.ts similarity index 67% rename from src/plugins/browser-tab.ts rename to src/@ionic-native/plugins/browser-tab/index.ts index 382131495..f1620451f 100644 --- a/src/plugins/browser-tab.ts +++ b/src/@ionic-native/plugins/browser-tab/index.ts @@ -1,26 +1,34 @@ -import { Plugin, Cordova } from './plugin'; +import { Plugin, Cordova } from '@ionic-native/core'; +import { Injectable } from '@angular/core'; /** - * @name BrowserTab + * @name Browser Tab * @description * This plugin provides an interface to in-app browser tabs that exist on some mobile platforms, specifically [Custom Tabs](http://developer.android.com/tools/support-library/features.html#custom-tabs) on Android (including the [Chrome Custom Tabs](https://developer.chrome.com/multidevice/android/customtabs) implementation), and [SFSafariViewController](https://developer.apple.com/library/ios/documentation/SafariServices/Reference/SFSafariViewController_Ref/) on iOS. * * @usage * ``` - * import { BrowserTab } from 'ionic-native'; + * import { BrowserTab } from '@ionic-native/browser-tab'; * - * BrowserTab.isAvailable() - * .then((isAvailable: boolean) => { + * constructor(private browserTab: BrowserTab) { * - * if (isAvailable) { + * browserTab.isAvailable() + * .then((isAvailable: boolean) => { * - * BrowserTab.openUrl('https://ionic.io'); + * if (isAvailable) { * - * } else { - * // open url with InAppBrowser instead - * } + * browserTab.open('https://ionic.io'); * - * }); + * } else { + * + * // open URL with InAppBrowser instead or SafariViewController + * + * } + * + * }); + * + * + * } * * ``` */ @@ -31,6 +39,7 @@ import { Plugin, Cordova } from './plugin'; repo: 'https://github.com/google/cordova-plugin-browsertab', platforms: ['Android', 'iOS'] }) +@Injectable() export class BrowserTab { /** @@ -38,7 +47,7 @@ export class BrowserTab { * @return {Promise} Returns a promise that resolves when check is successful and returns true or false */ @Cordova() - static isAvailable(): Promise { return; } + isAvailable(): Promise { return; } /** * Opens the provided URL using a browser tab @@ -46,12 +55,12 @@ export class BrowserTab { * @return {Promise} Returns a promise that resolves when check open was successful */ @Cordova() - static openUrl(url: string): Promise { return; } + openUrl(url: string): Promise { return; } /** * Closes browser tab * @return {Promise} Returns a promise that resolves when close was finished */ @Cordova() - static close(): Promise { return; } + close(): Promise { return; } } diff --git a/src/plugins/calendar.ts b/src/@ionic-native/plugins/calendar/index.ts similarity index 87% rename from src/plugins/calendar.ts rename to src/@ionic-native/plugins/calendar/index.ts index 79c3f144e..79fbb40b7 100644 --- a/src/plugins/calendar.ts +++ b/src/@ionic-native/plugins/calendar/index.ts @@ -1,8 +1,6 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; -/** - * @private - */ export interface CalendarOptions { /** @@ -62,11 +60,12 @@ export interface CalendarOptions { * * @usage * ``` - * import {Calendar} from 'ionic-native'; + * import {Calendar} from '@ionic-native/calendar'; + * + * constructor(private calendar: Calendar) { } * * - * - * Calendar.createCalendar('MyCalendar').then( + * this.calendar.createCalendar('MyCalendar').then( * (msg) => { console.log(msg); }, * (err) => { console.log(err); } * ); @@ -81,6 +80,7 @@ export interface CalendarOptions { repo: 'https://github.com/EddyVerbruggen/Calendar-PhoneGap-Plugin', platforms: ['Android', 'iOS'] }) +@Injectable() export class Calendar { /** @@ -95,42 +95,42 @@ export class Calendar { * @returns {Promise} */ @Cordova() - static hasReadWritePermission(): Promise { return; } + hasReadWritePermission(): Promise { return; } /** * Check if we have read permission * @returns {Promise} */ @Cordova() - static hasReadPermission(): Promise { return; } + hasReadPermission(): Promise { return; } /** * Check if we have write permission * @returns {Promise} */ @Cordova() - static hasWritePermission(): Promise { return; } + hasWritePermission(): Promise { return; } /** * Request write permission * @returns {Promise} */ @Cordova() - static requestWritePermission(): Promise { return; } + requestWritePermission(): Promise { return; } /** * Request read permission * @returns {Promise} */ @Cordova() - static requestReadPermission(): Promise { return; } + requestReadPermission(): Promise { return; } /** * Requests read/write permissions * @returns {Promise} */ @Cordova() - static requestReadWritePermission(): Promise { return; } + requestReadWritePermission(): Promise { return; } /** * Create a calendar. (iOS only) @@ -139,7 +139,7 @@ export class Calendar { * @returns {Promise} Returns a Promise */ @Cordova() - static createCalendar(nameOrOptions: string | any): Promise { return; } + createCalendar(nameOrOptions: string | any): Promise { return; } /** * Delete a calendar. (iOS only) @@ -147,7 +147,7 @@ export class Calendar { * @returns {Promise} Returns a Promise */ @Cordova() - static deleteCalendar(name: string): Promise { return; } + deleteCalendar(name: string): Promise { return; } /** * Returns the default calendar options. @@ -157,7 +157,7 @@ export class Calendar { @Cordova({ sync: true }) - static getCalendarOptions(): CalendarOptions { return; } + getCalendarOptions(): CalendarOptions { return; } /** * Silently create an event. @@ -169,7 +169,7 @@ export class Calendar { * @returns {Promise} Returns a Promise */ @Cordova() - static createEvent( + createEvent( title?: string, location?: string, notes?: string, @@ -189,7 +189,7 @@ export class Calendar { * @returns {Promise} Returns a Promise */ @Cordova() - static createEventWithOptions( + createEventWithOptions( title?: string, location?: string, notes?: string, @@ -209,7 +209,7 @@ export class Calendar { * @returns {Promise} Returns a Promise */ @Cordova() - static createEventInteractively( + createEventInteractively( title?: string, location?: string, notes?: string, @@ -229,7 +229,7 @@ export class Calendar { * @returns {Promise} */ @Cordova() - static createEventInteractivelyWithOptions( + createEventInteractivelyWithOptions( title?: string, location?: string, notes?: string, @@ -238,17 +238,6 @@ export class Calendar { options?: CalendarOptions ): Promise { return; } - // deprecated - // @Cordova() - // static createEventInNamedCalendar( - // title?: string, - // location?: string, - // notes?: string, - // startDate?: Date, - // endDate?: Date, - // calendarName?: string - // ) {} - /** * Find an event. * @@ -260,7 +249,7 @@ export class Calendar { * @returns {Promise} */ @Cordova() - static findEvent( + findEvent( title?: string, location?: string, notes?: string, @@ -279,7 +268,7 @@ export class Calendar { * @returns {Promise} Returns a Promise that resolves with the event, or rejects with an error. */ @Cordova() - static findEventWithOptions( + findEventWithOptions( title?: string, location?: string, notes?: string, @@ -298,14 +287,14 @@ export class Calendar { @Cordova({ platforms: ['Android'] }) - static listEventsInRange(startDate: Date, endDate: Date): Promise { return; } + listEventsInRange(startDate: Date, endDate: Date): Promise { return; } /** * Get a list of all calendars. * @returns {Promise} A Promise that resolves with the list of calendars, or rejects with an error. */ @Cordova() - static listCalendars(): Promise { return; } + listCalendars(): Promise { return; } /** * Get a list of all future events in the specified calendar. (iOS only) @@ -314,7 +303,7 @@ export class Calendar { @Cordova({ platforms: ['iOS'] }) - static findAllEventsInNamedCalendar(calendarName: string): Promise { return; } + findAllEventsInNamedCalendar(calendarName: string): Promise { return; } /** * Modify an event. (iOS only) @@ -334,7 +323,7 @@ export class Calendar { @Cordova({ platforms: ['iOS'] }) - static modifyEvent( + modifyEvent( title?: string, location?: string, notes?: string, @@ -367,7 +356,7 @@ export class Calendar { @Cordova({ platforms: ['iOS'] }) - static modifyEventWithOptions( + modifyEventWithOptions( title?: string, location?: string, notes?: string, @@ -393,7 +382,7 @@ export class Calendar { * @return Returns a Promise */ @Cordova() - static deleteEvent( + deleteEvent( title?: string, location?: string, notes?: string, @@ -415,7 +404,7 @@ export class Calendar { @Cordova({ platforms: ['iOS'] }) - static deleteEventFromNamedCalendar( + deleteEventFromNamedCalendar( title?: string, location?: string, notes?: string, @@ -430,6 +419,6 @@ export class Calendar { * @return {Promise} Promise returns a promise */ @Cordova() - static openCalendar(date: Date): Promise { return; } + openCalendar(date: Date): Promise { return; } } diff --git a/src/plugins/call-number.ts b/src/@ionic-native/plugins/call-number/index.ts similarity index 66% rename from src/plugins/call-number.ts rename to src/@ionic-native/plugins/call-number/index.ts index b64e5a18b..ff649600d 100644 --- a/src/plugins/call-number.ts +++ b/src/@ionic-native/plugins/call-number/index.ts @@ -1,15 +1,20 @@ -import { Plugin, Cordova } from './plugin'; - +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; /** - * @name CallNumber + * @name Call Number * @description * Call a number directly from your Cordova/Ionic application. * * @usage * ``` - * import {CallNumber} from 'ionic-native'; + * import {CallNumber} from '@ionic-native/call-number'; * - * CallNumber.callNumber(18001010101, true) + * constructor(private callNumber: CallNumber) { } + * + * ... + * + * + * this.callNumber.callNumber(18001010101, true) * .then(() => console.log('Launched dialer!')) * .catch(() => console.log('Error launching dialer')); * @@ -22,6 +27,7 @@ import { Plugin, Cordova } from './plugin'; repo: 'https://github.com/Rohfosho/CordovaCallNumberPlugin', platforms: ['iOS', 'Android'] }) +@Injectable() export class CallNumber { /** @@ -33,7 +39,7 @@ export class CallNumber { @Cordova({ callbackOrder: 'reverse' }) - static callNumber(numberToCall: string, bypassAppChooser: boolean): Promise { + callNumber(numberToCall: string, bypassAppChooser: boolean): Promise { return; } diff --git a/src/plugins/camera-preview.ts b/src/@ionic-native/plugins/camera-preview/index.ts similarity index 62% rename from src/plugins/camera-preview.ts rename to src/@ionic-native/plugins/camera-preview/index.ts index 3b3746114..2b4575b51 100644 --- a/src/plugins/camera-preview.ts +++ b/src/@ionic-native/plugins/camera-preview/index.ts @@ -1,5 +1,5 @@ -import { Cordova, Plugin } from './plugin'; - +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; export interface CameraPreviewDimensions { /** The width of the camera preview, default to window.screen.width */ @@ -38,7 +38,7 @@ export interface CameraPreviewOptions { alpha?: number; } -export interface PictureOptions { +export interface CameraPreviewPictureOptions { /** The width in pixels, default 0 */ width?: number; /** The height in pixels, default 0 */ @@ -49,18 +49,22 @@ export interface PictureOptions { /** * @beta - * @name CameraPreview + * @name Camera Preview * @description * Showing camera preview in HTML - * + * * Requires Cordova plugin: `https://github.com/cordova-plugin-camera-preview/cordova-plugin-camera-preview.git`. For more info, please see the [Cordova Camera Preview docs](https://github.com/cordova-plugin-camera-preview/cordova-plugin-camera-preview). * * @usage * ```typescript - * import { CameraPreview, PictureOptions, CameraPreviewOptions, CameraPreviewDimensions, } from 'ionic-native'; + * import { CameraPreview, PictureOptions, CameraPreviewOptions, CameraPreviewDimensions } from 'ionic-native'; + * + * constructor(private cameraPreview: CameraPreview) { } + * + * ... * * // camera options (Size and location). In the following example, the preview uses the rear camera and display the preview in the back of the webview - * public cameraPreviewOpts: CameraPreviewOptions = { + * const cameraPreviewOpts: CameraPreviewOptions = { * x: 0, * y: 0, * width: window.screen.width, @@ -73,7 +77,7 @@ export interface PictureOptions { * }; * * // start camera - * CameraPreview.startCamera(this.cameraPreviewOpts).then( + * this.cameraPreview.startCamera(cameraPreviewOpts).then( * (res) => { * console.log(res) * }, @@ -81,37 +85,43 @@ export interface PictureOptions { * console.log(err) * }); * - * + * // Set the handler to run every time we take a picture + * this.cameraPreview.setOnPictureTakenHandler().subscribe((result) => { + * console.log(result); + * // do something with the result + * }); + * + * * // picture options - * public pictureOpts: PictureOptions = { + * const pictureOpts: PictureOptions = { * width: 1280, * height: 1280, * quality: 85 * } * * // take a picture - * CameraPreview.takePicture(this.pictureOpts).then((imageData) => { + * this.cameraPreview.takePicture(this.pictureOpts).then((imageData) => { * this.picture = 'data:image/jpeg;base64,' + imageData; - * }, (err) => { + * }, (err) => { * console.log(err); * this.picture = 'assets/img/test.jpg'; * }); * - * + * * // Switch camera - * CameraPreview.switchCamera(); + * this.cameraPreview.switchCamera(); * * // set color effect to negative - * CameraPreview.setColorEffect('negative'); + * this.cameraPreview.setColorEffect('negative'); * * // Stop the camera preview - * CameraPreview.stopCamera(); + * this.cameraPreview.stopCamera(); * * ``` * * @interfaces * CameraPreviewOptions - * PictureOptions + * CameraPreviewPictureOptions * CameraPreviewDimensions */ @Plugin({ @@ -121,108 +131,117 @@ export interface PictureOptions { repo: 'https://github.com/cordova-plugin-camera-preview/cordova-plugin-camera-preview', platforms: ['Android', 'iOS'] }) +@Injectable() export class CameraPreview { /** - * Starts the camera preview instance. (iOS & Android) + * Starts the camera preview instance. * @param {CameraPreviewOptions} options + * @return {Promise} */ @Cordova({ successIndex: 1, errorIndex: 2 }) - static startCamera(options: CameraPreviewOptions): Promise { return; } + startCamera(options: CameraPreviewOptions): Promise { return; } /** * Stops the camera preview instance. (iOS & Android) + * @return {Promise} */ @Cordova({ successIndex: 0, errorIndex: 1 }) - static stopCamera(): Promise { return; } + stopCamera(): Promise { return; } /** - * Switch from the rear camera and front camera, if available. (iOS & Android) + * Switch from the rear camera and front camera, if available. + * @return {Promise} */ @Cordova({ successIndex: 0, errorIndex: 1 }) - static switchCamera(): Promise { return; } + switchCamera(): Promise { return; } /** - * Hide the camera preview box. (iOS & Android) + * Hide the camera preview box. + * @return {Promise} */ @Cordova({ successIndex: 0, errorIndex: 1 }) - static hide(): Promise { return; } + hide(): Promise { return; } /** - * Show the camera preview box. (iOS & Android) + * Show the camera preview box. + * @return {Promise} */ @Cordova({ successIndex: 0, errorIndex: 1 }) - static show(): Promise { return; } + show(): Promise { return; } /** - * Take the picture (base64), the parameter size is optional (iOS & Android) - * @param {PictureOptions} optional - size and quality of the picture to take + * Take the picture (base64) + * @param options {CameraPreviewPictureOptions} optional - size and quality of the picture to take + * @return {Promise} */ @Cordova({ successIndex: 1, errorIndex: 2 }) - static takePicture(opts?: PictureOptions): Promise { return; } + takePicture(options?: CameraPreviewPictureOptions): Promise { return; } /** - * - * Set camera color effect. (iOS partial & Android) + * + * Set camera color effect. * @static * @param {string} effect name : 'none' (iOS & Android), 'aqua' (Android), 'blackboard' (Android), 'mono' (iOS & Android), 'negative' (iOS & Android), 'posterize' (iOS & Android), 'sepia' (iOS & Android), 'solarize' (Android) or 'whiteboard' (Android) - * - * @memberOf CameraPreview + * @return {Promise} */ @Cordova({ successIndex: 1, errorIndex: 2 }) - static setColorEffect(effect: string): Promise { return; } - + setColorEffect(effect: string): Promise { return; } /** * Set the zoom (Android) - * @param Zoom value (integer) + * @param zoom {number} Zoom value + * @return {Promise} */ @Cordova({ successIndex: 1, errorIndex: 2 }) - static setZoom(zoom?: number): Promise { return; } + setZoom(zoom?: number): Promise { return; } /** - * Set the preview Size (Android) - * @param dimensions + * Set the preview Size + * @param dimensions {CameraPreviewDimensions} + * @return {Promise} */ @Cordova({ successIndex: 1, - errorIndex: 2 + errorIndex: 2, + platforms: ['Android'] }) - static setPreviewSize(dimensions?: CameraPreviewDimensions): Promise { return; } - + setPreviewSize(dimensions?: CameraPreviewDimensions): Promise { return; } /** - * Set the flashmode (iOS partial & Android) - * @param flashMode 'off' (iOS & Android), 'on' (iOS & Android), 'auto' (iOS & Android), 'torch' (Android) + * Set the flashmode + * @param flashMode {string} 'off' (iOS & Android), 'on' (iOS & Android), 'auto' (iOS & Android), 'torch' (Android) + * @return {Promise} */ @Cordova({ successIndex: 1, errorIndex: 2 }) - static setFlashMode(flashMode?: string): Promise { return; } + setFlashMode(flashMode?: string): Promise { return; } + } diff --git a/src/plugins/camera.ts b/src/@ionic-native/plugins/camera/index.ts similarity index 86% rename from src/plugins/camera.ts rename to src/@ionic-native/plugins/camera/index.ts index 24526cdea..4a128465b 100644 --- a/src/plugins/camera.ts +++ b/src/@ionic-native/plugins/camera/index.ts @@ -1,5 +1,5 @@ -import { Cordova, Plugin } from './plugin'; - +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; export interface CameraOptions { /** Picture quality in range 0-100. Default is 50 */ @@ -94,10 +94,21 @@ export interface CameraPopoverOptions { * * @usage * ```typescript - * import { Camera } from 'ionic-native'; + * import { Camera, CameraOptions } from '@ionic-native/camera'; + * + * constructor(private camera: Camera) { } + * + * ... * * - * Camera.getPicture(options).then((imageData) => { + * constant options: CameraOptions = { + * quality: 100, + * destinationType: this.camera.DestinationType.DATA_URL, + * enodingType: this.camera.EncodingType.JPEG, + * mediaType: this.camera.MediaType.PICTURE + * } + * + * this.camera.getPicture(options).then((imageData) => { * // imageData is either a base64 encoded string or a file URI * // If it's base64: * let base64Image = 'data:image/jpeg;base64,' + imageData; @@ -109,6 +120,7 @@ export interface CameraPopoverOptions { * CameraOptions * CameraPopoverOptions */ +@Injectable() @Plugin({ pluginName: 'Camera', plugin: 'cordova-plugin-camera', @@ -119,10 +131,9 @@ export interface CameraPopoverOptions { export class Camera { /** - * @private - * @enum {number} + * Constant for possible destination types */ - static DestinationType = { + DestinationType = { /** Return base64 encoded string. DATA_URL can be very memory intensive and cause app crashes or out of memory errors. Use FILE_URI or NATIVE_URI if possible */ DATA_URL: 0, /** Return file uri (content://media/external/images/media/2 for Android) */ @@ -132,20 +143,19 @@ export class Camera { }; /** - * @private - * @enum {number} + * Convenience constant */ - static EncodingType = { + EncodingType = { /** Return JPEG encoded image */ JPEG: 0, /** Return PNG encoded image */ PNG: 1 }; + /** - * @private - * @enum {number} + * Convenience constant */ - static MediaType = { + MediaType = { /** Allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType */ PICTURE: 0, /** Allow selection of video only, ONLY RETURNS URL */ @@ -154,11 +164,11 @@ export class Camera { ALLMEDIA: 2 }; + /** - * @private - * @enum {number} + * Convenience constant */ - static PictureSourceType = { + PictureSourceType = { /** Choose image from picture library (same as SAVEDPHOTOALBUM for Android) */ PHOTOLIBRARY: 0, /** Take picture from camera */ @@ -167,12 +177,11 @@ export class Camera { SAVEDPHOTOALBUM: 2 }; + /** - * @private - * Matches iOS UIPopoverArrowDirection constants to specify arrow location on popover. - * @enum {number} + * Convenience constant */ - static PopoverArrowDirection = { + PopoverArrowDirection = { ARROW_UP: 1, ARROW_DOWN: 2, ARROW_LEFT: 4, @@ -181,10 +190,9 @@ export class Camera { }; /** - * @private - * @enum {number} + * Convenience constant */ - static Direction = { + Direction = { /** Use the back-facing camera */ BACK: 0, /** Use the front-facing camera */ @@ -199,7 +207,7 @@ export class Camera { @Cordova({ callbackOrder: 'reverse' }) - static getPicture(options?: CameraOptions): Promise { return; } + getPicture(options?: CameraOptions): Promise { return; } /** * Remove intermediate image files that are kept in temporary storage after calling camera.getPicture. @@ -209,6 +217,6 @@ export class Camera { @Cordova({ platforms: ['iOS'] }) - static cleanup(): Promise { return; }; + cleanup(): Promise { return; }; } diff --git a/src/plugins/card-io.ts b/src/@ionic-native/plugins/card-io/index.ts similarity index 89% rename from src/plugins/card-io.ts rename to src/@ionic-native/plugins/card-io/index.ts index e0a8c824c..2b004b34b 100644 --- a/src/plugins/card-io.ts +++ b/src/@ionic-native/plugins/card-io/index.ts @@ -1,5 +1,5 @@ -import { Cordova, Plugin } from './plugin'; - +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; export interface CardIOOptions { @@ -130,14 +130,18 @@ export interface CardIOResponse { } /** - * @name CardIO + * @name Card IO * @description * @usage * ``` - * import { CardIO } from 'ionic-native'; + * import { CardIO } from '@ionic-native/card-io'; + * + * constructor(private cardIO: CardIO) { } + * + * ... * * - * CardIO.canScan() + * this.cardIO.canScan() * .then( * (res: boolean) => { * if(res){ @@ -162,6 +166,7 @@ export interface CardIOResponse { repo: 'https://github.com/card-io/card.io-Cordova-Plugin', platforms: ['iOS', 'Android'] }) +@Injectable() export class CardIO { /** @@ -171,7 +176,7 @@ export class CardIO { * @returns {Promise} */ @Cordova() - static canScan(): Promise { return; } + canScan(): Promise { return; } /** * Scan a credit card with card.io. @@ -179,13 +184,13 @@ export class CardIO { * @returns {Promise} */ @Cordova() - static scan(options?: CardIOOptions): Promise { return; } + scan(options?: CardIOOptions): Promise { return; } /** * Retrieve the version of the card.io library. Useful when contacting support. * @returns {Promise} */ @Cordova() - static version(): Promise { return; } + version(): Promise { return; } } diff --git a/src/plugins/clipboard.ts b/src/@ionic-native/plugins/clipboard/index.ts similarity index 72% rename from src/plugins/clipboard.ts rename to src/@ionic-native/plugins/clipboard/index.ts index f18c50fc8..577c541c8 100644 --- a/src/plugins/clipboard.ts +++ b/src/@ionic-native/plugins/clipboard/index.ts @@ -1,5 +1,5 @@ -import { Cordova, Plugin } from './plugin'; - +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; /** * @name Clipboard * @description @@ -10,20 +10,23 @@ import { Cordova, Plugin } from './plugin'; * * @usage * ```typescript - * import { Clipboard } from 'ionic-native'; + * import { Clipboard } from '@ionic-native/clipboard'; + * + * constructor(private clipboard: Clipboard) { } + * + * ... * * - * Clipboard.copy('Hello world'); + * this.clipboard.copy('Hello world'); * - * Clipboard.paste().then( + * this.clipboard.paste().then( * (resolve: string) => { - * alert(resolve); + * alert(resolve); * }, * (reject: string) => { - * alert('Error: ' + reject); + * alert('Error: ' + reject); * } - * ); - * ); + * ); * ``` */ @Plugin({ @@ -33,6 +36,7 @@ import { Cordova, Plugin } from './plugin'; repo: 'https://github.com/VersoSolutions/CordovaClipboard', platforms: ['Amazon Fire OS', 'iOS', 'Android', 'BlackBerry 10', 'Windows Phone 7', 'Windows Phone 8', 'Windows', 'Firefox OS', 'Browser'] }) +@Injectable() export class Clipboard { /** @@ -41,13 +45,13 @@ export class Clipboard { * @returns {Promise} Returns a promise after the text has been copied */ @Cordova() - static copy(text: string): Promise { return; } + copy(text: string): Promise { return; } /** * Pastes the text stored in clipboard * @returns {Promise} Returns a promise after the text has been pasted */ @Cordova() - static paste(): Promise { return; } + paste(): Promise { return; } } diff --git a/src/plugins/code-push.ts b/src/@ionic-native/plugins/code-push/index.ts similarity index 96% rename from src/plugins/code-push.ts rename to src/@ionic-native/plugins/code-push/index.ts index 7f4cafdd0..c0d32da99 100644 --- a/src/plugins/code-push.ts +++ b/src/@ionic-native/plugins/code-push/index.ts @@ -1,6 +1,6 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; - namespace Http { export const enum Verb { GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH @@ -396,7 +396,7 @@ export interface DownloadProgress { } /** - * @name CodePush + * @name Code Push * @description * CodePush plugin for Cordova by Microsoft that supports iOS and Android. * @@ -404,14 +404,18 @@ export interface DownloadProgress { * * @usage * ```typescript - * import { CodePush } from 'ionic-native'; + * import { CodePush } from '@ionic-native/code-push'; + * + * constructor(private codePush: CodePush) { } + * + * ... * * // note - mostly error & completed methods of observable will not fire * // as syncStatus will contain the current state of the update - * CodePush.sync().subscribe((syncStatus) => console.log(syncStatus)); + * this.codePush.sync().subscribe((syncStatus) => console.log(syncStatus)); * * const downloadProgress = (progress) => { console.log(`Downloaded ${progress.receivedBytes} of ${progress.totalBytes}`); } - * CodePush.sync({}, downloadProgress).subscribe((syncStatus) => console.log(syncStatus)); + * this.codePush.sync({}, downloadProgress).subscribe((syncStatus) => console.log(syncStatus)); * * ``` */ @@ -422,6 +426,7 @@ export interface DownloadProgress { repo: 'https://github.com/Microsoft/cordova-plugin-code-push', platforms: ['Android', 'iOS'] }) +@Injectable() export class CodePush { /** @@ -432,7 +437,7 @@ export class CodePush { * @returns {Promise} */ @Cordova() - static getCurrentPackage(): Promise { + getCurrentPackage(): Promise { return; } @@ -442,7 +447,7 @@ export class CodePush { * @returns {Promise} */ @Cordova() - static getPendingPackage(): Promise { + getPendingPackage(): Promise { return; } @@ -459,7 +464,7 @@ export class CodePush { @Cordova({ callbackOrder: 'reverse' }) - static checkForUpdate(deploymentKey?: string): Promise { + checkForUpdate(deploymentKey?: string): Promise { return; } @@ -473,7 +478,7 @@ export class CodePush { * @returns {Promise} */ @Cordova() - static notifyApplicationReady(): Promise { + notifyApplicationReady(): Promise { return; } @@ -483,7 +488,7 @@ export class CodePush { * @returns {Promise} */ @Cordova() - static restartApplication(): Promise { + restartApplication(): Promise { return; } @@ -513,7 +518,7 @@ export class CodePush { successIndex: 0, errorIndex: 3 // we don't need this, so we set it to a value higher than # of args }) - static sync(syncOptions?: SyncOptions, downloadProgress?: SuccessCallback): Observable { + sync(syncOptions?: SyncOptions, downloadProgress?: SuccessCallback): Observable { return; } diff --git a/src/plugins/contacts.ts b/src/@ionic-native/plugins/contacts/index.ts similarity index 94% rename from src/plugins/contacts.ts rename to src/@ionic-native/plugins/contacts/index.ts index 30c4a91db..eace0af62 100644 --- a/src/plugins/contacts.ts +++ b/src/@ionic-native/plugins/contacts/index.ts @@ -1,13 +1,11 @@ -import { CordovaInstance, InstanceProperty, Plugin, getPromise } from './plugin'; +import { Injectable } from '@angular/core'; +import { CordovaInstance, InstanceProperty, Plugin, getPromise } from '@ionic-native/core'; declare var window: any, navigator: any; export type ContactFieldType = '*' | 'addresses' | 'birthday' | 'categories' | 'country' | 'department' | 'displayName' | 'emails' | 'familyName' | 'formatted' | 'givenName' | 'honorificPrefix' | 'honorificSuffix' | 'id' | 'ims' | 'locality' | 'middleName' | 'name' | 'nickname' | 'note' | 'organizations' | 'phoneNumbers' | 'photos' | 'postalCode' | 'region' | 'streetAddress' | 'title' | 'urls'; -/** - * @private - */ export interface IContactProperties { /** A globally unique identifier. */ @@ -54,7 +52,7 @@ export interface IContactProperties { } /** - * @private + * @hidden */ export class Contact implements IContactProperties { private _objectInstance: any; @@ -100,7 +98,7 @@ export class Contact implements IContactProperties { } /** - * @private + * @hidden */ export interface IContactError { /** Error code */ @@ -110,7 +108,7 @@ export interface IContactError { } /** - * @private + * @hidden */ export declare var ContactError: { new (code: number): IContactError; @@ -139,7 +137,7 @@ export interface IContactName { } /** - * @private + * @hidden */ export class ContactName implements IContactName { constructor(public formatted?: string, @@ -160,7 +158,7 @@ export interface IContactField { } /** - * @private + * @hidden */ export class ContactField implements IContactField { constructor(public type?: string, @@ -188,7 +186,7 @@ export interface IContactAddress { } /** - * @private + * @hidden */ export class ContactAddress implements IContactAddress { constructor(public pref?: boolean, @@ -215,7 +213,7 @@ export interface IContactOrganization { } /** - * @private + * @hidden */ export class ContactOrganization implements IContactOrganization { constructor( @@ -242,7 +240,7 @@ export interface IContactFindOptions { } /** - * @private + * @hidden */ export class ContactFindOptions implements IContactFindOptions { constructor(public filter?: string, @@ -259,10 +257,11 @@ export class ContactFindOptions implements IContactFindOptions { * @usage * * ```typescript - * import { Contacts, Contact, ContactField, ContactName } from 'ionic-native'; + * import { Contacts, Contact, ContactField, ContactName } from '@ionic-native/contacts'; * + * constructor(private contacts: Contacts) { } * - * let contact: Contact = Contacts.create(); + * let contact: Contact = this.contacts.create(); * * contact.name = new ContactName(null, 'Smith', 'John'); * contact.phoneNumbers = [new ContactField('mobile', '6471234567')]; @@ -272,6 +271,8 @@ export class ContactFindOptions implements IContactFindOptions { * ); * * ``` + * @classes + * Contact * @interfaces * IContactProperties * IContactError @@ -287,13 +288,14 @@ export class ContactFindOptions implements IContactFindOptions { pluginRef: 'navigator.contacts', repo: 'https://github.com/apache/cordova-plugin-contacts' }) +@Injectable() export class Contacts { /** * Create a single contact. * @returns {Contact} Returns a Contact object */ - static create(): Contact { + create(): Contact { return new Contact(); } @@ -303,7 +305,7 @@ export class Contacts { * @param options {IContactFindOptions} Optional options for the query * @returns {Promise} Returns a Promise that resolves with the search results (an array of Contact objects) */ - static find(fields: ContactFieldType[], options?: IContactFindOptions): Promise { + find(fields: ContactFieldType[], options?: IContactFindOptions): Promise { return getPromise((resolve, reject) => { navigator.contacts.find(fields, (contacts) => { resolve(contacts.map(processContact)); @@ -315,7 +317,7 @@ export class Contacts { * Select a single Contact. * @returns {Promise} Returns a Promise that resolves with the selected Contact */ - static pickContact(): Promise { + pickContact(): Promise { return getPromise((resolve, reject) => { navigator.contacts.pickContact((contact) => resolve(processContact(contact)), reject); }); @@ -324,7 +326,7 @@ export class Contacts { } /** - * @private + * @hidden */ function processContact(contact) { let newContact = new Contact(); diff --git a/src/plugins/couchbase-lite.ts b/src/@ionic-native/plugins/couchbase-lite/index.ts similarity index 60% rename from src/plugins/couchbase-lite.ts rename to src/@ionic-native/plugins/couchbase-lite/index.ts index 39d987344..dfa14d1d8 100644 --- a/src/plugins/couchbase-lite.ts +++ b/src/@ionic-native/plugins/couchbase-lite/index.ts @@ -1,4 +1,6 @@ -import { Plugin, Cordova } from './plugin'; +import { Plugin, Cordova } from '@ionic-native/core'; +import { Injectable } from '@angular/core'; + /** * @name Couchbase Lite @@ -7,11 +9,15 @@ import { Plugin, Cordova } from './plugin'; * * @usage * ``` - * import { CouchbaseLite } from 'ionic-native'; + * import { CouchbaseLite } from '@ionic-native/couchbase-lite'; * - * CouchbaseLite.getURL() - * .then((url: any) => console.log(url)) - * .catch((error: any) => console.log(error)); + * constructor(private couchbase: CouchbaseLite) { + * + * couchbase.getURL() + * .then(url => console.log(url)) + * .catch(error => console.error(error)); + * + * } * * ``` */ @@ -21,6 +27,7 @@ import { Plugin, Cordova } from './plugin'; pluginRef: 'cblite', repo: 'https://github.com/couchbaselabs/Couchbase-Lite-PhoneGap-Plugin', }) +@Injectable() export class CouchbaseLite { /** @@ -30,6 +37,6 @@ export class CouchbaseLite { @Cordova({ callbackStyle: 'node' }) - static getURL(): Promise { return; } + getURL(): Promise { return; } } diff --git a/src/plugins/crop.ts b/src/@ionic-native/plugins/crop/index.ts similarity index 65% rename from src/plugins/crop.ts rename to src/@ionic-native/plugins/crop/index.ts index 0a73f811a..abe9f91e0 100644 --- a/src/plugins/crop.ts +++ b/src/@ionic-native/plugins/crop/index.ts @@ -1,15 +1,18 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; /** * @name Crop * @description Crops images * @usage * ``` - * import {Crop} from 'ionic-native'; + * import {Crop} from '@ionic-native/crop'; + * + * constructor(private crop: Crop) { } * * ... * - * Crop.crop('path/to/image.jpg', {quality: 75}) + * this.crop.crop('path/to/image.jpg', {quality: 75}) * .then( * newImage => console.log("new image path is: " + newImage), * error => console.error("Error cropping image", error) @@ -22,6 +25,7 @@ import { Cordova, Plugin } from './plugin'; pluginRef: 'plugins', repo: 'https://github.com/jeduan/cordova-plugin-crop' }) +@Injectable() export class Crop { /** @@ -33,6 +37,6 @@ export class Crop { @Cordova({ callbackOrder: 'reverse' }) - static crop(pathToImage: string, options?: {quality: number}): Promise { return; } + crop(pathToImage: string, options?: {quality: number}): Promise { return; } } diff --git a/src/plugins/datepicker.ts b/src/@ionic-native/plugins/date-picker/index.ts similarity index 88% rename from src/plugins/datepicker.ts rename to src/@ionic-native/plugins/date-picker/index.ts index 5fbd2baa5..f482cffe1 100644 --- a/src/plugins/datepicker.ts +++ b/src/@ionic-native/plugins/date-picker/index.ts @@ -1,4 +1,5 @@ -import {Cordova, Plugin} from './plugin'; +import { Injectable } from '@angular/core'; +import {Cordova, Plugin} from '@ionic-native/core'; export interface DatePickerOptions { /** @@ -125,12 +126,18 @@ export interface DatePickerOptions { * * @usage * ```typescript - * import { DatePicker } from 'ionic-native'; + * import { DatePicker } from '@ionic-native/date-picker'; + * + * constructor(private datePicker: DatePicker) { } * * - * DatePicker.show({ + * ... + * + * + * this.datePicker.show({ * date: new Date(), - * mode: 'date' + * mode: 'date', + * androidTheme: this.datePicker.ANDROID_THEMES.THEME_HOLO_DARK * }).then( * date => console.log('Got date: ', date), * err => console.log('Error occurred while getting date: ', err) @@ -146,12 +153,13 @@ export interface DatePickerOptions { repo: 'https://github.com/VitaliiBlagodir/cordova-plugin-datepicker', platforms: ['Android', 'iOS', 'Windows'] }) +@Injectable() export class DatePicker { /** - * @private + * @hidden */ - static ANDROID_THEMES = { + ANDROID_THEMES = { THEME_TRADITIONAL: 1, THEME_HOLO_DARK: 2, THEME_HOLO_LIGHT: 3, @@ -165,7 +173,7 @@ export class DatePicker { * @returns {Promise} Returns a promise that resolves with the picked date and/or time, or rejects with an error. */ @Cordova() - static show(options: DatePickerOptions): Promise { + show(options: DatePickerOptions): Promise { return; } diff --git a/src/plugins/dbmeter.ts b/src/@ionic-native/plugins/db-meter/index.ts similarity index 74% rename from src/plugins/dbmeter.ts rename to src/@ionic-native/plugins/db-meter/index.ts index 93d96dc17..0e96b58aa 100644 --- a/src/plugins/dbmeter.ts +++ b/src/@ionic-native/plugins/db-meter/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; /** @@ -6,16 +7,20 @@ import { Observable } from 'rxjs/Observable'; * @description This plugin defines a global DBMeter object, which permits to get the decibel values from the microphone. * @usage * ```typescript - * import { DBMeter } from 'ionic-native'; + * import { DBMeter } from '@ionic-native/db-meter'; + * + * constructor(private dbMeter: DBMeter) { } + * + * ... * * * // Start listening - * let subscription = DBMeter.start().subscribe( + * let subscription = this.dbMeter.start().subscribe( * data => console.log(data) * ); * * // Check if we are listening - * DBMeter.isListening().then( + * this.dbMeter.isListening().then( * (isListening: boolean) => console.log(isListening) * ); * @@ -23,7 +28,7 @@ import { Observable } from 'rxjs/Observable'; * subscription.unsubscribe(); * * // Delete DBMeter instance from memory - * DBMeter.delete().then( + * this.dbMeter.delete().then( * () => console.log('Deleted DB Meter instance'), * error => console.log('Error occurred while deleting DB Meter instance') * ); @@ -36,6 +41,7 @@ import { Observable } from 'rxjs/Observable'; repo: 'https://github.com/akofman/cordova-plugin-dbmeter', platforms: ['iOS', 'Android'] }) +@Injectable() export class DBMeter { /** @@ -46,27 +52,27 @@ export class DBMeter { observable: true, clearFunction: 'stop' }) - static start(): Observable { return; } + start(): Observable { return; } /** * Stops listening - * @private + * @hidden */ @Cordova() - static stop(): Promise { return; } + stop(): Promise { return; } /** * Check if the DB Meter is listening * @returns {Promise} Returns a promise that resolves with a boolean that tells us whether the DB meter is listening */ @Cordova() - static isListening(): Promise { return; } + isListening(): Promise { return; } /** * Delete the DB Meter instance * @returns {Promise} Returns a promise that will resolve if the instance has been deleted, and rejects if errors occur. */ @Cordova() - static delete(): Promise { return; } + delete(): Promise { return; } } diff --git a/src/plugins/deeplinks.ts b/src/@ionic-native/plugins/deeplinks/index.ts similarity index 64% rename from src/plugins/deeplinks.ts rename to src/@ionic-native/plugins/deeplinks/index.ts index d83a10106..069552e63 100644 --- a/src/plugins/deeplinks.ts +++ b/src/@ionic-native/plugins/deeplinks/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; export interface DeeplinkMatch { @@ -29,39 +30,41 @@ export interface DeeplinkMatch { * * @usage * ```typescript - * import { Deeplinks } from 'ionic-native'; + * import { Deeplinks } from '@ionic-native/deeplinks'; * - * Deeplinks.route({ - '/about-us': AboutPage, - '/universal-links-test': AboutPage, - '/products/:productId': ProductPage - }).subscribe((match) => { - // match.$route - the route we matched, which is the matched entry from the arguments to route() - // match.$args - the args passed in the link - // match.$link - the full link data - console.log('Successfully matched route', match); - }, (nomatch) => { - // nomatch.$link - the full link data - console.error('Got a deeplink that didn\'t match', nomatch); - }); + * constructor(private deepLinks: DeepLinks) { } + * + * this.deepLinks.route({ + * '/about-us': AboutPage, + * '/universal-links-test': AboutPage, + * '/products/:productId': ProductPage + * }).subscribe((match) => { + * // match.$route - the route we matched, which is the matched entry from the arguments to route() + * // match.$args - the args passed in the link + * // match.$link - the full link data + * console.log('Successfully matched route', match); + * }, (nomatch) => { + * // nomatch.$link - the full link data + * console.error('Got a deeplink that didn\'t match', nomatch); + * }); * ``` * * Alternatively, if you're using Ionic 2, there's a convenience method that takes a reference to a `NavController` and handles * the actual navigation for you: * * ```typescript - * Deeplinks.routeWithNavController(this.navController, { - '/about-us': AboutPage, - '/products/:productId': ProductPage - }).subscribe((match) => { - // match.$route - the route we matched, which is the matched entry from the arguments to route() - // match.$args - the args passed in the link - // match.$link - the full link data - console.log('Successfully matched route', match); - }, (nomatch) => { - // nomatch.$link - the full link data - console.error('Got a deeplink that didn\'t match', nomatch); - }); + * this.deepLinks.routeWithNavController(this.navController, { + * '/about-us': AboutPage, + * '/products/:productId': ProductPage + * }).subscribe((match) => { + * // match.$route - the route we matched, which is the matched entry from the arguments to route() + * // match.$args - the args passed in the link + * // match.$link - the full link data + * console.log('Successfully matched route', match); + * }, (nomatch) => { + * // nomatch.$link - the full link data + * console.error('Got a deeplink that didn\'t match', nomatch); + * }); * ``` * * See the [Ionic 2 Deeplinks Demo](https://github.com/driftyco/ionic2-deeplinks-demo/blob/master/app/app.ts) for an example of how to @@ -76,8 +79,10 @@ export interface DeeplinkMatch { pluginRef: 'IonicDeeplink', repo: 'https://github.com/driftyco/ionic-plugin-deeplinks', platforms: ['iOS', 'Android'], - install: 'ionic plugin add ionic-plugin-deeplinks --variable URL_SCHEME=myapp --variable DEEPLINK_SCHEME=https --variable DEEPLINK_HOST=example.com --variable ANDROID_PATH_PREFIX=/' + install: 'ionic plugin add ionic-plugin-deeplinks --variable URL_SCHEME=myapp --variable DEEPLINK_SCHEME=https --variable DEEPLINK_HOST=example.com --variable ANDROID_PATH_PREFIX=/', + installVariables: ['URL_SCHEME', 'DEEPLINK_SCHEME', 'DEEPLINK_HOST', 'ANDROID_PATH_PREFIX'] }) +@Injectable() export class Deeplinks { /** @@ -93,7 +98,7 @@ export class Deeplinks { @Cordova({ observable: true }) - static route(paths): Observable { return; } + route(paths): Observable { return; } /** * @@ -116,6 +121,6 @@ export class Deeplinks { @Cordova({ observable: true }) - static routeWithNavController(navController, paths): Observable { return; } + routeWithNavController(navController, paths): Observable { return; } } diff --git a/src/plugins/deviceaccounts.ts b/src/@ionic-native/plugins/device-accounts/index.ts similarity index 52% rename from src/plugins/deviceaccounts.ts rename to src/@ionic-native/plugins/device-accounts/index.ts index e660f6546..17190ad80 100644 --- a/src/plugins/deviceaccounts.ts +++ b/src/@ionic-native/plugins/device-accounts/index.ts @@ -1,5 +1,25 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; +/** + * @name Device Accounts + * @description + * Gets the Google accounts associated with the Android device + * + * @usage + * ```typescript + * import { DeviceAccounts } from '@ionic-native/device-accounts'; + * + * constructor(private deviceAccounts: DeviceAccounts) { } + * + * ... + * + * this.deviceAccounts.get() + * .then(accounts => console.log(accounts)) + * .catch(error => console.error(error)); + * + * ``` + */ @Plugin({ pluginName: 'DeviceAccounts', plugin: 'https://github.com/loicknuchel/cordova-device-accounts.git', @@ -7,6 +27,7 @@ import { Cordova, Plugin } from './plugin'; repo: 'https://github.com/loicknuchel/cordova-device-accounts', platforms: ['Android'] }) +@Injectable() export class DeviceAccounts { /** @@ -14,27 +35,27 @@ export class DeviceAccounts { * @returns {Promise} */ @Cordova() - static get(): Promise { return; } + get(): Promise { return; } /** * Get all accounts registered on Android device for requested type * @returns {Promise} */ @Cordova() - static getByType(type: string): Promise { return; } + getByType(type: string): Promise { return; } /** * Get all emails registered on Android device (accounts with 'com.google' type) * @returns {Promise} */ @Cordova() - static getEmails(): Promise { return; } + getEmails(): Promise { return; } /** * Get the first email registered on Android device * @returns {Promise} */ @Cordova() - static getEmail(): Promise { return; } + getEmail(): Promise { return; } } diff --git a/src/plugins/device-feedback.ts b/src/@ionic-native/plugins/device-feedback/index.ts similarity index 67% rename from src/plugins/device-feedback.ts rename to src/@ionic-native/plugins/device-feedback/index.ts index cf15b1380..f69f49761 100644 --- a/src/plugins/device-feedback.ts +++ b/src/@ionic-native/plugins/device-feedback/index.ts @@ -1,19 +1,25 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; /** - * @name DeviceFeedback + * @name Device Feedback * @description * * Plugin that lets you provide haptic or acoustic feedback on Android devices. * * @usage * ``` - * import { DeviceFeedback } from 'ionic-native'; + * import { DeviceFeedback } from '@ionic-native/device-feedback'; * - * DeviceFeedback.acoustic(); + * constructor(private deviceFeedback: DeviceFeedback) { } * - * DeviceFeedback.haptic(0); + * ... * - * DeviceFeedback.isFeedbackEnabled() + * + * this.deviceFeedback.acoustic(); + * + * this.deviceFeedback.haptic(0); + * + * this.deviceFeedback.isFeedbackEnabled() * .then((feedback) => { * console.log(feedback); * // { @@ -31,26 +37,27 @@ import { Plugin, Cordova } from './plugin'; repo: 'https://github.com/VVelda/device-feedback', platforms: ['Android'] }) +@Injectable() export class DeviceFeedback { /** * Provide sound feedback to user, nevertheless respect user's settings and current active device profile as native feedback do. */ @Cordova({ sync: true }) - static acoustic(): void { } + acoustic(): void { } /** * Provide vibrate feedback to user, nevertheless respect user's tactile feedback setting as native feedback do. * @param type {Number} Specify type of vibration feedback. 0 for long press, 1 for virtual key, or 3 for keyboard tap. */ @Cordova({ sync: true }) - static haptic(type: number): void { } + haptic(type: number): void { } /** * Check if haptic and acoustic feedback is enabled by user settings. * @returns {Promise} */ @Cordova() - static isFeedbackEnabled(): Promise<{ haptic: boolean; acoustic: boolean; }> { return; } + isFeedbackEnabled(): Promise<{ haptic: boolean; acoustic: boolean; }> { return; } } diff --git a/src/plugins/devicemotion.ts b/src/@ionic-native/plugins/device-motion/index.ts similarity index 76% rename from src/plugins/devicemotion.ts rename to src/@ionic-native/plugins/device-motion/index.ts index c163a7bbf..ede9e0ed7 100644 --- a/src/plugins/devicemotion.ts +++ b/src/@ionic-native/plugins/device-motion/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; export interface DeviceMotionAccelerationData { @@ -41,17 +42,20 @@ export interface DeviceMotionAccelerometerOptions { * * @usage * ```typescript - * import { DeviceMotion, DeviceMotionAccelerationData } from 'ionic-native'; + * import { DeviceMotion, DeviceMotionAccelerationData } from '@ionic-native/device-motion'; * + * constructor(private deviceMotion: DeviceMotion) { } + * + * ... * * // Get the device current acceleration - * DeviceMotion.getCurrentAcceleration().then( + * this.deviceMotion.getCurrentAcceleration().then( * (acceleration: DeviceMotionAccelerationData) => console.log(acceleration), * (error: any) => console.log(error) * ); * * // Watch device acceleration - * var subscription = DeviceMotion.watchAcceleration().subscribe((acceleration: DeviceMotionAccelerationData) => { + * var subscription = this.deviceMotion.watchAcceleration().subscribe((acceleration: DeviceMotionAccelerationData) => { * console.log(acceleration); * }); * @@ -69,6 +73,7 @@ export interface DeviceMotionAccelerometerOptions { pluginRef: 'navigator.accelerometer', repo: 'https://github.com/apache/cordova-plugin-device-motion' }) +@Injectable() export class DeviceMotion { /** @@ -76,7 +81,7 @@ export class DeviceMotion { * @returns {Promise} Returns object with x, y, z, and timestamp properties */ @Cordova() - static getCurrentAcceleration(): Promise { return; } + getCurrentAcceleration(): Promise { return; } /** * Watch the device acceleration. Clear the watch by unsubscribing from the observable. @@ -88,6 +93,6 @@ export class DeviceMotion { observable: true, clearFunction: 'clearWatch' }) - static watchAcceleration(options?: DeviceMotionAccelerometerOptions): Observable { return; } + watchAcceleration(options?: DeviceMotionAccelerometerOptions): Observable { return; } } diff --git a/src/plugins/deviceorientation.ts b/src/@ionic-native/plugins/device-orientation/index.ts similarity index 83% rename from src/plugins/deviceorientation.ts rename to src/@ionic-native/plugins/device-orientation/index.ts index c3a5f9967..0aa29c5f5 100644 --- a/src/plugins/deviceorientation.ts +++ b/src/@ionic-native/plugins/device-orientation/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; export interface DeviceOrientationCompassHeading { @@ -47,17 +48,20 @@ export interface DeviceOrientationCompassOptions { * @usage * ```typescript * // DeviceOrientationCompassHeading is an interface for compass - * import { DeviceOrientation, DeviceOrientationCompassHeading } from 'ionic-native'; + * import { DeviceOrientation, DeviceOrientationCompassHeading } from '@ionic-native/device-orientation'; * + * constructor(private deviceOrientation: DeviceOrientation) { } + * + * ... * * // Get the device current compass heading - * DeviceOrientation.getCurrentHeading().then( + * this.deviceOrientation.getCurrentHeading().then( * (data: DeviceOrientationCompassHeading) => console.log(data), * (error: any) => console.log(error) * ); * * // Watch the device compass heading change - * var subscription = DeviceOrientation.watchHeading().subscribe( + * var subscription = this.deviceOrientation.watchHeading().subscribe( * (data: DeviceOrientationCompassHeading) => console.log(data) * ); * @@ -74,6 +78,7 @@ export interface DeviceOrientationCompassOptions { pluginRef: 'navigator.compass', repo: 'https://github.com/apache/cordova-plugin-device-orientation' }) +@Injectable() export class DeviceOrientation { /** @@ -81,7 +86,7 @@ export class DeviceOrientation { * @returns {Promise} */ @Cordova() - static getCurrentHeading(): Promise { return; } + getCurrentHeading(): Promise { return; } /** * Get the device current heading at a regular interval @@ -95,6 +100,6 @@ export class DeviceOrientation { observable: true, clearFunction: 'clearWatch' }) - static watchHeading(options?: DeviceOrientationCompassOptions): Observable { return; } + watchHeading(options?: DeviceOrientationCompassOptions): Observable { return; } } diff --git a/src/plugins/device.ts b/src/@ionic-native/plugins/device/index.ts similarity index 71% rename from src/plugins/device.ts rename to src/@ionic-native/plugins/device/index.ts index 761a082f2..9404c3d64 100644 --- a/src/plugins/device.ts +++ b/src/@ionic-native/plugins/device/index.ts @@ -1,4 +1,5 @@ -import { CordovaProperty, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { CordovaProperty, Plugin } from '@ionic-native/core'; declare var window: any; @@ -9,10 +10,13 @@ declare var window: any; * * @usage * ```typescript - * import { Device } from 'ionic-native'; + * import { Device } from '@ionic-native/device'; * + * constructor(private device: Device) { } * - * console.log('Device UUID is: ' + Device.uuid); + * ... + * + * console.log('Device UUID is: ' + this.device.uuid); * ``` */ @Plugin({ @@ -21,41 +25,42 @@ declare var window: any; pluginRef: 'device', repo: 'https://github.com/apache/cordova-plugin-device' }) +@Injectable() export class Device { /** Get the version of Cordova running on the device. */ @CordovaProperty - static cordova: string; + cordova: string; /** * The device.model returns the name of the device's model or product. The value is set * by the device manufacturer and may be different across versions of the same product. */ @CordovaProperty - static model: string; + model: string; /** Get the device's operating system name. */ @CordovaProperty - static platform: string; + platform: string; /** Get the device's Universally Unique Identifier (UUID). */ @CordovaProperty - static uuid: string; + uuid: string; /** Get the operating system version. */ @CordovaProperty - static version: string; + version: string; /** Get the device's manufacturer. */ @CordovaProperty - static manufacturer: string; + manufacturer: string; /** Whether the device is running on a simulator. */ @CordovaProperty - static isVirtual: boolean; + isVirtual: boolean; /** Get the device hardware serial number. */ @CordovaProperty - static serial: string; + serial: string; } diff --git a/src/plugins/diagnostic.ts b/src/@ionic-native/plugins/diagnostic/index.ts similarity index 81% rename from src/plugins/diagnostic.ts rename to src/@ionic-native/plugins/diagnostic/index.ts index 58474adb7..fdc157614 100644 --- a/src/plugins/diagnostic.ts +++ b/src/@ionic-native/plugins/diagnostic/index.ts @@ -1,4 +1,5 @@ -import {Cordova, Plugin, CordovaProperty} from './plugin'; +import { Injectable } from '@angular/core'; +import {Cordova, Plugin, CordovaProperty} from '@ionic-native/core'; /** * @name Diagnostic @@ -7,19 +8,23 @@ import {Cordova, Plugin, CordovaProperty} from './plugin'; * * @usage * ```typescript - * import { Diagnostic } from 'ionic-native'; + * import { Diagnostic } from '@ionic-native/diagnostic'; + * + * constructor(private diagnostic: Diagnostic) { } + * + * ... * * let successCallback = (isAvailable) => { console.log('Is available? ' + isAvailable); }; * let errorCallback = (e) => console.error(e); * - * Diagnostic.isCameraAvailable().then(successCallback).catch(errorCallback); + * this.diagnostic.isCameraAvailable().then(successCallback).catch(errorCallback); * - * Diagnostic.isBluetoothAvailable().then(successCallback, errorCallback); + * this.diagnostic.isBluetoothAvailable().then(successCallback, errorCallback); * * - * Diagnostic.getBluetoothState() + * this.diagnostic.getBluetoothState() * .then((state) => { - * if (state == Diagnostic.bluetoothState.POWERED_ON){ + * if (state == this.diagnostic.bluetoothState.POWERED_ON){ * // do something * } else { * // do something else @@ -35,9 +40,10 @@ import {Cordova, Plugin, CordovaProperty} from './plugin'; pluginRef: 'cordova.plugins.diagnostic', repo: 'https://github.com/dpa99c/cordova-diagnostic-plugin' }) +@Injectable() export class Diagnostic { - static permission = { + permission = { READ_CALENDAR: 'READ_CALENDAR', WRITE_CALENDAR: 'WRITE_CALENDAR', CAMERA: 'CAMERA', @@ -65,7 +71,7 @@ export class Diagnostic { }; @CordovaProperty - static permissionStatus: { + permissionStatus: { GRANTED: string; DENIED: string; NOT_REQUESTED: string; @@ -74,12 +80,12 @@ export class Diagnostic { GRANTED_WHEN_IN_USE: string; }; - static locationAuthorizationMode = { + locationAuthorizationMode = { ALWAYS: 'always', WHEN_IN_USE: 'when_in_use' }; - static permissionGroups = { + permissionGroups = { CALENDAR: ['READ_CALENDAR', 'WRITE_CALENDAR'], CAMERA: ['CAMERA'], CONTACTS: ['READ_CONTACTS', 'WRITE_CONTACTS', 'GET_ACCOUNTS'], @@ -91,14 +97,14 @@ export class Diagnostic { STORAGE: ['READ_EXTERNAL_STORAGE', 'WRITE_EXTERNAL_STORAGE'] }; - static locationMode = { + locationMode = { HIGH_ACCURACY: 'high_accuracy', DEVICE_ONLY: 'device_only', BATTERY_SAVING: 'battery_saving', LOCATION_OFF: 'location_off' }; - static bluetoothState = { + bluetoothState = { UNKNOWN: 'unknown', RESETTING: 'resetting', // iOS UNSUPPORTED: 'unsupported', // iOS @@ -110,7 +116,7 @@ export class Diagnostic { }; @CordovaProperty - static NFCState: { + NFCState: { UNKNOWN: string; POWERED_OFF: string; POWERED_ON: string; @@ -124,7 +130,7 @@ export class Diagnostic { * @returns {Promise} */ @Cordova() - static isLocationAvailable(): Promise { return; } + isLocationAvailable(): Promise { return; } /** * Checks if Wifi is connected/enabled. On iOS this returns true if the device is connected to a network by WiFi. On Android and Windows 10 Mobile this returns true if the WiFi setting is set to enabled. @@ -132,7 +138,7 @@ export class Diagnostic { * @returns {Promise} */ @Cordova() - static isWifiAvailable(): Promise { return; } + isWifiAvailable(): Promise { return; } /** * Checks if the device has a camera. On Android this returns true if the device has a camera. On iOS this returns true if both the device has a camera AND the application is authorized to use it. On Windows 10 Mobile this returns true if both the device has a rear-facing camera AND the @@ -140,7 +146,7 @@ export class Diagnostic { * @returns {Promise} */ @Cordova() - static isCameraAvailable(): Promise { return; } + isCameraAvailable(): Promise { return; } /** * Checks if the device has Bluetooth capabilities and if so that Bluetooth is switched on (same on Android, iOS and Windows 10 Mobile) @@ -148,38 +154,38 @@ export class Diagnostic { * @returns {Promise} */ @Cordova() - static isBluetoothAvailable(): Promise { return; } + isBluetoothAvailable(): Promise { return; } /** * Displays the device location settings to allow user to enable location services/change location mode. */ @Cordova({ sync: true, platforms: ['Android', 'Windows 10'] }) - static switchToLocationSettings(): void { } + switchToLocationSettings(): void { } /** * Displays mobile settings to allow user to enable mobile data. */ @Cordova({ sync: true, platforms: ['Android', 'Windows 10'] }) - static switchToMobileDataSettings(): void { } + switchToMobileDataSettings(): void { } /** * Displays Bluetooth settings to allow user to enable Bluetooth. */ @Cordova({ sync: true, platforms: ['Android', 'Windows 10'] }) - static switchToBluetoothSettings(): void { } + switchToBluetoothSettings(): void { } /** * Displays WiFi settings to allow user to enable WiFi. */ @Cordova({ sync: true, platforms: ['Android', 'Windows 10'] }) - static switchToWifiSettings(): void { } + switchToWifiSettings(): void { } /** * Returns true if the WiFi setting is set to enabled, and is the same as `isWifiAvailable()` * @returns {Promise} */ @Cordova({ platforms: ['Android', 'Windows 10'] }) - static isWifiEnabled(): Promise { return; } + isWifiEnabled(): Promise { return; } /** * Enables/disables WiFi on the device. @@ -188,7 +194,7 @@ export class Diagnostic { * @returns {Promise} */ @Cordova({ callbackOrder: 'reverse', platforms: ['Android', 'Windows 10'] }) - static setWifiState(state: boolean): Promise { return; } + setWifiState(state: boolean): Promise { return; } /** * Enables/disables Bluetooth on the device. @@ -197,7 +203,7 @@ export class Diagnostic { * @returns {Promise} */ @Cordova({ callbackOrder: 'reverse', platforms: ['Android', 'Windows 10'] }) - static setBluetoothState(state: boolean): Promise { return; } + setBluetoothState(state: boolean): Promise { return; } // ANDROID AND IOS ONLY @@ -207,7 +213,7 @@ export class Diagnostic { * @returns {Promise} */ @Cordova({ platforms: ['Android', 'iOS'] }) - static isLocationEnabled(): Promise { return; } + isLocationEnabled(): Promise { return; } /** * Checks if the application is authorized to use location. @@ -215,14 +221,14 @@ export class Diagnostic { * @returns {Promise} */ @Cordova() - static isLocationAuthorized(): Promise { return; } + isLocationAuthorized(): Promise { return; } /** * Returns the location authorization status for the application. * @returns {Promise} */ @Cordova({ platforms: ['Android', 'iOS'] }) - static getLocationAuthorizationStatus(): Promise { return; } + getLocationAuthorizationStatus(): Promise { return; } /** * Returns the location authorization status for the application. @@ -232,14 +238,14 @@ export class Diagnostic { * @returns {Promise} */ @Cordova({ platforms: ['Android', 'iOS'], callbackOrder: 'reverse' }) - static requestLocationAuthorization(mode?: string): Promise { return; } + requestLocationAuthorization(mode?: string): Promise { return; } /** * Checks if camera hardware is present on device. * @returns {Promise} */ @Cordova({ platforms: ['Android', 'iOS'] }) - static isCameraPresent(): Promise { return; } + isCameraPresent(): Promise { return; } /** * Checks if the application is authorized to use the camera. @@ -247,63 +253,63 @@ export class Diagnostic { * @returns {Promise} */ @Cordova({ platforms: ['Android', 'iOS'] }) - static isCameraAuthorized(): Promise { return; } + isCameraAuthorized(): Promise { return; } /** * Returns the camera authorization status for the application. * @returns {Promise} */ @Cordova({ platforms: ['Android', 'iOS'] }) - static getCameraAuthorizationStatus(): Promise { return; } + getCameraAuthorizationStatus(): Promise { return; } /** * Requests camera authorization for the application. * @returns {Promise} */ @Cordova({ platforms: ['Android', 'iOS'] }) - static requestCameraAuthorization(): Promise { return; } + requestCameraAuthorization(): Promise { return; } /** * Checks if the application is authorized to use the microphone. * @returns {Promise} */ @Cordova({ platforms: ['Android', 'iOS'] }) - static isMicrophoneAuthorized(): Promise { return; } + isMicrophoneAuthorized(): Promise { return; } /** * Returns the microphone authorization status for the application. * @returns {Promise} */ @Cordova({ platforms: ['Android', 'iOS'] }) - static getMicrophoneAuthorizationStatus(): Promise { return; } + getMicrophoneAuthorizationStatus(): Promise { return; } /** * Requests microphone authorization for the application. * @returns {Promise} */ @Cordova({ platforms: ['Android', 'iOS'] }) - static requestMicrophoneAuthorization(): Promise { return; } + requestMicrophoneAuthorization(): Promise { return; } /** * Checks if the application is authorized to use contacts (address book). * @returns {Promise} */ @Cordova({ platforms: ['Android', 'iOS'] }) - static isContactsAuthorized(): Promise { return; } + isContactsAuthorized(): Promise { return; } /** * Returns the contacts authorization status for the application. * @returns {Promise} */ @Cordova({ platforms: ['Android', 'iOS'] }) - static getContactsAuthorizationStatus(): Promise { return; } + getContactsAuthorizationStatus(): Promise { return; } /** * Requests contacts authorization for the application. * @returns {Promise} */ @Cordova({ platforms: ['Android', 'iOS'] }) - static requestContactsAuthorization(): Promise { return; } + requestContactsAuthorization(): Promise { return; } /** * Checks if the application is authorized to use the calendar. @@ -316,7 +322,7 @@ export class Diagnostic { * @returns {Promise} */ @Cordova({ platforms: ['Android', 'iOS'] }) - static isCalendarAuthorized(): Promise { return; } + isCalendarAuthorized(): Promise { return; } /** * Returns the calendar authorization status for the application. @@ -330,7 +336,7 @@ export class Diagnostic { * @returns {Promise} */ @Cordova({ platforms: ['Android', 'iOS'] }) - static getCalendarAuthorizationStatus(): Promise { return; } + getCalendarAuthorizationStatus(): Promise { return; } /** * Requests calendar authorization for the application. @@ -347,7 +353,7 @@ export class Diagnostic { * @returns {Promise} */ @Cordova({ platforms: ['Android', 'iOS'] }) - static requestCalendarAuthorization(): Promise { return; } + requestCalendarAuthorization(): Promise { return; } /** * Opens settings page for this app. @@ -356,28 +362,28 @@ export class Diagnostic { * @returns {Promise} */ @Cordova({ platforms: ['Android', 'iOS'] }) - static switchToSettings(): Promise { return; } + switchToSettings(): Promise { return; } /** * Returns the state of Bluetooth on the device. * @returns {Promise} */ @Cordova({ platforms: ['Android', 'iOS'] }) - static getBluetoothState(): Promise { return; } + getBluetoothState(): Promise { return; } /** * Registers a function to be called when a change in Bluetooth state occurs. * @param handler */ @Cordova({ platforms: ['Android', 'iOS'], sync: true }) - static registerBluetoothStateChangeHandler(handler: Function): void { } + registerBluetoothStateChangeHandler(handler: Function): void { } /** * Registers a function to be called when a change in Location state occurs. * @param handler */ @Cordova({ platforms: ['Android', 'iOS'], sync: true }) - static registerLocationStateChangeHandler(handler: Function): void { } + registerLocationStateChangeHandler(handler: Function): void { } // ANDROID ONLY @@ -388,7 +394,7 @@ export class Diagnostic { * @returns {Promise} */ @Cordova({ platforms: ['Android'] }) - static isGpsLocationAvailable(): Promise { return; } + isGpsLocationAvailable(): Promise { return; } /** * Checks if location mode is set to return high-accuracy locations from GPS hardware. @@ -398,7 +404,7 @@ export class Diagnostic { * @returns {Promise} */ @Cordova({ platforms: ['Android'] }) - static isGpsLocationEnabled(): Promise { return; } + isGpsLocationEnabled(): Promise { return; } /** * Checks if low-accuracy locations are available to the app from network triangulation/WiFi access points. @@ -406,7 +412,7 @@ export class Diagnostic { * @returns {Promise} */ @Cordova({ platforms: ['Android'] }) - static isNetworkLocationAvailable(): Promise { return; } + isNetworkLocationAvailable(): Promise { return; } /** * Checks if location mode is set to return low-accuracy locations from network triangulation/WiFi access points. @@ -416,14 +422,14 @@ export class Diagnostic { * @returns {Promise} */ @Cordova({ platforms: ['Android'] }) - static isNetworkLocationEnabled(): Promise { return; } + isNetworkLocationEnabled(): Promise { return; } /** * Returns the current location mode setting for the device. * @returns {Promise} */ @Cordova({ platforms: ['Android'] }) - static getLocationMode(): Promise { return; } + getLocationMode(): Promise { return; } /** * Returns the current authorisation status for a given permission. @@ -432,7 +438,7 @@ export class Diagnostic { * @returns {Promise} */ @Cordova({ platforms: ['Android'], callbackOrder: 'reverse' }) - static getPermissionAuthorizationStatus(permission: any): Promise { return; } + getPermissionAuthorizationStatus(permission: any): Promise { return; } /** * Returns the current authorisation status for multiple permissions. @@ -441,7 +447,7 @@ export class Diagnostic { * @returns {Promise} */ @Cordova({ platforms: ['Android'], callbackOrder: 'reverse' }) - static getPermissionsAuthorizationStatus(permissions: any[]): Promise { return; } + getPermissionsAuthorizationStatus(permissions: any[]): Promise { return; } /** * Requests app to be granted authorisation for a runtime permission. @@ -450,7 +456,7 @@ export class Diagnostic { * @returns {Promise} */ @Cordova({ platforms: ['Android'], callbackOrder: 'reverse' }) - static requestRuntimePermission(permission: any): Promise { return; } + requestRuntimePermission(permission: any): Promise { return; } /** * Requests app to be granted authorisation for multiple runtime permissions. @@ -459,7 +465,7 @@ export class Diagnostic { * @returns {Promise} */ @Cordova({ platforms: ['Android'], callbackOrder: 'reverse' }) - static requestRuntimePermissions(permissions: any[]): Promise { return; } + requestRuntimePermissions(permissions: any[]): Promise { return; } /** * Indicates if the plugin is currently requesting a runtime permission via the native API. @@ -469,7 +475,7 @@ export class Diagnostic { * @returns {boolean} */ @Cordova({ sync: true }) - static isRequestingPermission(): boolean { return; } + isRequestingPermission(): boolean { return; } /** * Registers a function to be called when a runtime permission request has completed. @@ -477,7 +483,7 @@ export class Diagnostic { * @param handler {Function} */ @Cordova({ sync: true }) - static registerPermissionRequestCompleteHandler(handler: Function): void { return; } + registerPermissionRequestCompleteHandler(handler: Function): void { return; } /** * Checks if the device setting for Bluetooth is switched on. @@ -485,49 +491,49 @@ export class Diagnostic { * @returns {Promise} */ @Cordova({ platforms: ['Android'] }) - static isBluetoothEnabled(): Promise { return; } + isBluetoothEnabled(): Promise { return; } /** * Checks if the device has Bluetooth capabilities. * @returns {Promise} */ @Cordova({ platforms: ['Android'] }) - static hasBluetoothSupport(): Promise { return; } + hasBluetoothSupport(): Promise { return; } /** * Checks if the device has Bluetooth Low Energy (LE) capabilities. * @returns {Promise} */ @Cordova({ platforms: ['Android'] }) - static hasBluetoothLESupport(): Promise { return; } + hasBluetoothLESupport(): Promise { return; } /** * Checks if the device supports Bluetooth Low Energy (LE) Peripheral mode. * @returns {Promise} */ @Cordova({ platforms: ['Android'] }) - static hasBluetoothLEPeripheralSupport(): Promise { return; } + hasBluetoothLEPeripheralSupport(): Promise { return; } /** * Checks if the application is authorized to use external storage. * @returns {Promise} */ @Cordova({ platforms: ['Android'] }) - static isExternalStorageAuthorized(): Promise { return; } + isExternalStorageAuthorized(): Promise { return; } /** * CReturns the external storage authorization status for the application. * @returns {Promise} */ @Cordova({ platforms: ['Android'] }) - static getExternalStorageAuthorizationStatus(): Promise { return; } + getExternalStorageAuthorizationStatus(): Promise { return; } /** * Requests external storage authorization for the application. * @returns {Promise} */ @Cordova({ platforms: ['Android'] }) - static requestExternalStorageAuthorization(): Promise { return; } + requestExternalStorageAuthorization(): Promise { return; } /** * Returns details of external SD card(s): absolute path, is writable, free space. @@ -540,7 +546,7 @@ export class Diagnostic { * @returns {Promise} */ @Cordova({ platforms: ['Android'] }) - static getExternalSdCardDetails(): Promise { return; } + getExternalSdCardDetails(): Promise { return; } /** * Switches to the wireless settings page in the Settings app. Allows configuration of wireless controls such as Wi-Fi, Bluetooth and Mobile networks. @@ -565,7 +571,7 @@ export class Diagnostic { * @returns {Promise} */ @Cordova({ platforms: ['Android'] }) - static isNFCPresent(): Promise { return; } + isNFCPresent(): Promise { return; } /** * Checks if the device setting for NFC is switched on. @@ -573,7 +579,7 @@ export class Diagnostic { * @returns {Promise} */ @Cordova({ platforms: ['Android'] }) - static isNFCEnabled(): Promise { return; } + isNFCEnabled(): Promise { return; } /** * Checks if NFC is available to the app. Returns true if the device has NFC capabilities AND if NFC setting is switched on. @@ -581,7 +587,7 @@ export class Diagnostic { * @returns {Promise} */ @Cordova({ platforms: ['Android'] }) - static isNFCAvailable(): Promise { return; } + isNFCAvailable(): Promise { return; } /** * Registers a function to be called when a change in NFC state occurs. Pass in a falsey value to de-register the currently registered function. @@ -603,14 +609,14 @@ export class Diagnostic { * @returns {Promise} */ @Cordova({ platforms: ['iOS'] }) - static isCameraRollAuthorized(): Promise { return; } + isCameraRollAuthorized(): Promise { return; } /** * Returns the authorization status for the application to use the Camera Roll in Photos app. * @returns {Promise} */ @Cordova({ platforms: ['iOS'] }) - static getCameraRollAuthorizationStatus(): Promise { return; } + getCameraRollAuthorizationStatus(): Promise { return; } /** * Requests camera roll authorization for the application. @@ -619,21 +625,21 @@ export class Diagnostic { * @returns {Promise} */ @Cordova({ platforms: ['iOS'] }) - static requestCameraRollAuthorization(): Promise { return; } + requestCameraRollAuthorization(): Promise { return; } /** * Checks if remote (push) notifications are enabled. * @returns {Promise} */ @Cordova({ platforms: ['iOS'] }) - static isRemoteNotificationsEnabled(): Promise { return; } + isRemoteNotificationsEnabled(): Promise { return; } /** * Indicates if the app is registered for remote (push) notifications on the device. * @returns {Promise} */ @Cordova({ platforms: ['iOS'] }) - static isRegisteredForRemoteNotifications(): Promise { return; } + isRegisteredForRemoteNotifications(): Promise { return; } /** * Indicates the current setting of notification types for the app in the Settings app. @@ -641,42 +647,42 @@ export class Diagnostic { * @returns {Promise} */ @Cordova({ platforms: ['iOS'] }) - static getRemoteNotificationTypes(): Promise { return; } + getRemoteNotificationTypes(): Promise { return; } /** * Checks if the application is authorized to use reminders. * @returns {Promise} */ @Cordova({ platforms: ['iOS'] }) - static isRemindersAuthorized(): Promise { return; } + isRemindersAuthorized(): Promise { return; } /** * Returns the reminders authorization status for the application. * @returns {Promise} */ @Cordova({ platforms: ['iOS'] }) - static getRemindersAuthorizationStatus(): Promise { return; } + getRemindersAuthorizationStatus(): Promise { return; } /** * Requests reminders authorization for the application. * @returns {Promise} */ @Cordova({ platforms: ['iOS'] }) - static requestRemindersAuthorization(): Promise { return; } + requestRemindersAuthorization(): Promise { return; } /** * Checks if the application is authorized for background refresh. * @returns {Promise} */ @Cordova({ platforms: ['iOS'] }) - static isBackgroundRefreshAuthorized(): Promise { return; } + isBackgroundRefreshAuthorized(): Promise { return; } /** * Returns the background refresh authorization status for the application. * @returns {Promise} */ @Cordova({ platforms: ['iOS'] }) - static getBackgroundRefreshStatus(): Promise { return; } + getBackgroundRefreshStatus(): Promise { return; } /** * Requests Bluetooth authorization for the application. @@ -685,14 +691,14 @@ export class Diagnostic { * @return {Promise} */ @Cordova({ platforms: ['iOS'] }) - static requestBluetoothAuthorization(): Promise { return; } + requestBluetoothAuthorization(): Promise { return; } /** * Checks if motion tracking is available on the current device. * @return {Promise} */ @Cordova({ platforms: ['iOS'] }) - static isMotionAvailable(): Promise { return; } + isMotionAvailable(): Promise { return; } /** * Checks if it's possible to determine the outcome of a motion authorization request on the current device. @@ -702,7 +708,7 @@ export class Diagnostic { * @return {Promise} */ @Cordova({ platforms: ['iOS'] }) - static isMotionRequestOutcomeAvailable(): Promise { return; } + isMotionRequestOutcomeAvailable(): Promise { return; } /** * Requests and checks motion authorization for the application: there is no way to independently request only or check only, so both must be done in one operation. @@ -712,6 +718,6 @@ export class Diagnostic { * @return {Promise} */ @Cordova({ platforms: ['iOS'] }) - static requestAndCheckMotionAuthorization(): Promise { return; } + requestAndCheckMotionAuthorization(): Promise { return; } } diff --git a/src/plugins/dialogs.ts b/src/@ionic-native/plugins/dialogs/index.ts similarity index 78% rename from src/plugins/dialogs.ts rename to src/@ionic-native/plugins/dialogs/index.ts index c0bd11f79..ae1083860 100644 --- a/src/plugins/dialogs.ts +++ b/src/@ionic-native/plugins/dialogs/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; export interface DialogsPromptCallback { @@ -25,9 +26,15 @@ export interface DialogsPromptCallback { * * @usage * ```typescript - * import { Dialogs } from 'ionic-native'; + * import { Dialogs } from '@ionic-native/dialogs'; * + * constructor(private dialogs: Dialogs) { } * + * ... + * + * this.dialogs.alert('Hello world') + * .then(() => console.log('Dialog dismissed')) + * .catch(e => console.log('Error displaying dialog', e)); * * * ``` @@ -40,6 +47,7 @@ export interface DialogsPromptCallback { pluginRef: 'navigator.notification', repo: 'https://github.com/apache/cordova-plugin-dialogs.git' }) +@Injectable() export class Dialogs { /** @@ -53,11 +61,7 @@ export class Dialogs { successIndex: 1, errorIndex: 4 }) - static alert( - message, - title: string = 'Alert', - buttonName: string = 'OK' - ): Promise { return; } + alert(message: string, title?: string, buttonName?: string): Promise { return; } /** * Displays a customizable confirmation dialog box. @@ -70,11 +74,7 @@ export class Dialogs { successIndex: 1, errorIndex: 4 }) - static confirm( - message, - title: string = 'Confirm', - buttonLabels: Array = ['OK', 'Cancel'] - ): Promise { return; } + confirm(message, title?: string, buttonLabels?: string[]): Promise { return; } /** * Displays a native dialog box that is more customizable than the browser's prompt function. @@ -88,12 +88,7 @@ export class Dialogs { successIndex: 1, errorIndex: 5 }) - static prompt( - message?: string, - title: string = 'Prompt', - buttonLabels: Array = ['OK', 'Cancel'], - defaultText: string = '' - ): Promise { return; } + prompt(message?: string, title?: string, buttonLabels?: string[], defaultText?: string): Promise { return; } /** @@ -103,6 +98,6 @@ export class Dialogs { @Cordova({ sync: true }) - static beep(times: number): void { } + beep(times: number): void { } } diff --git a/src/plugins/emailcomposer.ts b/src/@ionic-native/plugins/email-composer/index.ts similarity index 83% rename from src/plugins/emailcomposer.ts rename to src/@ionic-native/plugins/email-composer/index.ts index a29d29d0e..58a6b3bb4 100644 --- a/src/plugins/emailcomposer.ts +++ b/src/@ionic-native/plugins/email-composer/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin, CordovaCheck } from '@ionic-native/core'; declare var cordova: any; @@ -35,10 +36,14 @@ export interface EmailComposerOptions { * * @usage * ```typescript - * import { EmailComposer } from 'ionic-native'; + * import { EmailComposer } from '@ionic-native/email-composer'; + * + * constructor(private emailComposer: EmailComposer) { } + * + * ... * * - * EmailComposer.isAvailable().then((available: boolean) =>{ + * this.emailComposer.isAvailable().then((available: boolean) =>{ * if(available) { * //Now we know we can send * } @@ -60,7 +65,7 @@ export interface EmailComposerOptions { * }; * * // Send a text message using default options - * EmailComposer.open(email); + * this.emailComposer.open(email); * * ``` * @interfaces @@ -73,6 +78,7 @@ export interface EmailComposerOptions { repo: 'https://github.com/hypery2k/cordova-email-plugin', platforms: ['Android', 'iOS'] }) +@Injectable() export class EmailComposer { /** @@ -81,7 +87,8 @@ export class EmailComposer { * @param app {string?} An optional app id or uri scheme. * @returns {Promise} Resolves if available, rejects if not available */ - static isAvailable(app?: string): Promise { + @CordovaCheck() + isAvailable(app?: string): Promise { return new Promise((resolve, reject) => { if (app) { cordova.plugins.email.isAvailable(app, (isAvailable) => { @@ -110,7 +117,7 @@ export class EmailComposer { * @param packageName {string} The package name */ @Cordova() - static addAlias(alias: string, packageName: string): void { } + addAlias(alias: string, packageName: string): void { } /** * Displays the email composer pre-filled with data. @@ -123,6 +130,6 @@ export class EmailComposer { successIndex: 1, errorIndex: 3 }) - static open(options: EmailComposerOptions, scope?: any): Promise { return; } + open(options: EmailComposerOptions, scope?: any): Promise { return; } } diff --git a/src/plugins/estimote-beacons.ts b/src/@ionic-native/plugins/estimote-beacons/index.ts similarity index 82% rename from src/plugins/estimote-beacons.ts rename to src/@ionic-native/plugins/estimote-beacons/index.ts index 1151d99f0..b3e932cc0 100644 --- a/src/plugins/estimote-beacons.ts +++ b/src/@ionic-native/plugins/estimote-beacons/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; export interface EstimoteBeaconRegion { @@ -16,11 +17,25 @@ export interface EstimoteBeaconRegion { } /** - * @name EstimoteBeacons + * @name Estimote Beacons * * @description * This plugin enables communication between a phone and Estimote Beacons peripherals. * + * @usage + * ```typescript + * import { EstimoteBeacons } from '@ionic-native/estimote-beacons'; + * + * constructor(private eb: EstimoteBeacons) { } + * + * ... + * + * this.eb.requestAlwaysAuthorization(); + * + * this.eb.enableAnalytics(true); + * + * ``` + * * @interfaces * EstimoteBeaconRegion */ @@ -31,63 +46,64 @@ export interface EstimoteBeaconRegion { repo: 'https://github.com/evothings/phonegap-estimotebeacons', platforms: ['iOS', 'Android'] }) +@Injectable() export class EstimoteBeacons { /** Proximity value */ - static ProximityUnknown = 0; + ProximityUnknown = 0; /** Proximity value */ - static ProximityImmediate = 1; + ProximityImmediate = 1; /** Proximity value */ - static ProximityNear = 2; + ProximityNear = 2; /** Proximity value */ - static ProximityFar = 3; + ProximityFar = 3; /** Beacon colour */ - static BeaconColorUnknown = 0; + BeaconColorUnknown = 0; /** Beacon colour */ - static BeaconColorMintCocktail = 1; + BeaconColorMintCocktail = 1; /** Beacon colour */ - static BeaconColorIcyMarshmallow = 2; + BeaconColorIcyMarshmallow = 2; /** Beacon colour */ - static BeaconColorBlueberryPie = 3; + BeaconColorBlueberryPie = 3; /** * Beacon colour. */ - static BeaconColorSweetBeetroot = 4; + BeaconColorSweetBeetroot = 4; /** Beacon colour */ - static BeaconColorCandyFloss = 5; + BeaconColorCandyFloss = 5; /** Beacon colour */ - static BeaconColorLemonTart = 6; + BeaconColorLemonTart = 6; /** Beacon colour */ - static BeaconColorVanillaJello = 7; + BeaconColorVanillaJello = 7; /** Beacon colour */ - static BeaconColorLiquoriceSwirl = 8; + BeaconColorLiquoriceSwirl = 8; /** Beacon colour */ - static BeaconColorWhite = 9; + BeaconColorWhite = 9; /** Beacon colour */ - static BeaconColorTransparent = 10; + BeaconColorTransparent = 10; /** Region state */ - static RegionStateUnknown = 'unknown'; + RegionStateUnknown = 'unknown'; /** Region state */ - static RegionStateOutside = 'outside'; + RegionStateOutside = 'outside'; /** Region state */ - static RegionStateInside = 'inside'; + RegionStateInside = 'inside'; /** * Ask the user for permission to use location services @@ -108,7 +124,7 @@ export class EstimoteBeacons { * @returns {Promise} */ @Cordova() - static requestWhenInUseAuthorization(): Promise { return; } + requestWhenInUseAuthorization(): Promise { return; } /** * Ask the user for permission to use location services @@ -129,7 +145,7 @@ export class EstimoteBeacons { * @returns {Promise} */ @Cordova() - static requestAlwaysAuthorization(): Promise { return; } + requestAlwaysAuthorization(): Promise { return; } /** * Get the current location authorization status. @@ -148,7 +164,7 @@ export class EstimoteBeacons { * @returns {Promise} */ @Cordova() - static authorizationStatus(): Promise { return; } + authorizationStatus(): Promise { return; } /** * Start advertising as a beacon. @@ -170,7 +186,7 @@ export class EstimoteBeacons { @Cordova({ clearFunction: 'stopAdvertisingAsBeacon' }) - static startAdvertisingAsBeacon(uuid: string, major: number, minor: number, regionId: string): Promise { return; } + startAdvertisingAsBeacon(uuid: string, major: number, minor: number, regionId: string): Promise { return; } /** * Stop advertising as a beacon. @@ -186,7 +202,7 @@ export class EstimoteBeacons { * @returns {Promise} */ @Cordova() - static stopAdvertisingAsBeacon(): Promise { return; } + stopAdvertisingAsBeacon(): Promise { return; } /** * Enable analytics. @@ -201,7 +217,7 @@ export class EstimoteBeacons { * @returns {Promise} */ @Cordova() - static enableAnalytics(enable: boolean): Promise { return; } + enableAnalytics(enable: boolean): Promise { return; } /** * Test if analytics is enabled. @@ -215,7 +231,7 @@ export class EstimoteBeacons { * @returns {Promise} */ @Cordova() - static isAnalyticsEnabled(): Promise { return; } + isAnalyticsEnabled(): Promise { return; } /** * Test if App ID and App Token is set. @@ -229,7 +245,7 @@ export class EstimoteBeacons { * @returns {Promise} */ @Cordova() - static isAuthorized(): Promise { return; } + isAuthorized(): Promise { return; } /** * Set App ID and App Token. @@ -245,7 +261,7 @@ export class EstimoteBeacons { * @returns {Promise} */ @Cordova() - static setupAppIDAndAppToken(appID: string, appToken: string): Promise { return; } + setupAppIDAndAppToken(appID: string, appToken: string): Promise { return; } /** * Start scanning for all nearby beacons using CoreBluetooth (no region object is used). @@ -266,7 +282,7 @@ export class EstimoteBeacons { observable: true, clearFunction: 'stopEstimoteBeaconDiscovery' }) - static startEstimoteBeaconDiscovery(): Observable { return; } + startEstimoteBeaconDiscovery(): Observable { return; } /** * Stop CoreBluetooth scan. Available on iOS. @@ -283,7 +299,7 @@ export class EstimoteBeacons { * @returns {Promise} */ @Cordova() - static stopEstimoteBeaconDiscovery(): Promise { return; } + stopEstimoteBeaconDiscovery(): Promise { return; } /** * Start ranging beacons. Available on iOS and Android. @@ -306,7 +322,7 @@ export class EstimoteBeacons { clearFunction: 'stopRangingBeaconsInRegion', clearWithArgs: true }) - static startRangingBeaconsInRegion(region: EstimoteBeaconRegion): Observable { return; } + startRangingBeaconsInRegion(region: EstimoteBeaconRegion): Observable { return; } /** * Stop ranging beacons. Available on iOS and Android. @@ -325,7 +341,7 @@ export class EstimoteBeacons { * @returns {Promise} */ @Cordova() - static stopRangingBeaconsInRegion(region: EstimoteBeaconRegion): Promise { return; } + stopRangingBeaconsInRegion(region: EstimoteBeaconRegion): Promise { return; } /** * Start ranging secure beacons. Available on iOS. @@ -340,7 +356,7 @@ export class EstimoteBeacons { clearFunction: 'stopRangingSecureBeaconsInRegion', clearWithArgs: true }) - static startRangingSecureBeaconsInRegion(region: EstimoteBeaconRegion): Observable { return; } + startRangingSecureBeaconsInRegion(region: EstimoteBeaconRegion): Observable { return; } /** * Stop ranging secure beacons. Available on iOS. @@ -349,7 +365,7 @@ export class EstimoteBeacons { * @returns {Promise} */ @Cordova() - static stopRangingSecureBeaconsInRegion(region: EstimoteBeaconRegion): Promise { return; } + stopRangingSecureBeaconsInRegion(region: EstimoteBeaconRegion): Promise { return; } /** * Start monitoring beacons. Available on iOS and Android. @@ -375,7 +391,7 @@ export class EstimoteBeacons { successIndex: 1, errorIndex: 2 }) - static startMonitoringForRegion(region: EstimoteBeaconRegion, notifyEntryStateOnDisplay: boolean): Observable { return; } + startMonitoringForRegion(region: EstimoteBeaconRegion, notifyEntryStateOnDisplay: boolean): Observable { return; } /** * Stop monitoring beacons. Available on iOS and Android. @@ -389,7 +405,7 @@ export class EstimoteBeacons { * @returns {Promise} */ @Cordova() - static stopMonitoringForRegion(region: EstimoteBeaconRegion): Promise { return; } + stopMonitoringForRegion(region: EstimoteBeaconRegion): Promise { return; } /** * Start monitoring secure beacons. Available on iOS. @@ -409,7 +425,7 @@ export class EstimoteBeacons { successIndex: 1, errorIndex: 2 }) - static startSecureMonitoringForRegion(region: EstimoteBeaconRegion, notifyEntryStateOnDisplay: boolean): Observable { return; } + startSecureMonitoringForRegion(region: EstimoteBeaconRegion, notifyEntryStateOnDisplay: boolean): Observable { return; } /** * Stop monitoring secure beacons. Available on iOS. @@ -419,7 +435,7 @@ export class EstimoteBeacons { * @returns {Promise} */ @Cordova() - static stopSecureMonitoringForRegion(region: EstimoteBeaconRegion): Promise { return; } + stopSecureMonitoringForRegion(region: EstimoteBeaconRegion): Promise { return; } /** * Connect to Estimote Beacon. Available on Android. @@ -439,7 +455,7 @@ export class EstimoteBeacons { * @returns {Promise} */ @Cordova() - static connectToBeacon(beacon: any): Promise { return; } + connectToBeacon(beacon: any): Promise { return; } /** * Disconnect from connected Estimote Beacon. Available on Android. @@ -451,7 +467,7 @@ export class EstimoteBeacons { * @returns {Promise} */ @Cordova() - static disconnectConnectedBeacon(): Promise { return; } + disconnectConnectedBeacon(): Promise { return; } /** * Write proximity UUID to connected Estimote Beacon. Available on Android. @@ -465,7 +481,7 @@ export class EstimoteBeacons { * @returns {Promise} */ @Cordova() - static writeConnectedProximityUUID(uuid: any): Promise { return; } + writeConnectedProximityUUID(uuid: any): Promise { return; } /** * Write major to connected Estimote Beacon. Available on Android. @@ -479,7 +495,7 @@ export class EstimoteBeacons { * @returns {Promise} */ @Cordova() - static writeConnectedMajor(major: number): Promise { return; } + writeConnectedMajor(major: number): Promise { return; } /** * Write minor to connected Estimote Beacon. Available on Android. @@ -493,7 +509,7 @@ export class EstimoteBeacons { * @returns {Promise} */ @Cordova() - static writeConnectedMinor(minor: number): Promise { return; } + writeConnectedMinor(minor: number): Promise { return; } } diff --git a/src/plugins/facebook.ts b/src/@ionic-native/plugins/facebook/index.ts similarity index 88% rename from src/plugins/facebook.ts rename to src/@ionic-native/plugins/facebook/index.ts index 7add1fc2e..00513de63 100644 --- a/src/plugins/facebook.ts +++ b/src/@ionic-native/plugins/facebook/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; export interface FacebookLoginResponse { @@ -92,8 +93,15 @@ export interface FacebookLoginResponse { * * @usage * ```typescript - * import { Facebook } from 'ionic-native'; + * import { Facebook, FacebookLoginResponse } from '@ionic-native/facebook'; * + * constructor(private fb: Facebook) { } + * + * ... + * + * this.fb.login(['public_profile', 'user_friends', 'email']) + * .then((res: FacebookLoginResponse) => console.log('Logged into Facebook!', res)) + * .catch(e => console.log('Error logging into Facebook', e)); * * * ``` @@ -104,8 +112,10 @@ export interface FacebookLoginResponse { plugin: 'cordova-plugin-facebook4', pluginRef: 'facebookConnectPlugin', repo: 'https://github.com/jeduan/cordova-plugin-facebook4', - install: 'ionic plugin add cordova-plugin-facebook4 --variable APP_ID="123456789" --variable APP_NAME="myApplication"' + install: 'ionic plugin add cordova-plugin-facebook4 --variable APP_ID="123456789" --variable APP_NAME="myApplication"', + installVariables: ['APP_ID', 'APP_NAME'] }) +@Injectable() export class Facebook { /** @@ -115,7 +125,7 @@ export class Facebook { * @returns {Promise} */ @Cordova() - static browserInit(appId: number, version?: string): Promise { + browserInit(appId: number, version?: string): Promise { return; } @@ -140,7 +150,7 @@ export class Facebook { * @returns {Promise} Returns a Promise that resolves with a status object if login succeeds, and rejects if login fails. */ @Cordova() - static login(permissions: string[]): Promise { return; } + login(permissions: string[]): Promise { return; } /** * Logout of Facebook. @@ -149,7 +159,7 @@ export class Facebook { * @returns {Promise} Returns a Promise that resolves on a successful logout, and rejects if logout fails. */ @Cordova() - static logout(): Promise { return; } + logout(): Promise { return; } /** * Determine if a user is logged in to Facebook and has authenticated your app. There are three possible states for a user: @@ -178,7 +188,7 @@ export class Facebook { * @returns {Promise} Returns a Promise that resolves with a status, or rejects with an error */ @Cordova() - static getLoginStatus(): Promise { return; } + getLoginStatus(): Promise { return; } /** * Get a Facebook access token for using Facebook services. @@ -186,7 +196,7 @@ export class Facebook { * @returns {Promise} Returns a Promise that resolves with an access token, or rejects with an error */ @Cordova() - static getAccessToken(): Promise { return; } + getAccessToken(): Promise { return; } /** * Show one of various Facebook dialogs. Example of options for a Share dialog: @@ -206,7 +216,7 @@ export class Facebook { * @returns {Promise} Returns a Promise that resolves with success data, or rejects with an error */ @Cordova() - static showDialog(options: any): Promise { return; } + showDialog(options: any): Promise { return; } /** * Make a call to Facebook Graph API. Can take additional permissions beyond those granted on login. @@ -222,7 +232,7 @@ export class Facebook { * @returns {Promise} Returns a Promise that resolves with the result of the request, or rejects with an error */ @Cordova() - static api(requestPath: string, permissions: string[]): Promise { return; } + api(requestPath: string, permissions: string[]): Promise { return; } /** * Log an event. For more information see the Events section above. @@ -236,11 +246,7 @@ export class Facebook { successIndex: 3, errorIndex: 4 }) - static logEvent( - name: string, - params?: Object, - valueToSum?: number - ): Promise { return; } + logEvent(name: string, params?: Object, valueToSum?: number): Promise { return; } /** * Log a purchase. For more information see the Events section above. @@ -250,7 +256,7 @@ export class Facebook { * @returns {Promise} */ @Cordova() - static logPurchase(value: number, currency: string): Promise { return; } + logPurchase(value: number, currency: string): Promise { return; } /** * Open App Invite dialog. Does not require login. @@ -268,7 +274,7 @@ export class Facebook { * @returns {Promise} Returns a Promise that resolves with the result data, or rejects with an error */ @Cordova() - static appInvite(options: { + appInvite(options: { url: string, picture: string }): Promise { return; } diff --git a/src/plugins/file-chooser.ts b/src/@ionic-native/plugins/file-chooser/index.ts similarity index 61% rename from src/plugins/file-chooser.ts rename to src/@ionic-native/plugins/file-chooser/index.ts index 449bfc8b6..aba17911e 100644 --- a/src/plugins/file-chooser.ts +++ b/src/@ionic-native/plugins/file-chooser/index.ts @@ -1,16 +1,21 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; /** - * @name FileChooser + * @name File Chooser * @description * * Opens the file picker on Android for the user to select a file, returns a file URI. * * @usage * ``` - * import {FileChooser} from 'ionic-native'; + * import { FileChooser } from '@ionic-native/file-chooser'; * - * FileChooser.open() + * constructor(private fileChooser: FileChooser) { } + * + * ... + * + * this.fileChooser.open() * .then(uri => console.log(uri)) * .catch(e => console.log(e)); * @@ -23,6 +28,7 @@ import { Plugin, Cordova } from './plugin'; repo: 'https://github.com/don/cordova-filechooser', platforms: ['Android'] }) +@Injectable() export class FileChooser { /** @@ -30,6 +36,6 @@ export class FileChooser { * @returns {Promise} */ @Cordova() - static open(): Promise { return; } + open(): Promise { return; } } diff --git a/src/plugins/file-opener.ts b/src/@ionic-native/plugins/file-opener/index.ts similarity index 63% rename from src/plugins/file-opener.ts rename to src/@ionic-native/plugins/file-opener/index.ts index 8bdd782ca..27adc26ae 100644 --- a/src/plugins/file-opener.ts +++ b/src/@ionic-native/plugins/file-opener/index.ts @@ -1,15 +1,22 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; /** - * @name FileOpener + * @name File Opener * @description * This plugin will open a file on your device file system with its default application. * * @usage * ``` - * import {FileOpener} from 'ionic-native'; + * import { FileOpener } from '@ionic-native/file-opener'; * + * constructor(private fileOpener: FileOpener) { } * + * ... + * + * this.fileOpener.open('path/to/file.pdf', 'application/pdf') + * .then(() => console.log('File is opened')) + * .catch(e => console.log('Error openening file', e)); * * ``` */ @@ -19,6 +26,7 @@ import { Plugin, Cordova } from './plugin'; pluginRef: 'cordova.plugins.fileOpener2', repo: 'https://github.com/pwlin/cordova-plugin-file-opener2' }) +@Injectable() export class FileOpener { /** @@ -32,7 +40,7 @@ export class FileOpener { successName: 'success', errorName: 'error' }) - static open(filePath: string, fileMIMEType: string): Promise {return; } + open(filePath: string, fileMIMEType: string): Promise {return; } /** * Uninstalls a package @@ -44,7 +52,7 @@ export class FileOpener { successName: 'success', errorName: 'error' }) - static uninstall(packageId: string): Promise {return; } + uninstall(packageId: string): Promise {return; } /** * Check if an app is already installed @@ -56,6 +64,6 @@ export class FileOpener { successName: 'success', errorName: 'error' }) - static appIsInstalled(packageId: string): Promise {return; } + appIsInstalled(packageId: string): Promise {return; } } diff --git a/src/plugins/filepath.ts b/src/@ionic-native/plugins/file-path/index.ts similarity index 58% rename from src/plugins/filepath.ts rename to src/@ionic-native/plugins/file-path/index.ts index 114afa5ef..b4c21643a 100644 --- a/src/plugins/filepath.ts +++ b/src/@ionic-native/plugins/file-path/index.ts @@ -1,20 +1,25 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; declare var window: any; /** - * @name FilePath + * @name File Path * @description * * This plugin allows you to resolve the native filesystem path for Android content URIs and is based on code in the aFileChooser library. * * @usage * ``` - * import {FilePath} from 'ionic-native'; + * import { FilePath } from '@ionic-native/file-path'; * - * FilePath.resolveNativePath(path) - * .then(filePath => console.log(filePath)) - * .catch(err => console.log(err)); + * constructor(private filePath: FilePath) { } + * + * ... + * + * this.filePath.resolveNativePath(path) + * .then(filePath => console.log(filePath); + * .catch(err => console.log(err); * * ``` */ @@ -25,6 +30,7 @@ declare var window: any; repo: 'https://github.com/hiddentao/cordova-plugin-filepath', platforms: ['Android'] }) +@Injectable() export class FilePath { /** @@ -33,6 +39,6 @@ export class FilePath { * @returns {Promise} */ @Cordova() - static resolveNativePath(path: string): Promise {return; } + resolveNativePath(path: string): Promise {return; } } diff --git a/src/plugins/file.ts b/src/@ionic-native/plugins/file/index.ts similarity index 84% rename from src/plugins/file.ts rename to src/@ionic-native/plugins/file/index.ts index be0d42b63..cbcbd4fdf 100644 --- a/src/plugins/file.ts +++ b/src/@ionic-native/plugins/file/index.ts @@ -1,4 +1,5 @@ -import {CordovaProperty, Plugin, pluginWarn} from './plugin'; +import { Injectable } from '@angular/core'; +import { CordovaProperty, Plugin, CordovaCheck } from '@ionic-native/core'; declare var window: any; declare var cordova: any; @@ -347,11 +348,14 @@ export declare var FileError: { * * Example: * ``` - * import { File } from 'ionic-native'; + * import { File } from '@ionic-native/file'; * - * const dataDirectory: string = File.dataDirectory; + * constructor(private file: File) { } + * + * ... + * + * this.file.checkDir(this.file.dataDirectory, 'mydir').then(_ => console.log('Directory exists')).catch(err => console.log('Directory doesnt exist')); * - * File.checkDir(dataDirectory, 'mydir').then(_ => console.log('yay')).catch(err => console.log('boooh')); * ``` * * This plugin is based on several specs, including : The HTML5 File API http://www.w3.org/TR/FileAPI/ @@ -365,82 +369,83 @@ export declare var FileError: { pluginRef: 'cordova.file', repo: 'https://github.com/apache/cordova-plugin-file' }) +@Injectable() export class File { /** * Read-only directory where the application is installed. */ @CordovaProperty - static applicationDirectory: string; + applicationDirectory: string; /** * Read-only directory where the application is installed. */ @CordovaProperty - static applicationStorageDirectory: string; + applicationStorageDirectory: string; /** * Where to put app-specific data files. */ @CordovaProperty - static dataDirectory: string; + dataDirectory: string; /** * Cached files that should survive app restarts. * Apps should not rely on the OS to delete files in here. */ @CordovaProperty - static cacheDirectory: string; + cacheDirectory: string; /** * Android: the application space on external storage. */ @CordovaProperty - static externalApplicationStorageDirectory: string; + externalApplicationStorageDirectory: string; /** * Android: Where to put app-specific data files on external storage. */ @CordovaProperty - static externalDataDirectory: string; + externalDataDirectory: string; /** * Android: the application cache on external storage. */ @CordovaProperty - static externalCacheDirectory: string; + externalCacheDirectory: string; /** * Android: the external storage (SD card) root. */ @CordovaProperty - static externalRootDirectory: string; + externalRootDirectory: string; /** * iOS: Temp directory that the OS can clear at will. */ @CordovaProperty - static tempDirectory: string; + tempDirectory: string; /** * iOS: Holds app-specific files that should be synced (e.g. to iCloud). */ @CordovaProperty - static syncedDataDirectory: string; + syncedDataDirectory: string; /** * iOS: Files private to the app, but that are meaningful to other applications (e.g. Office files) */ @CordovaProperty - static documentsDirectory: string; + documentsDirectory: string; /** * BlackBerry10: Files globally available to all apps */ @CordovaProperty - static sharedDirectory: string; + sharedDirectory: string; - static cordovaFileError: {} = { + cordovaFileError: {} = { 1: 'NOT_FOUND_ERR', 2: 'SECURITY_ERR', 3: 'ABORT_ERR', @@ -461,17 +466,10 @@ export class File { * Get free disk space in Bytes * @returns {Promise} Returns a promise that resolves with the remaining free disk space in Bytes */ - static getFreeDiskSpace(): Promise { + @CordovaCheck() + getFreeDiskSpace(): Promise { return new Promise((resolve, reject) => { - if (!cordova || !cordova.exec) { - pluginWarn({ - pluginName: 'File', - plugin: 'cordova-plugin-file' - }); - reject({ error: 'plugin_not_installed' }); - } else { - cordova.exec(resolve, reject, 'File', 'getFreeDiskSpace', []); - } + cordova.exec(resolve, reject, 'File', 'getFreeDiskSpace', []); }); } @@ -482,7 +480,8 @@ export class File { * @param {string} dir Name of directory to check * @returns {Promise} Returns a Promise that resolves to true if the directory exists or rejects with an error. */ - static checkDir(path: string, dir: string): Promise { + @CordovaCheck() + checkDir(path: string, dir: string): Promise { if ((/^\//.test(dir))) { let err = new FileError(5); err.message = 'directory cannot start with \/'; @@ -490,7 +489,7 @@ export class File { } let fullpath = path + dir; - return File.resolveDirectoryUrl(fullpath) + return this.resolveDirectoryUrl(fullpath) .then(() => { return true; }); @@ -506,7 +505,8 @@ export class File { * @param {boolean} replace If true, replaces file with same name. If false returns error * @returns {Promise} Returns a Promise that resolves with a DirectoryEntry or rejects with an error. */ - static createDir(path: string, dirName: string, replace: boolean): Promise { + @CordovaCheck() + createDir(path: string, dirName: string, replace: boolean): Promise { if ((/^\//.test(dirName))) { let err = new FileError(5); err.message = 'directory cannot start with \/'; @@ -521,9 +521,9 @@ export class File { options.exclusive = true; } - return File.resolveDirectoryUrl(path) + return this.resolveDirectoryUrl(path) .then((fse) => { - return File.getDirectory(fse, dirName, options); + return this.getDirectory(fse, dirName, options); }); } @@ -534,19 +534,20 @@ export class File { * @param {string} dirName The directory name * @returns {Promise} Returns a Promise that resolves to a RemoveResult or rejects with an error. */ - static removeDir(path: string, dirName: string): Promise { + @CordovaCheck() + removeDir(path: string, dirName: string): Promise { if ((/^\//.test(dirName))) { let err = new FileError(5); err.message = 'directory cannot start with \/'; return Promise.reject(err); } - return File.resolveDirectoryUrl(path) + return this.resolveDirectoryUrl(path) .then((fse) => { - return File.getDirectory(fse, dirName, {create: false}); + return this.getDirectory(fse, dirName, {create: false}); }) .then((de) => { - return File.remove(de); + return this.remove(de); }); } @@ -559,7 +560,8 @@ export class File { * @param {string} newDirName The destination directory name * @returns {Promise} Returns a Promise that resolves to the new DirectoryEntry object or rejects with an error. */ - static moveDir(path: string, dirName: string, newPath: string, newDirName: string): Promise { + @CordovaCheck() + moveDir(path: string, dirName: string, newPath: string, newDirName: string): Promise { newDirName = newDirName || dirName; if ((/^\//.test(newDirName))) { @@ -575,7 +577,7 @@ export class File { .then((srcde) => { return this.resolveDirectoryUrl(newPath) .then((deste) => { - return File.move(srcde, deste, newDirName); + return this.move(srcde, deste, newDirName); }); }); } @@ -589,7 +591,8 @@ export class File { * @param {string} newDirName New name of directory to copy to (leave blank to remain the same) * @returns {Promise} Returns a Promise that resolves to the new Entry object or rejects with an error. */ - static copyDir(path: string, dirName: string, newPath: string, newDirName: string): Promise { + @CordovaCheck() + copyDir(path: string, dirName: string, newPath: string, newDirName: string): Promise { if ((/^\//.test(newDirName))) { let err = new FileError(5); err.message = 'directory cannot start with \/'; @@ -603,7 +606,7 @@ export class File { .then((srcde) => { return this.resolveDirectoryUrl(newPath) .then((deste) => { - return File.copy(srcde, deste, newDirName); + return this.copy(srcde, deste, newDirName); }); }); } @@ -615,20 +618,21 @@ export class File { * @param {string} dirName Name of directory * @returns {Promise} Returns a Promise that resolves to an array of Entry objects or rejects with an error. */ - static listDir(path: string, dirName: string): Promise { + @CordovaCheck() + listDir(path: string, dirName: string): Promise { if ((/^\//.test(dirName))) { let err = new FileError(5); err.message = 'directory cannot start with \/'; return Promise.reject(err); } - return File.resolveDirectoryUrl(path) + return this.resolveDirectoryUrl(path) .then((fse) => { - return File.getDirectory(fse, dirName, {create: false, exclusive: false}); + return this.getDirectory(fse, dirName, {create: false, exclusive: false}); }) .then((de) => { let reader = de.createReader(); - return File.readEntries(reader); + return this.readEntries(reader); }); } @@ -639,19 +643,20 @@ export class File { * @param {string} dirName Name of directory * @returns {Promise} Returns a Promise that resolves with a RemoveResult or rejects with an error. */ - static removeRecursively(path: string, dirName: string): Promise { + @CordovaCheck() + removeRecursively(path: string, dirName: string): Promise { if ((/^\//.test(dirName))) { let err = new FileError(5); err.message = 'directory cannot start with \/'; return Promise.reject(err); } - return File.resolveDirectoryUrl(path) + return this.resolveDirectoryUrl(path) .then((fse) => { - return File.getDirectory(fse, dirName, {create: false}); + return this.getDirectory(fse, dirName, {create: false}); }) .then((de) => { - return File.rimraf(de); + return this.rimraf(de); }); } @@ -662,14 +667,15 @@ export class File { * @param {string} file Name of file to check * @returns {Promise} Returns a Promise that resolves with a boolean or rejects with an error. */ - static checkFile(path: string, file: string): Promise { + @CordovaCheck() + checkFile(path: string, file: string): Promise { if ((/^\//.test(file))) { let err = new FileError(5); err.message = 'file cannot start with \/'; return Promise.reject(err); } - return File.resolveLocalFilesystemUrl(path + file) + return this.resolveLocalFilesystemUrl(path + file) .then((fse) => { if (fse.isFile) { return true; @@ -691,7 +697,8 @@ export class File { * @param {boolean} replace If true, replaces file with same name. If false returns error * @returns {Promise} Returns a Promise that resolves to a FileEntry or rejects with an error. */ - static createFile(path: string, fileName: string, replace: boolean): Promise { + @CordovaCheck() + createFile(path: string, fileName: string, replace: boolean): Promise { if ((/^\//.test(fileName))) { let err = new FileError(5); err.message = 'file-name cannot start with \/'; @@ -706,9 +713,9 @@ export class File { options.exclusive = true; } - return File.resolveDirectoryUrl(path) + return this.resolveDirectoryUrl(path) .then((fse) => { - return File.getFile(fse, fileName, options); + return this.getFile(fse, fileName, options); }); } @@ -719,19 +726,20 @@ export class File { * @param {string} fileName Name of file to remove * @returns {Promise} Returns a Promise that resolves to a RemoveResult or rejects with an error. */ - static removeFile(path: string, fileName: string): Promise { + @CordovaCheck() + removeFile(path: string, fileName: string): Promise { if ((/^\//.test(fileName))) { let err = new FileError(5); err.message = 'file-name cannot start with \/'; return Promise.reject(err); } - return File.resolveDirectoryUrl(path) + return this.resolveDirectoryUrl(path) .then((fse) => { - return File.getFile(fse, fileName, {create: false}); + return this.getFile(fse, fileName, {create: false}); }) .then((fe) => { - return File.remove(fe); + return this.remove(fe); }); } @@ -743,7 +751,8 @@ export class File { * @param {WriteOptions} options replace file if set to true. See WriteOptions for more information. * @returns {Promise} Returns a Promise that resolves to updated file entry or rejects with an error. */ - static writeFile(path: string, fileName: string, + @CordovaCheck() + writeFile(path: string, fileName: string, text: string | Blob | ArrayBuffer, options: WriteOptions = {}): Promise { if ((/^\//.test(fileName))) { const err = new FileError(5); @@ -756,25 +765,25 @@ export class File { exclusive: !options.replace }; - return File.resolveDirectoryUrl(path) - .then((fse) => { - return File.getFile(fse, fileName, getFileOpts); + return this.resolveDirectoryUrl(path) + .then((directoryEntry: DirectoryEntry) => { + return this.getFile(directoryEntry, fileName, getFileOpts); }) - .then((fe) => { - return File.writeFileEntry(fe, text, options); + .then((fileEntry: FileEntry) => { + return this.writeFileEntry(fileEntry, text, options); }); } /** Write content to FileEntry. * - * @private + * @hidden * @param {FileEntry} fe file entry object * @param {string | Blob} text content or blob to write * @param {WriteOptions} options replace file if set to true. See WriteOptions for more information. * @returns {Promise} Returns a Promise that resolves to updated file entry or rejects with an error. */ - private static writeFileEntry(fe: FileEntry, text: string | Blob | ArrayBuffer, options: WriteOptions) { - return File.createWriter(fe) + private writeFileEntry(fe: FileEntry, text: string | Blob | ArrayBuffer, options: WriteOptions) { + return this.createWriter(fe) .then((writer) => { if (options.append) { writer.seek(writer.length); @@ -784,7 +793,7 @@ export class File { writer.truncate(options.truncate); } - return File.write(writer, text); + return this.write(writer, text); }) .then(() => fe); } @@ -797,8 +806,9 @@ export class File { * @param {string | Blob} text content or blob to write * @returns {Promise} Returns a Promise that resolves or rejects with an error. */ - static writeExistingFile(path: string, fileName: string, text: string | Blob): Promise { - return File.writeFile(path, fileName, text, { replace: true }); + @CordovaCheck() + writeExistingFile(path: string, fileName: string, text: string | Blob): Promise { + return this.writeFile(path, fileName, text, { replace: true }); } /** @@ -808,18 +818,19 @@ export class File { * @param {string} file Name of file, relative to path. * @returns {Promise} Returns a Promise that resolves with the contents of the file as string or rejects with an error. */ - static readAsText(path: string, file: string): Promise { + @CordovaCheck() + readAsText(path: string, file: string): Promise { if ((/^\//.test(file))) { let err = new FileError(5); err.message = 'file-name cannot start with \/'; return Promise.reject(err); } - return File.resolveDirectoryUrl(path) - .then((fse) => { - return File.getFile(fse, file, {create: false}); + return this.resolveDirectoryUrl(path) + .then((directoryEntry: DirectoryEntry) => { + return this.getFile(directoryEntry, file, {create: false}); }) - .then((fe) => { + .then((fileEntry: FileEntry) => { let reader = new FileReader(); return new Promise((resolve, reject) => { reader.onloadend = () => { @@ -831,7 +842,7 @@ export class File { reject({code: null, message: 'READER_ONLOADEND_ERR'}); } }; - fe.file(file => { + fileEntry.file(file => { reader.readAsText(file); }, error => { reject(error); @@ -849,18 +860,19 @@ export class File { * @param {string} file Name of file, relative to path. * @returns {Promise} Returns a Promise that resolves with the contents of the file as data URL or rejects with an error. */ - static readAsDataURL(path: string, file: string): Promise { + @CordovaCheck() + readAsDataURL(path: string, file: string): Promise { if ((/^\//.test(file))) { let err = new FileError(5); err.message = 'file-name cannot start with \/'; return Promise.reject(err); } - return File.resolveDirectoryUrl(path) - .then((fse) => { - return File.getFile(fse, file, {create: false}); + return this.resolveDirectoryUrl(path) + .then((directoryEntry: DirectoryEntry) => { + return this.getFile(directoryEntry, file, {create: false}); }) - .then((fe) => { + .then((fileEntry: FileEntry) => { let reader = new FileReader(); return new Promise((resolve, reject) => { reader.onloadend = () => { @@ -875,7 +887,7 @@ export class File { - fe.file(file => { + fileEntry.file(file => { reader.readAsDataURL(file); }, error => { reject(error); @@ -891,18 +903,19 @@ export class File { * @param {string} file Name of file, relative to path. * @returns {Promise} Returns a Promise that resolves with the contents of the file as string rejects with an error. */ - static readAsBinaryString(path: string, file: string): Promise { + @CordovaCheck() + readAsBinaryString(path: string, file: string): Promise { if ((/^\//.test(file))) { let err = new FileError(5); err.message = 'file-name cannot start with \/'; return Promise.reject(err); } - return File.resolveDirectoryUrl(path) - .then((fse) => { - return File.getFile(fse, file, {create: false}); + return this.resolveDirectoryUrl(path) + .then((directoryEntry: DirectoryEntry) => { + return this.getFile(directoryEntry, file, {create: false}); }) - .then((fe) => { + .then((fileEntry: FileEntry) => { let reader = new FileReader(); return new Promise((resolve, reject) => { reader.onloadend = () => { @@ -915,7 +928,7 @@ export class File { } }; - fe.file(file => { + fileEntry.file(file => { reader.readAsBinaryString(file); }, error => { reject(error); @@ -927,23 +940,23 @@ export class File { /** * Read file and return data as an ArrayBuffer. - * @param {string} path Base FileSystem. Please refer to the iOS and Android filesystems above * @param {string} file Name of file, relative to path. * @returns {Promise} Returns a Promise that resolves with the contents of the file as ArrayBuffer or rejects with an error. */ - static readAsArrayBuffer(path: string, file: string): Promise { + @CordovaCheck() + readAsArrayBuffer(path: string, file: string): Promise { if ((/^\//.test(file))) { let err = new FileError(5); err.message = 'file-name cannot start with \/'; return Promise.reject(err); } - return File.resolveDirectoryUrl(path) - .then((fse) => { - return File.getFile(fse, file, {create: false}); + return this.resolveDirectoryUrl(path) + .then((directoryEntry: DirectoryEntry) => { + return this.getFile(directoryEntry, file, {create: false}); }) - .then((fe) => { + .then((fileEntry: FileEntry) => { let reader = new FileReader(); return new Promise((resolve, reject) => { reader.onloadend = () => { @@ -956,7 +969,7 @@ export class File { } }; - fe.file(file => { + fileEntry.file(file => { reader.readAsArrayBuffer(file); }, error => { reject(error); @@ -975,7 +988,8 @@ export class File { * @param {string} newFileName New name of file to move to (leave blank to remain the same) * @returns {Promise} Returns a Promise that resolves to the new Entry or rejects with an error. */ - static moveFile(path: string, fileName: string, newPath: string, newFileName: string): Promise { + @CordovaCheck() + moveFile(path: string, fileName: string, newPath: string, newFileName: string): Promise { newFileName = newFileName || fileName; if ((/^\//.test(newFileName))) { @@ -991,7 +1005,7 @@ export class File { .then((srcfe) => { return this.resolveDirectoryUrl(newPath) .then((deste) => { - return File.move(srcfe, deste, newFileName); + return this.move(srcfe, deste, newFileName); }); }); } @@ -1005,7 +1019,8 @@ export class File { * @param {string} newFileName New name of file to copy to (leave blank to remain the same) * @returns {Promise} Returns a Promise that resolves to an Entry or rejects with an error. */ - static copyFile(path: string, fileName: string, newPath: string, newFileName: string): Promise { + @CordovaCheck() + copyFile(path: string, fileName: string, newPath: string, newFileName: string): Promise { newFileName = newFileName || fileName; if ((/^\//.test(newFileName))) { @@ -1021,17 +1036,17 @@ export class File { .then((srcfe) => { return this.resolveDirectoryUrl(newPath) .then((deste) => { - return File.copy(srcfe, deste, newFileName); + return this.copy(srcfe, deste, newFileName); }); }); } /** - * @private + * @hidden */ - private static fillErrorMessage(err: FileError): void { + private fillErrorMessage(err: FileError): void { try { - err.message = File.cordovaFileError[err.code]; + err.message = this.cordovaFileError[err.code]; } catch (e) {} } @@ -1040,17 +1055,18 @@ export class File { * @param fileUrl {string} file system url * @returns {Promise} */ - static resolveLocalFilesystemUrl(fileUrl: string): Promise { + @CordovaCheck() + resolveLocalFilesystemUrl(fileUrl: string): Promise { return new Promise((resolve, reject) => { try { window.resolveLocalFileSystemURL(fileUrl, (entry) => { resolve(entry); }, (err) => { - File.fillErrorMessage(err); + this.fillErrorMessage(err); reject(err); }); } catch (xc) { - File.fillErrorMessage(xc); + this.fillErrorMessage(xc); reject(xc); } }); @@ -1061,8 +1077,9 @@ export class File { * @param directoryUrl {string} directory system url * @returns {Promise} */ - static resolveDirectoryUrl(directoryUrl: string): Promise { - return File.resolveLocalFilesystemUrl(directoryUrl) + @CordovaCheck() + resolveDirectoryUrl(directoryUrl: string): Promise { + return this.resolveLocalFilesystemUrl(directoryUrl) .then((de) => { if (de.isDirectory) { return de; @@ -1081,17 +1098,18 @@ export class File { * @param flags {Flags} Options * @returns {Promise} */ - static getDirectory(directoryEntry: DirectoryEntry, directoryName: string, flags: Flags): Promise { + @CordovaCheck() + getDirectory(directoryEntry: DirectoryEntry, directoryName: string, flags: Flags): Promise { return new Promise((resolve, reject) => { try { directoryEntry.getDirectory(directoryName, flags, (de) => { resolve(de); }, (err) => { - File.fillErrorMessage(err); + this.fillErrorMessage(err); reject(err); }); } catch (xc) { - File.fillErrorMessage(xc); + this.fillErrorMessage(xc); reject(xc); } }); @@ -1104,108 +1122,109 @@ export class File { * @param flags {Flags} Options * @returns {Promise} */ - static getFile(directoryEntry: DirectoryEntry, fileName: string, flags: Flags): Promise { + @CordovaCheck() + getFile(directoryEntry: DirectoryEntry, fileName: string, flags: Flags): Promise { return new Promise((resolve, reject) => { try { directoryEntry.getFile(fileName, flags, resolve, (err) => { - File.fillErrorMessage(err); + this.fillErrorMessage(err); reject(err); }); } catch (xc) { - File.fillErrorMessage(xc); + this.fillErrorMessage(xc); reject(xc); } }); } /** - * @private + * @hidden */ - private static remove(fe: Entry): Promise { + private remove(fe: Entry): Promise { return new Promise((resolve, reject) => { fe.remove(() => { resolve({success: true, fileRemoved: fe}); }, (err) => { - File.fillErrorMessage(err); + this.fillErrorMessage(err); reject(err); }); }); } /** - * @private + * @hidden */ - private static move(srce: Entry, destdir: DirectoryEntry, newName: string): Promise { + private move(srce: Entry, destdir: DirectoryEntry, newName: string): Promise { return new Promise((resolve, reject) => { srce.moveTo(destdir, newName, (deste) => { resolve(deste); }, (err) => { - File.fillErrorMessage(err); + this.fillErrorMessage(err); reject(err); }); }); } /** - * @private + * @hidden */ - private static copy(srce: Entry, destdir: DirectoryEntry, newName: string): Promise { + private copy(srce: Entry, destdir: DirectoryEntry, newName: string): Promise { return new Promise((resolve, reject) => { srce.copyTo(destdir, newName, (deste) => { resolve(deste); }, (err) => { - File.fillErrorMessage(err); + this.fillErrorMessage(err); reject(err); }); }); } /** - * @private + * @hidden */ - private static readEntries(dr: DirectoryReader): Promise { + private readEntries(dr: DirectoryReader): Promise { return new Promise((resolve, reject) => { dr.readEntries((entries) => { resolve(entries); }, (err) => { - File.fillErrorMessage(err); + this.fillErrorMessage(err); reject(err); }); }); } /** - * @private + * @hidden */ - private static rimraf(de: DirectoryEntry): Promise { + private rimraf(de: DirectoryEntry): Promise { return new Promise((resolve, reject) => { de.removeRecursively(() => { resolve({success: true, fileRemoved: de}); }, (err) => { - File.fillErrorMessage(err); + this.fillErrorMessage(err); reject(err); }); }); } /** - * @private + * @hidden */ - private static createWriter(fe: FileEntry): Promise { + private createWriter(fe: FileEntry): Promise { return new Promise((resolve, reject) => { fe.createWriter((writer) => { resolve(writer); }, (err) => { - File.fillErrorMessage(err); + this.fillErrorMessage(err); reject(err); }); }); } /** - * @private + * @hidden */ - private static write(writer: FileWriter, gu: string | Blob | ArrayBuffer): Promise { + private write(writer: FileWriter, gu: string | Blob | ArrayBuffer): Promise { if (gu instanceof Blob) { return this.writeFileInChunks(writer, gu); } @@ -1223,9 +1242,9 @@ export class File { } /** - * @private + * @hidden */ - private static writeFileInChunks(writer: FileWriter, file: Blob) { + private writeFileInChunks(writer: FileWriter, file: Blob) { const BLOCK_SIZE = 1024 * 1024; let writtenSize = 0; diff --git a/src/plugins/fingerprint-aio.ts b/src/@ionic-native/plugins/fingerprint-aio/index.ts similarity index 80% rename from src/plugins/fingerprint-aio.ts rename to src/@ionic-native/plugins/fingerprint-aio/index.ts index 852e23614..6fdf09d17 100644 --- a/src/plugins/fingerprint-aio.ts +++ b/src/@ionic-native/plugins/fingerprint-aio/index.ts @@ -1,4 +1,5 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; export interface FingerprintOptions { @@ -27,9 +28,13 @@ export interface FingerprintOptions { * * @usage * ```typescript - * import { FingerprintAIO } from 'ionic-native'; + * import { FingerprintAIO } from '@ionic-native/fingerprint-aio'; * - * FingerprintAIO.show({ + * constructor(private faio: FingerpirntAIO) { } + * + * ... + * + * this.faio.show({ * clientId: "Fingerprint-Demo", * clientSecret: "password", //Only necessary for Android * disableBackup:true //Only for Android(optional) @@ -48,6 +53,7 @@ export interface FingerprintOptions { repo: 'https://github.com/NiklasMerz/cordova-plugin-fingerprint-aio', platforms: ['Android', 'iOS'] }) +@Injectable() export class FingerprintAIO { /** @@ -55,7 +61,7 @@ export class FingerprintAIO { * @return {Promise} Returns a promise with result */ @Cordova() - static isAvailable(): Promise { return; } + isAvailable(): Promise { return; } /** * Show authentication dialogue @@ -63,6 +69,6 @@ export class FingerprintAIO { * @return {Promise} Returns a promise that resolves when authentication was successfull */ @Cordova() - static show(options: FingerprintOptions): Promise { return; } + show(options: FingerprintOptions): Promise { return; } } diff --git a/src/plugins/firebase.ts b/src/@ionic-native/plugins/firebase/index.ts similarity index 73% rename from src/plugins/firebase.ts rename to src/@ionic-native/plugins/firebase/index.ts index 439eaabd0..33eb302f6 100644 --- a/src/plugins/firebase.ts +++ b/src/@ionic-native/plugins/firebase/index.ts @@ -1,4 +1,5 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; /** @@ -8,13 +9,17 @@ import { Observable } from 'rxjs/Observable'; * * @usage * ``` - * import { Firebase } from 'ionic-native'; + * import { Firebase } from '@ionic-native/firebase'; * - * Firebase.getToken() + * constructor(private firebase: Firebase) { } + * + * ... + * + * this.firebase.getToken() * .then(token => console.log(`The token is ${token}`)) // save the token server-side and use it to push notifications to this device * .catch(error => console.error('Error getting token', error)); * - * Firebase.onTokenRefresh() + * this.firebase.onTokenRefresh() * .subscribe((token: string) => console.log(`Got a new token ${token}`)); * * ``` @@ -26,6 +31,7 @@ import { Observable } from 'rxjs/Observable'; repo: 'https://github.com/arnesson/cordova-plugin-firebase', platforms: ['Android', 'iOS'] }) +@Injectable() export class Firebase { /** @@ -33,7 +39,7 @@ export class Firebase { * @return {Promise} */ @Cordova() - static getToken(): Promise { return; } + getToken(): Promise { return; } /** * Get notified when a token is refreshed @@ -42,7 +48,7 @@ export class Firebase { @Cordova({ observable: true }) - static onTokenRefresh(): Observable { return; } + onTokenRefresh(): Observable { return; } /** * Get notified when the user opens a notification @@ -51,7 +57,7 @@ export class Firebase { @Cordova({ observable: true }) - static onNotificationOpen(): Observable { return; } + onNotificationOpen(): Observable { return; } /** * Grant permission to recieve push notifications @@ -60,7 +66,7 @@ export class Firebase { @Cordova({ platforms: ['iOS'] }) - static grantPermission(): Promise { return; } + grantPermission(): Promise { return; } /** * Check permission to recieve push notifications @@ -69,7 +75,7 @@ export class Firebase { @Cordova({ platforms: ['iOS'] }) - static hasPermission(): Promise { return; } + hasPermission(): Promise { return; } /** * Set icon badge number. Set to 0 to clear the badge. @@ -77,14 +83,14 @@ export class Firebase { * @return {Promise} */ @Cordova() - static setBadgeNumber(badgeNumber: number): Promise { return; } + setBadgeNumber(badgeNumber: number): Promise { return; } /** * Get icon badge number * @return {Promise} */ @Cordova() - static getBadgeNumber(): Promise { return; } + getBadgeNumber(): Promise { return; } /** * Subscribe to a topic @@ -92,7 +98,7 @@ export class Firebase { * @return {Promise} */ @Cordova() - static subscribe(topic: string): Promise { return; } + subscribe(topic: string): Promise { return; } /** * Unsubscribe from a topic @@ -100,7 +106,7 @@ export class Firebase { * @return {Promise} */ @Cordova() - static unsubscribe(topic: string): Promise { return; } + unsubscribe(topic: string): Promise { return; } /** * Log an event using Analytics @@ -109,7 +115,7 @@ export class Firebase { * @return {Promise} */ @Cordova() - static logEvent(type: string, data: any): Promise { return; } + logEvent(type: string, data: any): Promise { return; } /** * Set the name of the current screen in Analytics @@ -117,7 +123,7 @@ export class Firebase { * @return {Promise} */ @Cordova() - static setScreenName(name: string): Promise { return; } + setScreenName(name: string): Promise { return; } /** * Set a user id for use in Analytics @@ -125,7 +131,7 @@ export class Firebase { * @return {Promise} */ @Cordova() - static setUserId(userId: string): Promise { return; } + setUserId(userId: string): Promise { return; } /** * Set a user property for use in Analytics @@ -134,7 +140,7 @@ export class Firebase { * @return {Promise} */ @Cordova() - static setUserProperty(name: string, value: string): Promise { return; } + setUserProperty(name: string, value: string): Promise { return; } /** * Fetch Remote Config parameter values for your app @@ -146,7 +152,7 @@ export class Firebase { successIndex: 1, errorIndex: 2 }) - static fetch(cacheExpirationSeconds?: number): Promise { return; } + fetch(cacheExpirationSeconds?: number): Promise { return; } /** * Activate the Remote Config fetched config @@ -155,7 +161,7 @@ export class Firebase { @Cordova({ platforms: ['Android'] }) - static activateFetched(): Promise { return; } + activateFetched(): Promise { return; } /** * Retrieve a Remote Config value @@ -168,7 +174,7 @@ export class Firebase { successIndex: 2, errorIndex: 3 }) - static getValue(key: string, namespace?: string): Promise { return; } + getValue(key: string, namespace?: string): Promise { return; } /** * Retrieve a Remote Config byte array @@ -181,7 +187,7 @@ export class Firebase { successIndex: 2, errorIndex: 3 }) - static getByteArray(key: string, namespace?: string): Promise { return; } + getByteArray(key: string, namespace?: string): Promise { return; } /** * Get the current state of the FirebaseRemoteConfig singleton object @@ -190,7 +196,7 @@ export class Firebase { @Cordova({ platforms: ['Android'] }) - static getInfo(): Promise { return; } + getInfo(): Promise { return; } /** * Change the settings for the FirebaseRemoteConfig object's operations @@ -200,7 +206,7 @@ export class Firebase { @Cordova({ platforms: ['Android'] }) - static setConfigSettings(settings: any): Promise { return; } + setConfigSettings(settings: any): Promise { return; } /** * Set defaults in the Remote Config @@ -213,6 +219,6 @@ export class Firebase { successIndex: 2, errorIndex: 3 }) - static setDefaults(defaults: any, namespace: string): Promise { return; } + setDefaults(defaults: any, namespace: string): Promise { return; } } diff --git a/src/plugins/flashlight.ts b/src/@ionic-native/plugins/flashlight/index.ts similarity index 70% rename from src/plugins/flashlight.ts rename to src/@ionic-native/plugins/flashlight/index.ts index 0fb2aa4a5..7ac98cddc 100644 --- a/src/plugins/flashlight.ts +++ b/src/@ionic-native/plugins/flashlight/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; /** * @name Flashlight @@ -8,8 +9,13 @@ import { Cordova, Plugin } from './plugin'; * * @usage * ```typescript - * import { Flashlight } from 'ionic-native'; + * import { Flashlight } from '@ionic-native/flashlight'; * + * constructor(private flashlight: FlashLight) { } + * + * ... + * + * this.flashlight.switchOn(); * * * ``` @@ -20,6 +26,7 @@ import { Cordova, Plugin } from './plugin'; pluginRef: 'window.plugins.flashlight', repo: 'https://github.com/EddyVerbruggen/Flashlight-PhoneGap-Plugin.git' }) +@Injectable() export class Flashlight { /** @@ -27,28 +34,28 @@ export class Flashlight { * @returns {Promise} Returns a promise that resolves with a boolean stating if the flashlight is available. */ @Cordova() - static available(): Promise { return; } + available(): Promise { return; } /** * Switches the flashlight on * @returns {Promise} */ @Cordova() - static switchOn(): Promise { return; } + switchOn(): Promise { return; } /** * Switches the flashlight off * @returns {Promise} */ @Cordova() - static switchOff(): Promise { return; } + switchOff(): Promise { return; } /** * Toggles the flashlight * @returns {Promise} */ @Cordova() - static toggle(): Promise { return; } + toggle(): Promise { return; } /** @@ -58,6 +65,6 @@ export class Flashlight { @Cordova({ sync: true }) - static isSwitchedOn(): boolean { return; } + isSwitchedOn(): boolean { return; } } diff --git a/src/plugins/geofence.ts b/src/@ionic-native/plugins/geofence/index.ts similarity index 80% rename from src/plugins/geofence.ts rename to src/@ionic-native/plugins/geofence/index.ts index f8cf5054a..c9fd1e98c 100644 --- a/src/plugins/geofence.ts +++ b/src/@ionic-native/plugins/geofence/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin, CordovaFunctionOverride } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; declare var window: any; @@ -9,21 +10,21 @@ declare var window: any; * Geofences persist after device reboot. Geofences will be monitored even when the app is not running. * @usage * ``` - * import { Geofence } from 'ionic-native'; - * import { Platform } from 'ionic-angular' + * import { Geofence } from '@ionic-native/geofence'; + * * ... * - * constructor(private platform: Platform) { - * this.platform.ready().then(() => { - // initialize the plugin - * Geofence.initialize().then( - * // resolved promise does not return a value - * () => console.log('Geofence Plugin Ready'), - * (err) => console.log(err) - * ) - * }) + * constructor(private geofence: Geofence) { + * // initialize the plugin + * geofence.initialize().then( + * // resolved promise does not return a value + * () => console.log('Geofence Plugin Ready'), + * (err) => console.log(err) + * ) * } * + * ... + * * private addGeofence() { * //options describing geofence * let fence = { @@ -40,7 +41,7 @@ declare var window: any; * } * } * - * Geofence.addOrUpdate(fence).then( + * this.geofence.addOrUpdate(fence).then( * () => console.log('Geofence added'), * (err) => console.log('Geofence failed to add') * ); @@ -82,15 +83,21 @@ declare var window: any; platforms: ['Android', 'iOS', 'Windows Phone 8', 'Windows Phone'] }) +@Injectable() export class Geofence { - public static TransitionType = { + public TransitionType = { ENTER: 1, EXIT: 2, BOTH: 3 }; - public static onTrasitionReceived: Function; + /** + * Subscribe to get notified when a transition is received + * @return {Observable} + */ + @CordovaFunctionOverride() + onTrasitionReceived(): Observable { return; }; /** * Initializes the plugin. User will be prompted to allow the app to use location and notifications. @@ -98,7 +105,7 @@ export class Geofence { * @returns {Promise} */ @Cordova() - static initialize(): Promise { return; }; + initialize(): Promise { return; }; /** * Adds a new geofence or array of geofences. For geofence object, see above. @@ -106,7 +113,7 @@ export class Geofence { * @returns {Promise} */ @Cordova() - static addOrUpdate(geofences: Object | Array): Promise { return; }; + addOrUpdate(geofences: Object | Array): Promise { return; }; /** * Removes a geofence or array of geofences. `geofenceID` corresponds to one or more IDs specified when the @@ -115,7 +122,7 @@ export class Geofence { * @returns {Promise} */ @Cordova() - static remove(geofenceId: string | Array): Promise { return; }; + remove(geofenceId: string | Array): Promise { return; }; /** * Removes all geofences. @@ -123,7 +130,7 @@ export class Geofence { * @returns {Promise} */ @Cordova() - static removeAll(): Promise { return; }; + removeAll(): Promise { return; }; /** * Returns an array of geofences currently being monitored. @@ -131,14 +138,14 @@ export class Geofence { * @returns {Promise>} */ @Cordova() - static getWatched(): Promise { return; }; + getWatched(): Promise { return; }; /** * Called when a geofence is crossed in the direction specified by `TransitType`. * * @returns {Observable} */ - static onTransitionReceived(): Observable { + onTransitionReceived(): Observable { return new Observable((observer) => { window && window.geofence && (window.geofence.onTransitionReceived = observer.next.bind(observer)); @@ -152,7 +159,7 @@ export class Geofence { * * @returns {Observable} */ - static onNotificationClicked(): Observable { + onNotificationClicked(): Observable { return new Observable((observer) => { window && window.geofence && (window.geofence.onNotificationClicked = observer.next.bind(observer)); diff --git a/src/plugins/geolocation.ts b/src/@ionic-native/plugins/geolocation/index.ts similarity index 94% rename from src/plugins/geolocation.ts rename to src/@ionic-native/plugins/geolocation/index.ts index 37be828e8..dbf2d11ae 100644 --- a/src/plugins/geolocation.ts +++ b/src/@ionic-native/plugins/geolocation/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; declare var navigator: any; @@ -119,7 +120,7 @@ export interface GeolocationOptions { * @usage * * ```typescript - * import { Geolocation } from 'ionic-native'; + * import { Geolocation } from '@ionic-native/geolocation'; * * * Geolocation.getCurrentPosition().then((resp) => { @@ -148,6 +149,7 @@ export interface GeolocationOptions { pluginRef: 'navigator.geolocation', repo: 'https://github.com/apache/cordova-plugin-geolocation' }) +@Injectable() export class Geolocation { /** @@ -159,7 +161,7 @@ export class Geolocation { @Cordova({ callbackOrder: 'reverse' }) - static getCurrentPosition(options?: GeolocationOptions): Promise { return; } + getCurrentPosition(options?: GeolocationOptions): Promise { return; } /** * Watch the current device's position. Clear the watch by unsubscribing from @@ -179,7 +181,7 @@ export class Geolocation { * @param {GeolocationOptions} options The [geolocation options](https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions). * @returns {Observable} Returns an Observable that notifies with the [position](https://developer.mozilla.org/en-US/docs/Web/API/Position) of the device, or errors. */ - static watchPosition(options?: GeolocationOptions): Observable { + watchPosition(options?: GeolocationOptions): Observable { return new Observable( (observer: any) => { let watchId = navigator.geolocation.watchPosition(observer.next.bind(observer), observer.next.bind(observer), options); diff --git a/src/plugins/globalization.ts b/src/@ionic-native/plugins/globalization/index.ts similarity index 70% rename from src/plugins/globalization.ts rename to src/@ionic-native/plugins/globalization/index.ts index 87f4305eb..f99bddc25 100644 --- a/src/plugins/globalization.ts +++ b/src/@ionic-native/plugins/globalization/index.ts @@ -1,11 +1,22 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; /** * @name Globalization * @description * @usage * ```typescript - * import { Globalization } from 'ionic-native'; + * import { Globalization } from '@ionic-native/globalization'; + * + * constructor(private globalization: Globalization) { } + * + * + * ... + * + * + * this.globalization.getPreferredLanguage() + * .then(res => console.log(res)) + * .catch(e => console.log(e)); * * * ``` @@ -17,6 +28,7 @@ import { Cordova, Plugin } from './plugin'; repo: 'https://github.com/apache/cordova-plugin-globalization', platforms: ['Amazon Fire OS', 'Android', 'BlackBerry 10', 'Firefox OS', 'iOS', 'Windows Phone 8', 'Widnows', 'Browser'] }) +@Injectable() export class Globalization { /** @@ -24,14 +36,14 @@ export class Globalization { * @returns {Promise<{value: string}>} */ @Cordova() - static getPreferredLanguage(): Promise<{ value: string }> { return; } + getPreferredLanguage(): Promise<{ value: string }> { return; } /** * Returns the BCP 47 compliant locale identifier string to the successCallback with a properties object as a parameter. * @returns {Promise<{value: string}>} */ @Cordova() - static getLocaleName(): Promise<{ value: string }> { return; } + getLocaleName(): Promise<{ value: string }> { return; } /** * Converts date to string @@ -43,7 +55,7 @@ export class Globalization { successIndex: 1, errorIndex: 2 }) - static dateToString(date: Date, options: { formatLength: string, selector: string }): Promise<{ value: string }> { return; } + dateToString(date: Date, options: { formatLength: string, selector: string }): Promise<{ value: string }> { return; } /** * Parses a date formatted as a string, according to the client's user preferences and calendar using the time zone of the client, and returns the corresponding date object. @@ -55,7 +67,7 @@ export class Globalization { successIndex: 1, errorIndex: 2 }) - static stringToDate(dateString: string, options: { formatLength: string, selector: string }): Promise<{ year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number }> { return; } + stringToDate(dateString: string, options: { formatLength: string, selector: string }): Promise<{ year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number }> { return; } /** * Returns a pattern string to format and parse dates according to the client's user preferences. @@ -65,7 +77,7 @@ export class Globalization { @Cordova({ callbackOrder: 'reverse' }) - static getDatePattern(options: { formatLength: string, selector: string }): Promise<{ pattern: string }> { return; } + getDatePattern(options: { formatLength: string, selector: string }): Promise<{ pattern: string }> { return; } /** * Returns an array of the names of the months or days of the week, depending on the client's user preferences and calendar. @@ -75,7 +87,7 @@ export class Globalization { @Cordova({ callbackOrder: 'reverse' }) - static getDateNames(options: { type: string, item: string }): Promise<{ value: Array }> { return; } + getDateNames(options: { type: string, item: string }): Promise<{ value: Array }> { return; } /** * Indicates whether daylight savings time is in effect for a given date using the client's time zone and calendar. @@ -83,14 +95,14 @@ export class Globalization { * @returns {Promise<{dst: string}>} reutrns a promise with the value */ @Cordova() - static isDayLightSavingsTime(date: Date): Promise<{ dst: string }> { return; } + isDayLightSavingsTime(date: Date): Promise<{ dst: string }> { return; } /** * Returns the first day of the week according to the client's user preferences and calendar. * @returns {Promise<{value: string}>} returns a promise with the value */ @Cordova() - static getFirstDayOfWeek(): Promise<{ value: string }> { return; } + getFirstDayOfWeek(): Promise<{ value: string }> { return; } /** * Returns a number formatted as a string according to the client's user preferences. @@ -101,7 +113,7 @@ export class Globalization { successIndex: 1, errorIndex: 2 }) - static numberToString(numberToConvert: number, options: { type: string }): Promise<{ value: string }> { return; } + numberToString(numberToConvert: number, options: { type: string }): Promise<{ value: string }> { return; } /** * @@ -113,7 +125,7 @@ export class Globalization { successIndex: 1, errorIndex: 2 }) - static stringToNumber(stringToConvert: string, options: { type: string }): Promise<{ value: number | string }> { return; } + stringToNumber(stringToConvert: string, options: { type: string }): Promise<{ value: number | string }> { return; } /** * Returns a pattern string to format and parse numbers according to the client's user preferences. @@ -123,7 +135,7 @@ export class Globalization { @Cordova({ callbackOrder: 'reverse' }) - static getNumberPattern(options: { type: string }): Promise<{ pattern: string, symbol: string, fraction: number, rounding: number, positive: string, negative: string, decimal: string, grouping: string }> { return; } + getNumberPattern(options: { type: string }): Promise<{ pattern: string, symbol: string, fraction: number, rounding: number, positive: string, negative: string, decimal: string, grouping: string }> { return; } /** * Returns a pattern string to format and parse currency values according to the client's user preferences and ISO 4217 currency code. @@ -131,6 +143,6 @@ export class Globalization { * @returns {Promise<{ pattern: string, code: string, fraction: number, rounding: number, decimal: number, grouping: string }>} */ @Cordova() - static getCurrencyPattern(currencyCode: string): Promise<{ pattern: string, code: string, fraction: number, rounding: number, decimal: number, grouping: string }> { return; } + getCurrencyPattern(currencyCode: string): Promise<{ pattern: string, code: string, fraction: number, rounding: number, decimal: number, grouping: string }> { return; } } diff --git a/src/plugins/googleanalytics.ts b/src/@ionic-native/plugins/google-analytics/index.ts similarity index 74% rename from src/plugins/googleanalytics.ts rename to src/@ionic-native/plugins/google-analytics/index.ts index 7791e2c3a..b108889bc 100644 --- a/src/plugins/googleanalytics.ts +++ b/src/@ionic-native/plugins/google-analytics/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; declare var window; @@ -12,9 +13,13 @@ declare var window; * - (Android) Google Play Services SDK installed via [Android SDK Manager](https://developer.android.com/sdk/installing/adding-packages.html) * @usage * ```typescript - * import { GoogleAnalytics } from 'ionic-native'; + * import { GoogleAnalytics } from '@ionic-native/google-analytics'; * - * GoogleAnalytics.startTrackerWithId('YOUR_TRACKER_ID') + * constructor(private ga: GoogleAnalytics) { } + * + * ... + * + * this.ga.startTrackerWithId('YOUR_TRACKER_ID') * .then(() => { * console.log('Google analytics is ready now'); * // Tracker is ready @@ -32,6 +37,7 @@ declare var window; repo: 'https://github.com/danwilson/google-analytics-plugin', platforms: ['Android', 'iOS', 'Browser'] }) +@Injectable() export class GoogleAnalytics { /** @@ -45,7 +51,7 @@ export class GoogleAnalytics { successIndex: 2, errorIndex: 3 }) - static startTrackerWithId(id: string, interval?: number): Promise { return; } + startTrackerWithId(id: string, interval?: number): Promise { return; } /** * Enabling Advertising Features in Google Analytics allows you to take advantage of Remarketing, Demographics & Interests reports, and more @@ -53,7 +59,7 @@ export class GoogleAnalytics { * @returns {Promise} */ @Cordova() - static setAllowIDFACollection(allow: boolean): Promise { return; } + setAllowIDFACollection(allow: boolean): Promise { return; } /** * Set a UserId @@ -62,7 +68,7 @@ export class GoogleAnalytics { * @returns {Promise} */ @Cordova() - static setUserId(id: string): Promise { return; } + setUserId(id: string): Promise { return; } /** * Set a anonymize Ip address @@ -70,7 +76,7 @@ export class GoogleAnalytics { * @returns {Promise} */ @Cordova() - static setAnonymizeIp(anonymize: boolean): Promise { return; } + setAnonymizeIp(anonymize: boolean): Promise { return; } /** * Sets the app version @@ -78,7 +84,7 @@ export class GoogleAnalytics { * @returns {Promise} */ @Cordova() - static setAppVersion(appVersion: string): Promise { return; } + setAppVersion(appVersion: string): Promise { return; } /** * Set OptOut @@ -86,14 +92,14 @@ export class GoogleAnalytics { * @returns {Promise} */ @Cordova() - static setOptOut(optout: boolean): Promise { return; } + setOptOut(optout: boolean): Promise { return; } /** * Enable verbose logging * @returns {Promise} */ @Cordova() - static debugMode(): Promise { return; } + debugMode(): Promise { return; } /** * Track custom metric @@ -105,7 +111,7 @@ export class GoogleAnalytics { successIndex: 2, errorIndex: 3 }) - static trackMetric(key: string, value?: any): Promise { return; } + trackMetric(key: string, value?: any): Promise { return; } /** * Track a screen @@ -120,7 +126,7 @@ export class GoogleAnalytics { successIndex: 3, errorIndex: 4 }) - static trackView(title: string, campaignUrl?: string, newSession?: boolean): Promise { return; } + trackView(title: string, campaignUrl?: string, newSession?: boolean): Promise { return; } /** * Add a Custom Dimension @@ -130,7 +136,7 @@ export class GoogleAnalytics { * @returns {Promise} */ @Cordova() - static addCustomDimension(key: number, value: string): Promise { return; } + addCustomDimension(key: number, value: string): Promise { return; } /** * Track an event @@ -146,7 +152,7 @@ export class GoogleAnalytics { successIndex: 5, errorIndex: 6 }) - static trackEvent(category: string, action: string, label?: string, value?: number, newSession?: boolean): Promise { return; } + trackEvent(category: string, action: string, label?: string, value?: number, newSession?: boolean): Promise { return; } /** * Track an exception @@ -155,7 +161,7 @@ export class GoogleAnalytics { * @returns {Promise} */ @Cordova() - static trackException(description: string, fatal: boolean): Promise { return; } + trackException(description: string, fatal: boolean): Promise { return; } /** * Track User Timing (App Speed) @@ -166,7 +172,7 @@ export class GoogleAnalytics { * @returns {Promise} */ @Cordova() - static trackTiming(category: string, intervalInMilliseconds: number, variable: string, label: string): Promise { return; } + trackTiming(category: string, intervalInMilliseconds: number, variable: string, label: string): Promise { return; } /** * Add a Transaction (Ecommerce) @@ -180,7 +186,7 @@ export class GoogleAnalytics { * @returns {Promise} */ @Cordova() - static addTransaction(id: string, affiliation: string, revenue: number, tax: number, shipping: number, currencyCode: string): Promise { return; } + addTransaction(id: string, affiliation: string, revenue: number, tax: number, shipping: number, currencyCode: string): Promise { return; } /** * Add a Transaction Item (Ecommerce) @@ -195,7 +201,7 @@ export class GoogleAnalytics { * @returns {Promise} */ @Cordova() - static addTransactionItem(id: string, name: string, sku: string, category: string, price: number, quantity: number, currencyCode: string): Promise { return; } + addTransactionItem(id: string, name: string, sku: string, category: string, price: number, quantity: number, currencyCode: string): Promise { return; } /** * Enable/disable automatic reporting of uncaught exceptions @@ -203,6 +209,6 @@ export class GoogleAnalytics { * @returns {Promise} */ @Cordova() - static enableUncaughtExceptionReporting(shouldEnable: boolean): Promise { return; } + enableUncaughtExceptionReporting(shouldEnable: boolean): Promise { return; } } diff --git a/src/plugins/googlemap.ts b/src/@ionic-native/plugins/google-maps/index.ts similarity index 81% rename from src/plugins/googlemap.ts rename to src/@ionic-native/plugins/google-maps/index.ts index 4774ada98..c4ec9fab3 100644 --- a/src/plugins/googlemap.ts +++ b/src/@ionic-native/plugins/google-maps/index.ts @@ -1,11 +1,12 @@ -import { Cordova, CordovaInstance, Plugin, InstanceProperty, getPlugin, pluginWarn } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, CordovaInstance, CordovaCheck, Plugin, InstanceProperty, InstanceCheck, checkAvailability } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/fromEvent'; declare var plugin: any; /** - * @private + * @hidden * You can listen to these events where appropriate */ export const GoogleMapsEvent = { @@ -30,7 +31,7 @@ export const GoogleMapsEvent = { }; /** - * @private + * @hidden */ export const GoogleMapsAnimation = { BOUNCE: 'BOUNCE', @@ -38,7 +39,7 @@ export const GoogleMapsAnimation = { }; /** - * @private + * @hidden */ export const GoogleMapsMapTypeId = { HYBRID: 'MAP_TYPE_HYBRID', @@ -50,100 +51,21 @@ export const GoogleMapsMapTypeId = { }; /** - * @name Google Maps - * @description This plugin uses the native Google Maps SDK - * @usage - * ``` - * import { - * GoogleMap, - * GoogleMapsEvent, - * GoogleMapsLatLng, - * CameraPosition, - * GoogleMapsMarkerOptions, - * GoogleMapsMarker, - * GoogleMapsMapTypeId - * } from 'ionic-native'; - * - * export class MapPage { - * constructor() {} - * - * // Load map only after view is initialize - * ngAfterViewInit() { - * this.loadMap(); - * } - * - * loadMap() { - * // make sure to create following structure in your view.html file - * // and add a height (for example 100%) to it, else the map won't be visible - * // - * //
    - * //
    - * - * // create a new map by passing HTMLElement - * let element: HTMLElement = document.getElementById('map'); - * - * let map = new GoogleMap(element); - * - * // create LatLng object - * let ionic: GoogleMapsLatLng = new GoogleMapsLatLng(43.0741904,-89.3809802); - * - * // create CameraPosition - * let position: CameraPosition = { - * target: ionic, - * zoom: 18, - * tilt: 30 - * }; - * - * // listen to MAP_READY event - * map.one(GoogleMapsEvent.MAP_READY).then(() => { - * // move the map's camera to position - * map.moveCamera(position); // works on iOS and Android - * }); - * - * - * // create new marker - * let markerOptions: GoogleMapsMarkerOptions = { - * position: ionic, - * title: 'Ionic' - * }; - * - * map.addMarker(markerOptions) - * .then((marker: GoogleMapsMarker) => { - * marker.showInfoWindow(); - * }); - * } - * } - * ``` + * @hidden */ @Plugin({ - pluginName: 'GoogleMap', - pluginRef: 'plugin.google.maps.Map', - plugin: 'cordova-plugin-googlemaps', - repo: 'https://github.com/mapsplugin/cordova-plugin-googlemaps', - install: 'ionic plugin add cordova-plugin-googlemaps --variable API_KEY_FOR_ANDROID="YOUR_ANDROID_API_KEY_IS_HERE" --variable API_KEY_FOR_IOS="YOUR_IOS_API_KEY_IS_HERE"' + pluginName: 'GoogleMaps', + plugin: 'cordova-plugin-googlemaps' }) export class GoogleMap { _objectInstance: any; - /** - * Checks if a map object has been created and is available. - * - * @returns {Promise} - */ - @Cordova() - static isAvailable(): Promise { return; } - constructor(element: string | HTMLElement, options?: any) { - if (!!getPlugin('plugin.google.maps.Map')) { + if (checkAvailability('plugin.google.maps.Map', null, 'GoogleMaps') === true) { if (typeof element === 'string') { element = document.getElementById(element); } this._objectInstance = plugin.google.maps.Map.getMap(element, options); - } else { - pluginWarn({ - pluginName: 'GoogleMap', - plugin: 'plugin.google.maps.Map' - }); } } @@ -152,6 +74,7 @@ export class GoogleMap { * * @returns {Observable} */ + @InstanceCheck() addEventListener(eventName: string): Observable { return Observable.fromEvent(this._objectInstance, eventName); } @@ -161,13 +84,9 @@ export class GoogleMap { * * @returns {Promise} */ + @InstanceCheck() addListenerOnce(eventName: string): Promise { - if (!this._objectInstance) { - return Promise.reject({ error: 'plugin_not_installed' }); - } - return new Promise( - resolve => this._objectInstance.addListenerOnce(eventName, resolve) - ); + return new Promise(resolve => this._objectInstance.addListenerOnce(eventName, resolve)); } /** @@ -190,19 +109,9 @@ export class GoogleMap { * * @returns {Observable} */ + @InstanceCheck({ observable: true }) on(eventName: string): Observable { - if (!this._objectInstance) { - return new Observable((observer) => { - observer.error({ error: 'plugin_not_installed' }); - }); - } - - return new Observable( - (observer) => { - this._objectInstance.on(eventName, observer.next.bind(observer)); - return () => this._objectInstance.off(event); - } - ); + return Observable.fromEvent(this._objectInstance, eventName); } /** @@ -210,13 +119,9 @@ export class GoogleMap { * * @returns {Promise} */ + @InstanceCheck() one(eventName: string): Promise { - if (!this._objectInstance) { - return Promise.reject({ error: 'plugin_not_installed' }); - } - return new Promise( - resolve => this._objectInstance.one(eventName, resolve) - ); + return new Promise(resolve => this._objectInstance.one(eventName, resolve)); } /** @@ -265,7 +170,7 @@ export class GoogleMap { getLicenseInfo(): Promise { return; } @CordovaInstance({ sync: true }) - setCenter(latLng: GoogleMapsLatLng): void { } + setCenter(latLng: LatLng): void { } @CordovaInstance({ sync: true }) setZoom(zoomLevel: number): void { } @@ -304,143 +209,115 @@ export class GoogleMap { setAllGesturesEnabled(enabled: boolean): void { } /** - * @returns {Promise} + * @returns {Promise} */ - addMarker(options: GoogleMapsMarkerOptions): Promise { - if (!this._objectInstance) { - return Promise.reject({ error: 'plugin_not_installed' }); - } - return new Promise( - (resolve, reject) => { + @InstanceCheck() + addMarker(options: MarkerOptions): Promise { + return new Promise((resolve, reject) => { this._objectInstance.addMarker(options, (marker: any) => { if (marker) { - resolve(new GoogleMapsMarker(marker)); + resolve(new Marker(marker)); } else { reject(); } }); - } - ); + }); } /** - * @returns {Promise} + * @returns {Promise} */ - addCircle(options: GoogleMapsCircleOptions): Promise { - if (!this._objectInstance) { - return Promise.reject({ error: 'plugin_not_installed' }); - } - return new Promise( - (resolve, reject) => { + @InstanceCheck() + addCircle(options: CircleOptions): Promise { + return new Promise((resolve, reject) => { this._objectInstance.addCircle(options, (circle: any) => { if (circle) { - resolve(new GoogleMapsCircle(circle)); + resolve(new Circle(circle)); } else { reject(); } }); - } - ); + }); } /** - * @returns {Promise} + * @returns {Promise} */ - addPolygon(options: GoogleMapsPolygonOptions): Promise { - if (!this._objectInstance) { - return Promise.reject({ error: 'plugin_not_installed' }); - } - return new Promise( - (resolve, reject) => { + @InstanceCheck() + addPolygon(options: PolygonOptions): Promise { + return new Promise((resolve, reject) => { this._objectInstance.addPolygon(options, (polygon: any) => { if (polygon) { - resolve(new GoogleMapsPolygon(polygon)); + resolve(new Polygon(polygon)); } else { reject(); } }); - } - ); + }); } /** - * @returns {Promise} + * @returns {Promise} */ - addPolyline(options: GoogleMapsPolylineOptions): Promise { - if (!this._objectInstance) { - return Promise.reject({ error: 'plugin_not_installed' }); - } - return new Promise( - (resolve, reject) => { + @InstanceCheck() + addPolyline(options: PolylineOptions): Promise { + return new Promise((resolve, reject) => { this._objectInstance.addPolyline(options, (polyline: any) => { if (polyline) { - resolve(new GoogleMapsPolyline(polyline)); + resolve(new Polyline(polyline)); } else { reject(); } }); - } - ); + }); } /** - * @returns {Promise} + * @returns {Promise} */ - addTileOverlay(options: GoogleMapsTileOverlayOptions): Promise { - if (!this._objectInstance) { - return Promise.reject({ error: 'plugin_not_installed' }); - } - return new Promise( - (resolve, reject) => { + @InstanceCheck() + addTileOverlay(options: TileOverlayOptions): Promise { + return new Promise((resolve, reject) => { this._objectInstance.addTileOverlay(options, (tileOverlay: any) => { if (tileOverlay) { - resolve(new GoogleMapsTileOverlay(tileOverlay)); + resolve(new TileOverlay(tileOverlay)); } else { reject(); } }); - } - ); + }); } /** - * @returns {Promise} + * @returns {Promise} */ - addGroundOverlay(options: GoogleMapsGroundOverlayOptions): Promise { - if (!this._objectInstance) { - return Promise.reject({ error: 'plugin_not_installed' }); - } - return new Promise( - (resolve, reject) => { + @InstanceCheck() + addGroundOverlay(options: GroundOverlayOptions): Promise { + return new Promise((resolve, reject) => { this._objectInstance.addGroundOverlay(options, (groundOverlay: any) => { if (groundOverlay) { - resolve(new GoogleMapsGroundOverlay(groundOverlay)); + resolve(new GroundOverlay(groundOverlay)); } else { reject(); } }); - } - ); + }); } /** - * @returns {Promise} + * @returns {Promise} */ - addKmlOverlay(options: GoogleMapsKmlOverlayOptions): Promise { - if (!this._objectInstance) { - return Promise.reject({ error: 'plugin_not_installed' }); - } - return new Promise( - (resolve, reject) => { + @InstanceCheck() + addKmlOverlay(options: KmlOverlayOptions): Promise { + return new Promise((resolve, reject) => { this._objectInstance.addKmlOverlay(options, (kmlOverlay: any) => { if (kmlOverlay) { - resolve(new GoogleMapsKmlOverlay(kmlOverlay)); + resolve(new KmlOverlay(kmlOverlay)); } else { reject(); } }); - } - ); + }); } @CordovaInstance({ sync: true }) @@ -468,13 +345,13 @@ export class GoogleMap { * @returns {Promise} */ @CordovaInstance() - fromLatLngToPoint(latLng: GoogleMapsLatLng, point: any): Promise { return; } + fromLatLngToPoint(latLng: LatLng, point: any): Promise { return; } /** - * @returns {Promise} + * @returns {Promise} */ @CordovaInstance() - fromPointToLatLng(point: any, latLng: GoogleMapsLatLng): Promise { return; } + fromPointToLatLng(point: any, latLng: LatLng): Promise { return; } /** * @returns {Promise} @@ -487,14 +364,123 @@ export class GoogleMap { @CordovaInstance({ sync: true }) panBy(): void { } +} + +/** + * @name Google Maps + * @description This plugin uses the native Google Maps SDK + * @usage + * ``` + * import { + * GoogleMaps, + * GoogleMap, + * GoogleMapsEvent, + * LatLng, + * CameraPosition, + * MarkerOptions, + * Marker + * } from '@ionic-native/google-maps'; + * + * export class MapPage { + * constructor(private googleMaps: GoogleMaps) {} + * + * // Load map only after view is initialize + * ngAfterViewInit() { + * this.loadMap(); + * } + * + * loadMap() { + * // make sure to create following structure in your view.html file + * // and add a height (for example 100%) to it, else the map won't be visible + * // + * //
    + * //
    + * + * // create a new map by passing HTMLElement + * let element: HTMLElement = document.getElementById('map'); + * + * let map: GoogleMap = GoogleMaps.create(element); + * + * // listen to MAP_READY event + * // You must wait for this event to fire before adding something to the map or modifying it in anyway + * map.one(GoogleMapsEvent.MAP_READY).then(() => console.log('Map is ready!')); + * + * // create LatLng object + * let ionic: LatLng = new GoogleMapsLatLng(43.0741904,-89.3809802); + * + * // create CameraPosition + * let position: CameraPosition = { + * target: ionic, + * zoom: 18, + * tilt: 30 + * }; + * + * // move the map's camera to position + * map.moveCamera(position); + * + * // create new marker + * let markerOptions: MarkerOptions = { + * position: ionic, + * title: 'Ionic' + * }; + * + * const marker: Marker = map.addMarker(markerOptions) + * .then((marker: Marker) => { + * marker.showInfoWindow(); + * }); + * } + * + * } + * ``` + * @classes + * GoogleMap + * Marker + * LatLng + * Geocoder + * @interfaces + * AnimateCameraOptions + * MarkerOptions + * MyLocation + * MyLocationOptions + * VisibleRegion + * + */ +@Plugin({ + pluginName: 'GoogleMaps', + pluginRef: 'plugin.google.maps.Map', + plugin: 'cordova-plugin-googlemaps', + repo: 'https://github.com/mapsplugin/cordova-plugin-googlemaps', + install: 'ionic plugin add cordova-plugin-googlemaps --variable API_KEY_FOR_ANDROID="YOUR_ANDROID_API_KEY_IS_HERE" --variable API_KEY_FOR_IOS="YOUR_IOS_API_KEY_IS_HERE"', + installVariables: ['API_KEY_FOR_ANDROID', 'API_KEY_FOR_IOS'] +}) +@Injectable() +export class GoogleMaps { + + /** + * Checks if a map object has been created and is available. + * + * @returns {Promise} + */ + @Cordova() + isAvailable(): Promise { return; } + + /** + * Creates a new GoogleMap instance + * @param element {string | HTMLElement} Element ID or reference to attach the map to + * @param options {any} Options + * @returns {GoogleMap} + */ + create(element: string | HTMLElement, options?: any): GoogleMap { + return new GoogleMap(element, options); + } } /** - * @private + * @hidden */ export interface AnimateCameraOptions { - target?: GoogleMapsLatLng | Array | GoogleMapsLatLngBounds; + target?: LatLng | Array | LatLngBounds; tilt?: number; zoom?: number; bearing?: number; @@ -502,34 +488,34 @@ export interface AnimateCameraOptions { } /** - * @private + * @hidden */ export interface CameraPosition { - target?: GoogleMapsLatLng | GoogleMapsLatLngBounds | GoogleMapsLatLng[]; + target?: LatLng | LatLngBounds | LatLng[]; zoom?: number; tilt?: number; bearing?: number; } /** - * @private + * @hidden */ export interface MyLocation { - latLng?: GoogleMapsLatLng; + latLng?: LatLng; speed?: number; time?: string; bearing?: number; } /** - * @private + * @hidden */ export interface MyLocationOptions { enableHighAccuracy?: boolean; } /** - * @private + * @hidden */ export interface VisibleRegion { northeast?: any; @@ -537,9 +523,9 @@ export interface VisibleRegion { } /** - * @private + * @hidden */ -export interface GoogleMapsMarkerOptions { +export interface MarkerOptions { /** * The icon image url or properties. Also you can specify HTML Color values. Alternatively you can specify the image as Base64 */ @@ -558,7 +544,7 @@ export interface GoogleMapsMarkerOptions { /** * The position of the marker. */ - position?: GoogleMapsLatLng; + position?: LatLng; /** * Specify the anchor of the InfoWindow @@ -617,9 +603,9 @@ export interface GoogleMapsMarkerOptions { } /** - * @private + * @hidden */ -export interface GoogleMapsMarkerIcon { +export interface MarkerIcon { url?: string; size?: { width?: number; @@ -628,9 +614,9 @@ export interface GoogleMapsMarkerIcon { } /** - * @private + * @hidden */ -export class GoogleMapsMarker { +export class Marker { constructor(private _objectInstance: any) { } @@ -801,7 +787,7 @@ export class GoogleMapsMarker { * @param icon */ @CordovaInstance({ sync: true }) - setIcon(icon: GoogleMapsMarkerIcon): void { return; } + setIcon(icon: MarkerIcon): void { return; } /** * Change title of the infoWindow. @@ -864,14 +850,14 @@ export class GoogleMapsMarker { * @param latLng {GoogleMapLatLng} */ @CordovaInstance({ sync: true }) - setPosition(latLng: GoogleMapsLatLng): void { return; } + setPosition(latLng: LatLng): void { return; } /** * Return the marker position. * @return {Promise} */ @CordovaInstance() - getPosition(): Promise { return; } + getPosition(): Promise { return; } /** * Return the map instance. @@ -890,10 +876,10 @@ export class GoogleMapsMarker { } /** - * @private + * @hidden */ -export interface GoogleMapsCircleOptions { - center?: GoogleMapsLatLng; +export interface CircleOptions { + center?: LatLng; radius?: number; strokeColor?: string; strokeWidth?: number; @@ -903,9 +889,10 @@ export interface GoogleMapsCircleOptions { } /** - * @private + * @hidden */ -export class GoogleMapsCircle { + +export class Circle { constructor(private _objectInstance: any) { } @@ -988,7 +975,7 @@ export class GoogleMapsCircle { empty(): void { } @CordovaInstance({ sync: true }) - getCenter(): GoogleMapsLatLng { return; } + getCenter(): LatLng { return; } @CordovaInstance({ sync: true }) getRadius(): number { return; } @@ -1006,7 +993,7 @@ export class GoogleMapsCircle { remove(): void { } @CordovaInstance({ sync: true }) - setCenter(latLng: GoogleMapsLatLng): void { } + setCenter(latLng: LatLng): void { } @CordovaInstance({ sync: true }) setFillColor(fillColor: string): void { } @@ -1031,10 +1018,10 @@ export class GoogleMapsCircle { } /** - * @private + * @hidden */ -export interface GoogleMapsPolylineOptions { - points?: Array; +export interface PolylineOptions { + points?: Array; visible?: boolean; geodesic?: boolean; color?: string; @@ -1043,9 +1030,10 @@ export interface GoogleMapsPolylineOptions { } /** - * @private + * @hidden */ -export class GoogleMapsPolyline { + +export class Polyline { constructor(private _objectInstance: any) { } /** @@ -1127,7 +1115,7 @@ export class GoogleMapsPolyline { empty(): void { } @CordovaInstance({ sync: true }) - getPoints(): Array { return; } + getPoints(): Array { return; } @CordovaInstance({ sync: true }) getCOlor(): string { return; } @@ -1145,7 +1133,7 @@ export class GoogleMapsPolyline { remove(): void { } @CordovaInstance({ sync: true }) - setPoints(points: Array): void { } + setPoints(points: Array): void { } @CordovaInstance({ sync: true }) setColor(color: string): void { } @@ -1168,23 +1156,24 @@ export class GoogleMapsPolyline { } /** - * @private + * @hidden */ -export interface GoogleMapsPolygonOptions { - points?: Array; +export interface PolygonOptions { + points?: Array; geodesic?: boolean; strokeColor?: string; strokeWidth?: number; fillColor?: string; visible?: boolean; zIndex?: number; - addHole?: Array; + addHole?: Array; } /** - * @private + * @hidden */ -export class GoogleMapsPolygon { + +export class Polygon { constructor(private _objectInstance: any) { } @@ -1267,7 +1256,7 @@ export class GoogleMapsPolygon { empty(): void { } @CordovaInstance({ sync: true }) - getPoints(): Array { return; } + getPoints(): Array { return; } @CordovaInstance({ sync: true }) getStrokeColor(): string { return; } @@ -1291,7 +1280,7 @@ export class GoogleMapsPolygon { remove(): void { } @CordovaInstance({ sync: true }) - setPoints(points: Array): void { } + setPoints(points: Array): void { } @CordovaInstance({ sync: true }) setStrokeColor(strokeColor: string): void { } @@ -1313,9 +1302,9 @@ export class GoogleMapsPolygon { } /** - * @private + * @hidden */ -export interface GoogleMapsTileOverlayOptions { +export interface TileOverlayOptions { tileUrlFormat?: string; visible?: boolean; zIndex?: number; @@ -1324,9 +1313,9 @@ export interface GoogleMapsTileOverlayOptions { } /** - * @private + * @hidden */ -export class GoogleMapsTileOverlay { +export class TileOverlay { constructor(private _objectInstance: any) { } @@ -1441,11 +1430,11 @@ export class GoogleMapsTileOverlay { } /** - * @private + * @hidden */ -export interface GoogleMapsGroundOverlayOptions { +export interface GroundOverlayOptions { url?: string; - bounds?: Array; + bounds?: Array; visible?: boolean; opacity?: number; bearing?: number; @@ -1453,9 +1442,9 @@ export interface GoogleMapsGroundOverlayOptions { } /** - * @private + * @hidden */ -export class GoogleMapsGroundOverlay { +export class GroundOverlay { constructor(private _objectInstance: any) { } @@ -1564,18 +1553,18 @@ export class GoogleMapsGroundOverlay { } /** - * @private + * @hidden */ -export interface GoogleMapsKmlOverlayOptions { +export interface KmlOverlayOptions { url?: string; preserveViewport?: boolean; animation?: boolean; } /** - * @private + * @hidden */ -export class GoogleMapsKmlOverlay { +export class KmlOverlay { constructor(private _objectInstance: any) { } @@ -1661,20 +1650,20 @@ export class GoogleMapsKmlOverlay { remove(): void { } @CordovaInstance({ sync: true }) - getOverlays(): Array { return; } + getOverlays(): Array { return; } } /** - * @private + * @hidden */ -export class GoogleMapsLatLngBounds { +export class LatLngBounds { private _objectInstance: any; - @InstanceProperty northeast: GoogleMapsLatLng; - @InstanceProperty southwest: GoogleMapsLatLng; + @InstanceProperty northeast: LatLng; + @InstanceProperty southwest: LatLng; @InstanceProperty type: string; - constructor(southwestOrArrayOfLatLng: GoogleMapsLatLng | GoogleMapsLatLng[], northeast?: GoogleMapsLatLng) { + constructor(southwestOrArrayOfLatLng: LatLng | LatLng[], northeast?: LatLng) { let args = !!northeast ? [southwestOrArrayOfLatLng, northeast] : southwestOrArrayOfLatLng; this._objectInstance = new plugin.google.maps.LatLngBounds(args); } @@ -1686,19 +1675,20 @@ export class GoogleMapsLatLngBounds { toUrlValue(precision?: number): string { return; } @CordovaInstance({ sync: true }) - extend(LatLng: GoogleMapsLatLng): void { } + extend(LatLng: LatLng): void { } @CordovaInstance({ sync: true }) - contains(LatLng: GoogleMapsLatLng): boolean { return; } + contains(LatLng: LatLng): boolean { return; } @CordovaInstance({ sync: true }) - getCenter(): GoogleMapsLatLng { return; } + getCenter(): LatLng { return; } } /** - * @private + * @hidden */ -export class GoogleMapsLatLng { + +export class LatLng { lat: number; lng: number; @@ -1708,7 +1698,7 @@ export class GoogleMapsLatLng { this.lng = lng; } - equals(other: GoogleMapsLatLng): boolean { + equals(other: LatLng): boolean { return this.lat === other.lat && this.lng === other.lng; } @@ -1723,15 +1713,15 @@ export class GoogleMapsLatLng { } } /** - * @private + * @hidden */ export interface GeocoderRequest { address?: string; - bounds?: GoogleMapsLatLng[]; + bounds?: LatLng[]; position?: { lat: number; lng: number }; } /** - * @private + * @hidden */ export interface GeocoderResult { adminArea?: string; @@ -1754,25 +1744,24 @@ export interface GeocoderResult { thoroughfare?: string; } /** - * @private + * @hidden */ +@Plugin({ + pluginName: 'Geocoder', + pluginRef: 'plugins.google.maps.Geocoder', + plugin: 'cordova-plugin-googlemaps', + repo: '' +}) export class Geocoder { /** * Converts position to address and vice versa * @param {GeocoderRequest} request Request object with either an address or a position * @returns {Promise} */ - static geocode(request: GeocoderRequest): Promise { - return new Promise((resolve, reject) => { - if (!plugin || !plugin.google || !plugin.google.maps || !plugin.google.maps.Geocoder) { - pluginWarn({ - pluginName: 'GoogleMap', - plugin: 'plugin.google.maps.Map' - }); - reject({ error: 'plugin_not_installed' }); - } else { - plugin.google.maps.Geocoder.geocode(request, resolve); - } + @CordovaCheck() + geocode(request: GeocoderRequest): Promise { + return new Promise(resolve => { + plugin.google.maps.Geocoder.geocode(request, resolve); }); } } diff --git a/src/plugins/google-plus.ts b/src/@ionic-native/plugins/google-plus/index.ts similarity index 71% rename from src/plugins/google-plus.ts rename to src/@ionic-native/plugins/google-plus/index.ts index 4f439ff44..0d6457b7c 100644 --- a/src/plugins/google-plus.ts +++ b/src/@ionic-native/plugins/google-plus/index.ts @@ -1,13 +1,18 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; /** * @name Google Plus * @description * @usage * ```typescript - * import { GooglePlus } from 'ionic-native'; + * import { GooglePlus } from '@ionic-native/google-plus'; * - * GooglePlus.login() + * constructor(private googlePlus: GooglePlus) { } + * + * ... + * + * this.googlePlus.login() * .then(res => console.log(res)) * .catch(err => console.error(err)); * @@ -19,8 +24,10 @@ import { Cordova, Plugin } from './plugin'; pluginRef: 'window.plugins.googleplus', repo: 'https://github.com/EddyVerbruggen/cordova-plugin-googleplus', platforms: ['Web', 'Android', 'iOS'], - install: 'ionic plugin add cordova-plugin-googleplus --variable REVERSED_CLIENT_ID=myreversedclientid' + install: 'ionic plugin add cordova-plugin-googleplus --variable REVERSED_CLIENT_ID=myreversedclientid', + installVariables: ['REVERSED_CLIENT_ID'] }) +@Injectable() export class GooglePlus { /** @@ -32,7 +39,7 @@ export class GooglePlus { successIndex: 1, errorIndex: 2 }) - static login(options?: any): Promise { return; } + login(options?: any): Promise { return; } /** * You can call trySilentLogin to check if they're already signed in to the app and sign them in silently if they are. @@ -40,20 +47,20 @@ export class GooglePlus { * @returns {Promise} */ @Cordova() - static trySilentLogin(options?: any): Promise { return; } + trySilentLogin(options?: any): Promise { return; } /** * This will clear the OAuth2 token. * @returns {Promise} */ @Cordova() - static logout(): Promise { return; } + logout(): Promise { return; } /** * This will clear the OAuth2 token, forget which account was used to login, and disconnect that account from the app. This will require the user to allow the app access again next time they sign in. Be aware that this effect is not always instantaneous. It can take time to completely disconnect. * @returns {Promise} */ @Cordova() - static disconnect(): Promise { return; } + disconnect(): Promise { return; } } diff --git a/src/@ionic-native/plugins/gyroscope/index.ts b/src/@ionic-native/plugins/gyroscope/index.ts new file mode 100644 index 000000000..605d25ef2 --- /dev/null +++ b/src/@ionic-native/plugins/gyroscope/index.ts @@ -0,0 +1,109 @@ +import { Plugin, Cordova } from '@ionic-native/core'; +import { Observable } from 'rxjs/Observable'; +import { Injectable } from '@angular/core'; + +declare var navigator: any; + +/** + * @hidden + */ +export interface GyroscopeOrientation { + /** + * Represent x-axis + */ + x: number; + + /** + * Represent y-axis + */ + y: number; + + /** + * Represent z-axis + */ + z: number; + + /** + * Represent timestamp of sensor read. Default is 10000ms + */ + timestamp: number; +} + +/** + * @hidden + */ +export interface GyroscopeOptions { + /** + * Represent how often (in milliseconds) sensor should be read. Default is 10000 ms + */ + frequency: number; +} + +/** + * @name Gyroscope + * @description Read Gyroscope sensor data + * @usage + * ``` + * import { Gyroscope, GyroscopeOrientation, GyroscopeOptions } from '@ionic-native/gyroscope'; + * + * + * constructor(private gyroscope: Gyroscope) { } + * + * ... + * + * + * let options: GyroscopeOptions = { + * frequency: 1000 + * }; + * + * this.gyroscope.getCurrent(options) + * .then((orientation: GyroscopeOrientation) => { + * console.log(orientation.x, orientation.y, orientation.z, orientation.timestamp); + * }) + * .catch() + * + * + * this.gyroscope.watch() + * .subscribe((orientation: GyroscopeOrientation) => { + * console.log(orientation.x, orientation.y, orientation.z, orientation.timestamp); + * }); + * + * ``` + * @interfaces + * GyroscopeOrientation + * GyroscopeOptions + */ +@Plugin({ + pluginName: 'Gyroscope', + plugin: 'cordova-plugin-gyroscope', + pluginRef: 'navigator.gyroscope', + repo: 'https://github.com/NeoLSN/cordova-plugin-gyroscope', + platforms: ['Android', 'iOS'] +}) +@Injectable() +export class Gyroscope { + + /** + * Watching for gyroscope sensor changes + * @param options {GyroscopeOptions} (optional) + * @return {Observable} Returns an Observable that resolves GyroscopeOrientation + */ + watch(options?: GyroscopeOptions): Observable { + return new Observable ( + (observer: any) => { + let watchId = navigator.gyroscope.watch(observer.next.bind(observer), observer.next.bind(observer), options); + return () => navigator.gyroscope.clearWatch(watchId); + } + ); + } + + /** + * Get current data from gyroscope sensor + * @param options {GyroscopeOptions} (optional) + * @return {Promise} Returns a promise that resolves GyroscopeOrientation + */ + @Cordova({ + callbackOrder: 'reverse' + }) + getCurrent(options?: GyroscopeOptions): Promise { return; } +} diff --git a/src/plugins/headercolor.ts b/src/@ionic-native/plugins/header-color/index.ts similarity index 63% rename from src/plugins/headercolor.ts rename to src/@ionic-native/plugins/header-color/index.ts index b7d5362db..9201de3b4 100644 --- a/src/plugins/headercolor.ts +++ b/src/@ionic-native/plugins/header-color/index.ts @@ -1,15 +1,20 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; /** - * @name HeaderColor + * @name Header Color * @description * Cordova plugin to change color of header in multitask view * * @usage * ```typescript - * import { HeaderColor } from 'ionic-native'; + * import { HeaderColor } from '@ionic-native/header-color'; * - * HeaderColor.tint("#becb29"); + * constructor(private headerColor: HeaderColor) { } + * + * ... + * + * this.headerColor.tint("#becb29"); * ``` */ @Plugin({ @@ -19,6 +24,7 @@ import { Plugin, Cordova } from './plugin'; repo: 'https://github.com/tomloprod/cordova-plugin-headercolor', platforms: ['Android'] }) +@Injectable() export class HeaderColor { /** @@ -31,6 +37,6 @@ export class HeaderColor { successName: 'success', errorName: 'failure' }) - static tint(color: string): Promise { return; } + tint(color: string): Promise { return; } } diff --git a/src/plugins/health.ts b/src/@ionic-native/plugins/health/index.ts similarity index 90% rename from src/plugins/health.ts rename to src/@ionic-native/plugins/health/index.ts index 25cadef7b..58bbe6f55 100644 --- a/src/plugins/health.ts +++ b/src/@ionic-native/plugins/health/index.ts @@ -1,5 +1,9 @@ -import {Plugin, Cordova} from './plugin'; +import { Plugin, Cordova } from '@ionic-native/core'; +import { Injectable } from '@angular/core'; +/** + * @hidden + */ export interface HealthQueryOptions { /** * Start date from which to get data @@ -33,6 +37,9 @@ export interface HealthQueryOptions { filtered?: boolean; } +/** + * @hidden + */ export interface HealthQueryOptionsAggregated { /** * Start date from which to get data @@ -56,6 +63,9 @@ export interface HealthQueryOptionsAggregated { bucket: string; } +/** + * @hidden + */ export interface HealthStoreOptions { /** * Start date from which to get data @@ -77,13 +87,13 @@ export interface HealthStoreOptions { */ value: string; - /* + /** * The source that produced this data. In iOS this is ignored and * set automatically to the name of your app. */ sourceName: string; - /* + /** * The complete package of the source that produced this data. * In Android, if not specified, it's assigned to the package of the App. In iOS this is ignored and * set automatically to the bunde id of the app. @@ -91,6 +101,9 @@ export interface HealthStoreOptions { sourceBundleId: string; } +/** + * @hidden + */ export interface HealthData { /** * Start date from which to get data @@ -133,17 +146,28 @@ export interface HealthData { * * @usage * ``` - * import { Health } from 'ionic-native'; + * import { Health } from '@ionic-native/health'; + * + * + * constructor(private health: Health) { } + * + * ... + * + * this.health.isAvailable() + * .then(res => console.log(res)) + * .catch(e => console.log(e)); + * * * ``` * See description at https://github.com/dariosalvi78/cordova-plugin-health for a full list of Datatypes and see examples. + * * @interfaces * HealthQueryOptions * HealthQueryOptionsAggregated * HealthStoreOptions * HealthData */ - +@Injectable() @Plugin({ pluginName: 'Health', plugin: 'cordova-plugin-health', @@ -160,9 +184,7 @@ export class Health { @Cordova({ callbackOrder: 'reverse' }) - static isAvailable(): Promise { - return; - }; + isAvailable(): Promise { return; } /** * Checks if recent Google Play Services and Google Fit are installed. If the play services are not installed, @@ -178,9 +200,7 @@ export class Health { @Cordova({ callbackOrder: 'reverse' }) - static promptInstallFit(): Promise { - return; - }; + promptInstallFit(): Promise { return; } /** * Requests read and write access to a set of data types. It is recommendable to always explain why the app @@ -203,21 +223,17 @@ export class Health { * @return {Promise} */ @Cordova() - static requestAuthorization(datatypes: Array): Promise { - return; - }; + requestAuthorization(datatypes: Array): Promise { return; } /** * Check if the app has authorization to read/write a set of datatypes. * This function is similar to requestAuthorization() and has similar quirks. * * @param {Array} datatypes a list of data types you want to be granted access to - * @return {Promise} + * @return {Promise} Returns a promise that resolves with a boolean that indicates the authorization status */ @Cordova() - static isAuthorized(datatypes: Array): Promise { - return; - }; + isAuthorized(datatypes: Array): Promise { return; } /** * Gets all the data points of a certain data type within a certain time window. @@ -251,9 +267,7 @@ export class Health { * @return {Promise} */ @Cordova() - static query(queryOptions: HealthQueryOptions): Promise { - return; - }; + query(queryOptions: HealthQueryOptions): Promise { return; } /** * Gets aggregated data in a certain time window. Usually the sum is returned for the given quantity. @@ -277,9 +291,7 @@ export class Health { * @return {Promise} */ @Cordova() - static queryAggregated(queryOptionsAggregated: HealthQueryOptionsAggregated): Promise { - return; - }; + queryAggregated(queryOptionsAggregated: HealthQueryOptionsAggregated): Promise { return; } /** * Stores a data point. @@ -296,8 +308,6 @@ export class Health { * @return {Promise} */ @Cordova() - static store(storeOptions: HealthStoreOptions): Promise { - return; - }; + store(storeOptions: HealthStoreOptions): Promise { return; } } diff --git a/src/plugins/hotspot.ts b/src/@ionic-native/plugins/hotspot/index.ts similarity index 75% rename from src/plugins/hotspot.ts rename to src/@ionic-native/plugins/hotspot/index.ts index 719970a7c..2df8ed495 100644 --- a/src/plugins/hotspot.ts +++ b/src/@ionic-native/plugins/hotspot/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; export interface HotspotConnectionInfo { @@ -89,13 +90,11 @@ export interface HotspotNetworkConfig { export interface HotspotDevice { /** - * ip * Hotspot IP Address */ ip: string; /** - * mac * Hotspot MAC Address */ mac: string; @@ -108,10 +107,14 @@ export interface HotspotDevice { * @description * @usage * ```typescript - * import { Hotspot, Network } from 'ionic-native'; + * import { Hotspot, HotspotNetwork } from '@ionic-native/hotspot'; + * + * constructor(private hotspot: Hotspot) { } + * + * ... * * - * Hotspot.scanWifi().then((networks: Array) => { + * this.hotspot.scanWifi().then((networks: Array) => { * console.log(networks); * }); * @@ -129,19 +132,20 @@ export interface HotspotDevice { repo: 'https://github.com/hypery2k/cordova-hotspot-plugin', platforms: ['Android'] }) +@Injectable() export class Hotspot { /** * @returns {Promise} */ @Cordova() - static isAvailable(): Promise { return; } + isAvailable(): Promise { return; } /** * @returns {Promise} */ @Cordova() - static toggleWifi(): Promise { return; } + toggleWifi(): Promise { return; } /** * Configures and starts hotspot with SSID and Password @@ -153,7 +157,7 @@ export class Hotspot { * @returns {Promise} - Promise to call once hotspot is started, or reject upon failure */ @Cordova() - static createHotspot(ssid: string, mode: string, password: string): Promise { return; } + createHotspot(ssid: string, mode: string, password: string): Promise { return; } /** * Turns on Access Point @@ -161,7 +165,7 @@ export class Hotspot { * @returns {Promise} - true if AP is started */ @Cordova() - static startHotspot(): Promise { return; } + startHotspot(): Promise { return; } /** * Configures hotspot with SSID and Password @@ -173,7 +177,7 @@ export class Hotspot { * @returns {Promise} - Promise to call when hotspot is configured, or reject upon failure */ @Cordova() - static configureHotspot(ssid: string, mode: string, password: string): Promise { return; } + configureHotspot(ssid: string, mode: string, password: string): Promise { return; } /** * Turns off Access Point @@ -181,7 +185,7 @@ export class Hotspot { * @returns {Promise} - Promise to turn off the hotspot, true on success, false on failure */ @Cordova() - static stopHotspot(): Promise { return; } + stopHotspot(): Promise { return; } /** * Checks if hotspot is enabled @@ -189,13 +193,13 @@ export class Hotspot { * @returns {Promise} - Promise that hotspot is enabled, rejected if it is not enabled */ @Cordova() - static isHotspotEnabled(): Promise { return; } + isHotspotEnabled(): Promise { return; } /** * @returns {Promise>} */ @Cordova() - static getAllHotspotDevices(): Promise> { return; } + getAllHotspotDevices(): Promise> { return; } /** * Connect to a WiFi network @@ -209,7 +213,7 @@ export class Hotspot { * Promise that connection to the WiFi network was successfull, rejected if unsuccessful */ @Cordova() - static connectToWifi(ssid: string, password: string): Promise { return; } + connectToWifi(ssid: string, password: string): Promise { return; } /** * Connect to a WiFi network @@ -227,7 +231,7 @@ export class Hotspot { * Promise that connection to the WiFi network was successfull, rejected if unsuccessful */ @Cordova() - static connectToWifiAuthEncrypt(ssid: string, password: string, authentication: string, encryption: Array): Promise { return; } + connectToWifiAuthEncrypt(ssid: string, password: string, authentication: string, encryption: Array): Promise { return; } /** * Add a WiFi network @@ -243,7 +247,7 @@ export class Hotspot { * Promise that adding the WiFi network was successfull, rejected if unsuccessful */ @Cordova() - static addWifiNetwork(ssid: string, mode: string, password: string): Promise { return; } + addWifiNetwork(ssid: string, mode: string, password: string): Promise { return; } /** * Remove a WiFi network @@ -255,79 +259,79 @@ export class Hotspot { * Promise that removing the WiFi network was successfull, rejected if unsuccessful */ @Cordova() - static removeWifiNetwork(ssid: string): Promise { return; } + removeWifiNetwork(ssid: string): Promise { return; } /** * @returns {Promise} */ @Cordova() - static isConnectedToInternet(): Promise { return; } + isConnectedToInternet(): Promise { return; } /** * @returns {Promise} */ @Cordova() - static isConnectedToInternetViaWifi(): Promise { return; } + isConnectedToInternetViaWifi(): Promise { return; } /** * @returns {Promise} */ @Cordova() - static isWifiOn(): Promise { return; } + isWifiOn(): Promise { return; } /** * @returns {Promise} */ @Cordova() - static isWifiSupported(): Promise { return; } + isWifiSupported(): Promise { return; } /** * @returns {Promise} */ @Cordova() - static isWifiDirectSupported(): Promise { return; } + isWifiDirectSupported(): Promise { return; } /** * @returns {Promise>} */ @Cordova() - static scanWifi(): Promise> { return; } + scanWifi(): Promise> { return; } /** * @returns {Promise>} */ @Cordova() - static scanWifiByLevel(): Promise> { return; } + scanWifiByLevel(): Promise> { return; } /** * @returns {Promise} */ @Cordova() - static startWifiPeriodicallyScan(interval: number, duration: number): Promise { return; } + startWifiPeriodicallyScan(interval: number, duration: number): Promise { return; } /** * @returns {Promise} */ @Cordova() - static stopWifiPeriodicallyScan(): Promise { return; } + stopWifiPeriodicallyScan(): Promise { return; } /** * @returns {Promise} */ @Cordova() - static getNetConfig(): Promise { return; } + getNetConfig(): Promise { return; } /** * @returns {Promise} */ @Cordova() - static getConnectionInfo(): Promise { return; } + getConnectionInfo(): Promise { return; } /** * @returns {Promise} */ @Cordova() - static pingHost(ip: string): Promise { return; } + pingHost(ip: string): Promise { return; } /** * Gets MAC Address associated with IP Address from ARP File @@ -337,7 +341,7 @@ export class Hotspot { * @returns {Promise} - A Promise for the MAC Address */ @Cordova() - static getMacAddressOfHost(ip: string): Promise { return; } + getMacAddressOfHost(ip: string): Promise { return; } /** * Checks if IP is live using DNS @@ -347,7 +351,7 @@ export class Hotspot { * @returns {Promise} - A Promise for whether the IP Address is reachable */ @Cordova() - static isDnsLive(ip: string): Promise { return; } + isDnsLive(ip: string): Promise { return; } /** * Checks if IP is live using socket And PORT @@ -357,7 +361,7 @@ export class Hotspot { * @returns {Promise} - A Promise for whether the IP Address is reachable */ @Cordova() - static isPortLive(ip: string): Promise { return; } + isPortLive(ip: string): Promise { return; } /** * Checks if device is rooted @@ -365,6 +369,6 @@ export class Hotspot { * @returns {Promise} - A Promise for whether the device is rooted */ @Cordova() - static isRooted(): Promise { return; } + isRooted(): Promise { return; } } diff --git a/src/plugins/http.ts b/src/@ionic-native/plugins/http/index.ts similarity index 82% rename from src/plugins/http.ts rename to src/@ionic-native/plugins/http/index.ts index a5bb8c478..8b1d1acf1 100644 --- a/src/plugins/http.ts +++ b/src/@ionic-native/plugins/http/index.ts @@ -1,4 +1,5 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; export interface HTTPResponse { /** @@ -30,9 +31,13 @@ export interface HTTPResponse { * * @usage * ``` - * import { HTTP } from 'ionic-native'; + * import { HTTP } from '@ionic-native/http'; * - * HTTP.get('http://ionic.io', {}, {}) + * constructor(private http: HTTP) { } + * + * ... + * + * this.http.get('http://ionic.io', {}, {}) * .then(data => { * * console.log(data.status); @@ -59,6 +64,7 @@ export interface HTTPResponse { repo: 'https://github.com/wymsee/cordova-HTTP', platforms: ['Android', 'iOS'] }) +@Injectable() export class HTTP { /** @@ -68,7 +74,7 @@ export class HTTP { * @returns {Object} an object representing a basic HTTP Authorization header of the form {'Authorization': 'Basic base64encodedusernameandpassword'} */ @Cordova({ sync: true }) - static getBasicAuthHeader(username: string, password: string): { Authorization: string; } { return; } + getBasicAuthHeader(username: string, password: string): { Authorization: string; } { return; } /** * This sets up all future requests to use Basic HTTP authentication with the given username and password. @@ -76,7 +82,7 @@ export class HTTP { * @param password {string} Password */ @Cordova({ sync: true }) - static useBasicAuth(username: string, password: string): void { } + useBasicAuth(username: string, password: string): void { } /** * Set a header for all future requests. Takes a header and a value. @@ -84,7 +90,7 @@ export class HTTP { * @param value {string} The value of the header */ @Cordova({ sync: true }) - static setHeader(header: string, value: string): void { } + setHeader(header: string, value: string): void { } /** * Enable or disable SSL Pinning. This defaults to false. @@ -96,7 +102,7 @@ export class HTTP { * @returns {Promise} returns a promise that will resolve on success, and reject on failure */ @Cordova() - static enableSSLPinning(enable: boolean): Promise { return; } + enableSSLPinning(enable: boolean): Promise { return; } /** * Accept all SSL certificates. Or disabled accepting all certificates. Defaults to false. @@ -104,7 +110,7 @@ export class HTTP { * @returns {Promise} returns a promise that will resolve on success, and reject on failure */ @Cordova() - static acceptAllCerts(accept: boolean): Promise { return; } + acceptAllCerts(accept: boolean): Promise { return; } /** * Whether or not to validate the domain name in the certificate. This defaults to true. @@ -112,7 +118,7 @@ export class HTTP { * @returns {Promise} returns a promise that will resolve on success, and reject on failure */ @Cordova() - static validateDomainName(validate: boolean): Promise { return; } + validateDomainName(validate: boolean): Promise { return; } /** * Make a POST request @@ -122,7 +128,7 @@ export class HTTP { * @returns {Promise} returns a promise that resolve on success, and reject on failure */ @Cordova() - static post(url: string, body: any, headers: any): Promise { return; } + post(url: string, body: any, headers: any): Promise { return; } /** * @@ -132,7 +138,7 @@ export class HTTP { * @returns {Promise} returns a promise that resolve on success, and reject on failure */ @Cordova() - static get(url: string, parameters: any, headers: any): Promise { return; } + get(url: string, parameters: any, headers: any): Promise { return; } /** * @@ -144,7 +150,7 @@ export class HTTP { * @returns {Promise} returns a promise that resolve on success, and reject on failure */ @Cordova() - static uploadFile(url: string, body: any, headers: any, filePath: string, name: string): Promise { return; } + uploadFile(url: string, body: any, headers: any, filePath: string, name: string): Promise { return; } /** * @@ -155,5 +161,5 @@ export class HTTP { * @returns {Promise} returns a promise that resolve on success, and reject on failure */ @Cordova() - static downloadFile(url: string, body: any, headers: any, filePath: string): Promise { return; } + downloadFile(url: string, body: any, headers: any, filePath: string): Promise { return; } } diff --git a/src/plugins/httpd.ts b/src/@ionic-native/plugins/httpd/index.ts similarity index 79% rename from src/plugins/httpd.ts rename to src/@ionic-native/plugins/httpd/index.ts index 919477429..a9aae1ff7 100644 --- a/src/plugins/httpd.ts +++ b/src/@ionic-native/plugins/httpd/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; export interface HttpdOptions { @@ -25,7 +26,12 @@ export interface HttpdOptions { * Embedded httpd for Cordova apps. Light weight HTTP server. * @usage * ```typescript - * import {Httpd, HttpdOptions} from 'ionic-native'; + * import { Httpd, HttpdOptions } from '@ionic-native/httpd'; + * + * constructor(private httpd: Httpd) { } + * + * ... + * * * let options: HttpdOptions = { * www_root: 'httpd_root', // relative path to app's www directory @@ -33,7 +39,7 @@ export interface HttpdOptions { * localhost_only: false * }; * - * Httpd.startServer(options).subscribe((data) => { + * this.httpd.startServer(options).subscribe((data) => { * console.log('Server is live'); * }); * @@ -48,6 +54,7 @@ export interface HttpdOptions { repo: 'https://github.com/floatinghotpot/cordova-httpd', platforms: ['iOS', 'Android'] }) +@Injectable() export class Httpd { /** @@ -59,21 +66,20 @@ export class Httpd { observable: true, clearFunction: 'stopServer' }) - static startServer(options?: HttpdOptions): Observable { return; } + startServer(options?: HttpdOptions): Observable { return; } /** * Gets the URL of the running server * @returns {Promise} Returns a promise that resolves with the URL of the web server. */ @Cordova() - static getUrl(): Promise { return; } + getUrl(): Promise { return; } /** * Get the local path of the running webserver * @returns {Promise} Returns a promise that resolves with the local path of the web server. */ @Cordova() - static getLocalPath(): Promise { return; } + getLocalPath(): Promise { return; } } - diff --git a/src/plugins/ibeacon.ts b/src/@ionic-native/plugins/ibeacon/index.ts similarity index 90% rename from src/plugins/ibeacon.ts rename to src/@ionic-native/plugins/ibeacon/index.ts index 3bb2ce831..da29385f8 100644 --- a/src/plugins/ibeacon.ts +++ b/src/@ionic-native/plugins/ibeacon/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin, CordovaCheck } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; declare var cordova: any; @@ -231,13 +232,17 @@ export interface IBeaconDelegate { * @usage * * ```typescript - * import { IBeacon } from 'ionic-native'; + * import { IBeacon } from '@ionic-native/ibeacon'; + * + * constructor(private ibeacon: IBeacon) { } + * + * ... * * * // Request permission to use location on iOS - * IBeacon.requestAlwaysAuthorization(); + * this.ibeacon.requestAlwaysAuthorization(); * // create a new delegate and register it with the native layer - * let delegate = IBeacon.Delegate(); + * let delegate = this.ibeacon.Delegate(); * * // Subscribe to some of the delegate's event handlers * delegate.didRangeBeaconsInRegion() @@ -257,9 +262,9 @@ export interface IBeaconDelegate { * } * ); * - * let beaconRegion = IBeacon.BeaconRegion('deskBeacon','F7826DA6-ASDF-ASDF-8024-BC5B71E0893E'); + * let beaconRegion = this.ibeacon.BeaconRegion('deskBeacon','F7826DA6-ASDF-ASDF-8024-BC5B71E0893E'); * - * IBeacon.startMonitoringForRegion(beaconRegion) + * this.ibeacon.startMonitoringForRegion(beaconRegion) * .then( * () => console.log('Native layer recieved the request to monitoring'), * error => console.error('Native layer failed to begin monitoring: ', error) @@ -280,6 +285,7 @@ export interface IBeaconDelegate { repo: 'https://github.com/petermetz/cordova-plugin-ibeacon', platforms: ['Android', 'iOS'] }) +@Injectable() export class IBeacon { /** @@ -288,7 +294,8 @@ export class IBeacon { * * @returns {IBeaconDelegate} An instance of the type {@type Delegate}. */ - static Delegate(): IBeaconDelegate { + @CordovaCheck({ sync: true }) + Delegate(): IBeaconDelegate { let delegate = new cordova.plugins.locationManager.Delegate(); delegate.didChangeAuthorizationStatus = (pluginResult?: IBeaconPluginResult) => { @@ -388,7 +395,8 @@ export class IBeacon { * * @returns {BeaconRegion} Returns the BeaconRegion that was created */ - static BeaconRegion(identifer: string, uuid: string, major?: number, minor?: number, notifyEntryStateOnDisplay?: boolean): BeaconRegion { + @CordovaCheck({ sync: true }) + BeaconRegion(identifer: string, uuid: string, major?: number, minor?: number, notifyEntryStateOnDisplay?: boolean): BeaconRegion { return new cordova.plugins.locationManager.BeaconRegion(identifer, uuid, major, minor, notifyEntryStateOnDisplay); } @@ -396,7 +404,7 @@ export class IBeacon { * @returns {IBeaconDelegate} Returns the IBeaconDelegate */ @Cordova() - static getDelegate(): IBeaconDelegate { return; } + getDelegate(): IBeaconDelegate { return; } /** * @param {IBeaconDelegate} delegate An instance of a delegate to register with the native layer. @@ -404,7 +412,7 @@ export class IBeacon { * @returns {IBeaconDelegate} Returns the IBeaconDelegate */ @Cordova() - static setDelegate(delegate: IBeaconDelegate): IBeaconDelegate { return; } + setDelegate(delegate: IBeaconDelegate): IBeaconDelegate { return; } /** * Signals the native layer that the client side is ready to consume messages. @@ -427,7 +435,7 @@ export class IBeacon { * native layer acknowledged the request and started to send events. */ @Cordova({otherPromise: true}) - static onDomDelegateReady(): Promise { return; } + onDomDelegateReady(): Promise { return; } /** * Determines if bluetooth is switched on, according to the native layer. @@ -435,7 +443,7 @@ export class IBeacon { * indicating whether bluetooth is active. */ @Cordova({otherPromise: true}) - static isBluetoothEnabled(): Promise { return; } + isBluetoothEnabled(): Promise { return; } /** * Enables Bluetooth using the native Layer. (ANDROID ONLY) @@ -444,7 +452,7 @@ export class IBeacon { * could be enabled. If not, the promise will be rejected with an error. */ @Cordova({otherPromise: true}) - static enableBluetooth(): Promise { return; } + enableBluetooth(): Promise { return; } /** * Disables Bluetooth using the native Layer. (ANDROID ONLY) @@ -453,7 +461,7 @@ export class IBeacon { * could be enabled. If not, the promise will be rejected with an error. */ @Cordova({otherPromise: true}) - static disableBluetooth(): Promise { return; } + disableBluetooth(): Promise { return; } /** * Start monitoring the specified region. @@ -473,7 +481,7 @@ export class IBeacon { * native layer acknowledged the dispatch of the monitoring request. */ @Cordova({otherPromise: true}) - static startMonitoringForRegion(region: BeaconRegion): Promise { return; } + startMonitoringForRegion(region: BeaconRegion): Promise { return; } /** * Stop monitoring the specified region. It is valid to call @@ -490,7 +498,7 @@ export class IBeacon { * native layer acknowledged the dispatch of the request to stop monitoring. */ @Cordova({otherPromise: true}) - static stopMonitoringForRegion(region: BeaconRegion): Promise { return; } + stopMonitoringForRegion(region: BeaconRegion): Promise { return; } /** * Request state the for specified region. When result is ready @@ -506,7 +514,7 @@ export class IBeacon { * native layer acknowledged the dispatch of the request to stop monitoring. */ @Cordova({otherPromise: true}) - static requestStateForRegion(region: Region): Promise { return; } + requestStateForRegion(region: Region): Promise { return; } /** @@ -524,7 +532,7 @@ export class IBeacon { * native layer acknowledged the dispatch of the monitoring request. */ @Cordova({otherPromise: true}) - static startRangingBeaconsInRegion(region: BeaconRegion): Promise { return; } + startRangingBeaconsInRegion(region: BeaconRegion): Promise { return; } /** * Stop ranging the specified region. It is valid to call @@ -541,7 +549,7 @@ export class IBeacon { * native layer acknowledged the dispatch of the request to stop monitoring. */ @Cordova({otherPromise: true}) - static stopRangingBeaconsInRegion(region: BeaconRegion): Promise { return; } + stopRangingBeaconsInRegion(region: BeaconRegion): Promise { return; } /** * Queries the native layer to determine the current authorization in effect. @@ -550,7 +558,7 @@ export class IBeacon { * requested authorization status. */ @Cordova({otherPromise: true}) - static getAuthorizationStatus(): Promise { return; } + getAuthorizationStatus(): Promise { return; } /** * For iOS 8 and above only. The permission model has changed by Apple in iOS 8, making it necessary for apps to @@ -562,7 +570,7 @@ export class IBeacon { * @returns {Promise} Returns a promise that is resolved when the request dialog is shown. */ @Cordova({otherPromise: true}) - static requestWhenInUseAuthorization(): Promise { return; } + requestWhenInUseAuthorization(): Promise { return; } /** @@ -572,7 +580,7 @@ export class IBeacon { * shows the request dialog. */ @Cordova({otherPromise: true}) - static requestAlwaysAuthorization(): Promise { return; } + requestAlwaysAuthorization(): Promise { return; } /** * @@ -580,7 +588,7 @@ export class IBeacon { * of {Region} instances that are being monitored by the native layer. */ @Cordova({otherPromise: true}) - static getMonitoredRegions(): Promise { return; } + getMonitoredRegions(): Promise { return; } /** * @@ -588,7 +596,7 @@ export class IBeacon { * of {Region} instances that are being ranged by the native layer. */ @Cordova({otherPromise: true}) - static getRangedRegions(): Promise { return; } + getRangedRegions(): Promise { return; } /** * Determines if ranging is available or not, according to the native layer. @@ -596,7 +604,7 @@ export class IBeacon { * indicating whether ranging is available or not. */ @Cordova({otherPromise: true}) - static isRangingAvailable(): Promise { return; } + isRangingAvailable(): Promise { return; } /** * Determines if region type is supported or not, according to the native layer. @@ -608,7 +616,7 @@ export class IBeacon { * indicating whether the region type is supported or not. */ @Cordova({otherPromise: true}) - static isMonitoringAvailableForClass(region: Region): Promise { return; } + isMonitoringAvailableForClass(region: Region): Promise { return; } /** * Start advertising the specified region. @@ -628,7 +636,7 @@ export class IBeacon { * native layer acknowledged the dispatch of the advertising request. */ @Cordova({otherPromise: true}) - static startAdvertising(region: Region, measuredPower: number): Promise { return; } + startAdvertising(region: Region, measuredPower: number): Promise { return; } /** * Stop advertising as a beacon. @@ -639,7 +647,7 @@ export class IBeacon { * native layer acknowledged the dispatch of the request to stop advertising. */ @Cordova({otherPromise: true}) - static stopAdvertising(region: Region): Promise { return; } + stopAdvertising(region: Region): Promise { return; } /** * Determines if advertising is available or not, according to the native layer. @@ -647,7 +655,7 @@ export class IBeacon { * indicating whether advertising is available or not. */ @Cordova({otherPromise: true}) - static isAdvertisingAvailable(): Promise { return; } + isAdvertisingAvailable(): Promise { return; } /** * Determines if advertising is currently active, according to the native layer. @@ -655,7 +663,7 @@ export class IBeacon { * indicating whether advertising is active. */ @Cordova({otherPromise: true}) - static isAdvertising(): Promise { return; } + isAdvertising(): Promise { return; } /** * Disables debug logging in the native layer. Use this method if you want @@ -665,7 +673,7 @@ export class IBeacon { * native layer has set the logging level accordingly. */ @Cordova({otherPromise: true}) - static disableDebugLogs(): Promise { return; } + disableDebugLogs(): Promise { return; } /** * Enables the posting of debug notifications in the native layer. Use this method if you want @@ -676,7 +684,7 @@ export class IBeacon { * native layer has set the flag to enabled. */ @Cordova({otherPromise: true}) - static enableDebugNotifications(): Promise { return; } + enableDebugNotifications(): Promise { return; } /** * Disables the posting of debug notifications in the native layer. Use this method if you want @@ -686,7 +694,7 @@ export class IBeacon { * native layer has set the flag to disabled. */ @Cordova({otherPromise: true}) - static disableDebugNotifications(): Promise { return; } + disableDebugNotifications(): Promise { return; } /** * Enables debug logging in the native layer. Use this method if you want @@ -696,7 +704,7 @@ export class IBeacon { * native layer has set the logging level accordingly. */ @Cordova({otherPromise: true}) - static enableDebugLogs(): Promise { return; } + enableDebugLogs(): Promise { return; } /** * Appends the provided [message] to the device logs. @@ -709,6 +717,6 @@ export class IBeacon { * is expected to be equivalent to the one provided in the original call. */ @Cordova({otherPromise: true}) - static appendToDeviceLog(message: string): Promise { return; } + appendToDeviceLog(message: string): Promise { return; } } diff --git a/src/plugins/imagepicker.ts b/src/@ionic-native/plugins/image-picker/index.ts similarity index 79% rename from src/plugins/imagepicker.ts rename to src/@ionic-native/plugins/image-picker/index.ts index 806e4178b..1c7164da4 100644 --- a/src/plugins/imagepicker.ts +++ b/src/@ionic-native/plugins/image-picker/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; export interface ImagePickerOptions { @@ -37,15 +38,19 @@ export interface ImagePickerOptions { * * @usage * ```typescript - * import { ImagePicker } from 'ionic-native'; + * import { ImagePicker } from '@ionic-native/image-picker'; * * + * constructor(private imagePicker: ImagePicker) { } * - * ImagePicker.getPictures(options).then((results) => { + * ... + * + * this.imagePicker.getPictures(options).then((results) => { * for (var i = 0; i < results.length; i++) { * console.log('Image URI: ' + results[i]); * } * }, (err) => { }); + * * ``` * @interfaces * ImagePickerOptions @@ -56,6 +61,7 @@ export interface ImagePickerOptions { pluginRef: 'window.imagePicker', repo: 'https://github.com/Telerik-Verified-Plugins/ImagePicker' }) +@Injectable() export class ImagePicker { /** * Pick pictures from the library. @@ -66,7 +72,7 @@ export class ImagePicker { @Cordova({ callbackOrder: 'reverse' }) - static getPictures(options: ImagePickerOptions): Promise { return; } + getPictures(options: ImagePickerOptions): Promise { return; } /** * Check if we have permission to read images @@ -75,7 +81,7 @@ export class ImagePicker { @Cordova({ platforms: ['Android'] }) - static hasReadPermission(): Promise { return; } + hasReadPermission(): Promise { return; } /** * Request permission to read images @@ -84,6 +90,6 @@ export class ImagePicker { @Cordova({ platforms: ['Android'] }) - static requestReadPermission(): Promise { return; } + requestReadPermission(): Promise { return; } } diff --git a/src/plugins/imageresizer.ts b/src/@ionic-native/plugins/image-resizer/index.ts similarity index 75% rename from src/plugins/imageresizer.ts rename to src/@ionic-native/plugins/image-resizer/index.ts index d08ca280b..f08ccca70 100644 --- a/src/plugins/imageresizer.ts +++ b/src/@ionic-native/plugins/image-resizer/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; export interface ImageResizerOptions { /** @@ -37,7 +38,7 @@ export interface ImageResizerOptions { } /** - * @name ImageResizer + * @name Image Resizer * @description * Cordova Plugin For Image Resize * @@ -48,7 +49,11 @@ export interface ImageResizerOptions { * * @usage * ```typescript - * import { ImageResizer, ImageResizerOptions } from 'ionic-native'; + * import { ImageResizer, ImageResizerOptions } from '@ionic-native/image-resizer'; + * + * constructor(private imageResizer: ImageResizer) { } + * + * ... * * let options = { * uri: uri, @@ -58,12 +63,11 @@ export interface ImageResizerOptions { * height: 1280 * } as ImageResizerOptions; * - * ImageResizer - * .resize(options) - * .then( - * (filePath: string) => { console.log('FilePath', filePath); }, - * () => { console.log('Error occured'); } - * ) + * this.imageResizer + * .resize(options) + * .then((filePath: string) => console.log('FilePath', filePath)) + * .catch(e => console.log(e)); + * * ``` * @interfaces * ImageResizerOptions @@ -74,10 +78,11 @@ export interface ImageResizerOptions { pluginRef: 'ImageResizer', repo: 'https://github.com/protonet/cordova-plugin-image-resizer' }) +@Injectable() export class ImageResizer { /** * @returns {Promise} */ @Cordova() - static resize(options: ImageResizerOptions): Promise { return; } + resize(options: ImageResizerOptions): Promise { return; } } diff --git a/src/plugins/inappbrowser.ts b/src/@ionic-native/plugins/in-app-browser/index.ts similarity index 82% rename from src/plugins/inappbrowser.ts rename to src/@ionic-native/plugins/in-app-browser/index.ts index 3cfd15875..a4f8a2da0 100644 --- a/src/plugins/inappbrowser.ts +++ b/src/@ionic-native/plugins/in-app-browser/index.ts @@ -1,5 +1,7 @@ -import { Plugin, CordovaInstance } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, CordovaInstance } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; +import 'rxjs/add/observable/fromEvent'; declare var cordova: any; @@ -57,33 +59,11 @@ export interface InAppBrowserEvent extends Event { /** the error message, only in the case of loaderror. */ message: string; } + /** - * @name InAppBrowser - * @description Launches in app Browser - * @usage - * ```typescript - * import {InAppBrowser} from 'ionic-native'; - * - * - * ... - * - * - * let browser = new InAppBrowser('https://ionic.io', '_system'); - * browser.executeScript(...); - * browser.insertCSS(...); - * browser.close(); - * ``` - * @interfaces - * InAppBrowserEvent - * InAppBrowserOptions + * @hidden */ -@Plugin({ - pluginName: 'InAppBrowser', - plugin: 'cordova-plugin-inappbrowser', - pluginRef: 'cordova.InAppBrowser', - repo: 'https://github.com/apache/cordova-plugin-inappbrowser' -}) -export class InAppBrowser { +export class InAppBrowserObject { private _objectInstance: any; @@ -95,8 +75,6 @@ export class InAppBrowser { * The options string must not contain any blank space, and each feature's * name/value pairs must be separated by a comma. Feature names are case insensitive. */ - constructor(url: string, target?: string, options?: InAppBrowserOptions); - constructor(url: string, target?: string, options?: string); constructor(url: string, target?: string, options?: string | InAppBrowserOptions) { try { if (options && typeof options !== 'string') @@ -104,7 +82,7 @@ export class InAppBrowser { this._objectInstance = cordova.InAppBrowser.open(url, target, options); } catch (e) { window.open(url); - console.warn('Native: InAppBrowser is not installed or you are running on a browser. Falling back to window.open, all instance methods will NOT work.'); + console.warn('Native: InAppBrowser is not installed or you are running on a browser. Falling back to window.open.'); } } @@ -146,14 +124,60 @@ export class InAppBrowser { /** * A method that allows you to listen to events happening in the browser. - * @param {string} name of the event + * @param event {string} Name of the event * @returns {Observable} Returns back an observable that will listen to the event on subscribe, and will stop listening to the event on unsubscribe. */ on(event: string): Observable { - return new Observable((observer) => { - this._objectInstance.addEventListener(event, observer.next.bind(observer)); - return () => this._objectInstance.removeEventListener(event, observer.next.bind(observer)); - }); + return Observable.fromEvent(this._objectInstance, event); + } +} + +/** + * @name In App Browser + * @description Launches in app Browser + * @usage + * ```typescript + * import { InAppBrowser } from '@ionic-native/in-app-browser'; + * + * constructor(private iab: InAppBrowser) { } + * + * + * ... + * + * + * const browser = this.iab.create('https://ionic.io'); + * + * browser.executeScript(...); + * browser.insertCSS(...); + * browser.close(); + * + * ``` + * @classes + * InAppBrowserObject + * @interfaces + * InAppBrowserEvent + * InAppBrowserOptions + */ +@Plugin({ + pluginName: 'InAppBrowser', + plugin: 'cordova-plugin-inappbrowser', + pluginRef: 'cordova.InAppBrowser', + repo: 'https://github.com/apache/cordova-plugin-inappbrowser' +}) +@Injectable() +export class InAppBrowser { + + /** + * Opens a URL in a new InAppBrowser instance, the current browser instance, or the system browser. + * @param url {string} The URL to load. + * @param target {string} The target in which to load the URL, an optional parameter that defaults to _self. + * @param options {string} Options for the InAppBrowser. Optional, defaulting to: location=yes. + * The options string must not contain any blank space, and each feature's + * name/value pairs must be separated by a comma. Feature names are case insensitive. + * @returns {InAppBrowserObject} + */ + create(url: string, target?: string, options?: string | InAppBrowserOptions): InAppBrowserObject { + return new InAppBrowserObject(url, target, options); } } diff --git a/src/plugins/inapppurchase.ts b/src/@ionic-native/plugins/in-app-purchase/index.ts similarity index 77% rename from src/plugins/inapppurchase.ts rename to src/@ionic-native/plugins/in-app-purchase/index.ts index 447bb3222..49295b98f 100644 --- a/src/plugins/inapppurchase.ts +++ b/src/@ionic-native/plugins/in-app-purchase/index.ts @@ -1,16 +1,21 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; /** - * @name InAppPurchase + * @name In App Purchase * @description * A lightweight Cordova plugin for in app purchases on iOS/Android. * * @usage * ```ts - * import {InAppPurchase} from 'ionic-native'; + * import { InAppPurchase } from '@ionic-native/in-app-purchase'; * - * InAppPurchase + * constructor(private iap: InAppPurchase) { } + * + * ... + * + * this.iap * .getProducts(['com.yourapp.prod1', 'com.yourapp.prod2', ...]) * .then((products) => { * console.log(products); @@ -21,7 +26,7 @@ import { Plugin, Cordova } from './plugin'; * }); * * - * InAppPurchase + * this.iap * .buy('com.yourapp.prod1') * .then((data)=> { * console.log(data); @@ -41,14 +46,12 @@ import { Plugin, Cordova } from './plugin'; * * ```ts * // fist buy the product... - * InAppPurchase + * this.iap * .buy('com.yourapp.consumable_prod1') - * .then(data => InAppPurchase.consume(data.productType, data.receipt, data.signature)) + * .then(data => this.iap.consume(data.productType, data.receipt, data.signature)) * .then(() => console.log('product was successfully consumed!')) * .catch( err=> console.log(err)) * ``` - * - * */ @Plugin({ pluginName: 'InAppPurchase', @@ -57,6 +60,7 @@ import { Plugin, Cordova } from './plugin'; platforms: ['Android', 'iOS'], repo: 'https://github.com/AlexDisler/cordova-plugin-inapppurchase' }) +@Injectable() export class InAppPurchase { /** @@ -67,7 +71,7 @@ export class InAppPurchase { @Cordova({ otherPromise: true }) - static getProducts(productId: string[]): Promise { return; } + getProducts(productId: string[]): Promise { return; } /** * Buy a product that matches the productId. @@ -77,7 +81,7 @@ export class InAppPurchase { @Cordova({ otherPromise: true }) - static buy(productId: string): Promise<{transactionId: string, receipt: string, signature: string, productType: string}> { return; } + buy(productId: string): Promise<{transactionId: string, receipt: string, signature: string, productType: string}> { return; } /** * Same as buy, but for subscription based products. @@ -87,7 +91,7 @@ export class InAppPurchase { @Cordova({ otherPromise: true }) - static subscribe(productId: string): Promise<{transactionId: string, receipt: string, signature: string, productType: string}> { return; } + subscribe(productId: string): Promise<{transactionId: string, receipt: string, signature: string, productType: string}> { return; } /** * Call this function after purchasing a "consumable" product to mark it as consumed. On Android, you must consume products that you want to let the user purchase multiple times. If you will not consume the product after a purchase, the next time you will attempt to purchase it you will get the error message: @@ -99,7 +103,7 @@ export class InAppPurchase { @Cordova({ otherPromise: true }) - static consume(productType: string, receipt: string, signature: string): Promise { return; } + consume(productType: string, receipt: string, signature: string): Promise { return; } /** * Restore all purchases from the store @@ -108,7 +112,7 @@ export class InAppPurchase { @Cordova({ otherPromise: true }) - static restorePurchases(): Promise { return; } + restorePurchases(): Promise { return; } /** * Get the receipt. @@ -118,6 +122,6 @@ export class InAppPurchase { otherPromise: true, platforms: ['iOS'] }) - static getReceipt(): Promise { return; } + getReceipt(): Promise { return; } } diff --git a/src/plugins/insomnia.ts b/src/@ionic-native/plugins/insomnia/index.ts similarity index 68% rename from src/plugins/insomnia.ts rename to src/@ionic-native/plugins/insomnia/index.ts index 978412425..a78974bf5 100644 --- a/src/plugins/insomnia.ts +++ b/src/@ionic-native/plugins/insomnia/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; /** @@ -8,16 +9,19 @@ import { Cordova, Plugin } from './plugin'; * * @usage * ```typescript - * import { Insomnia } from 'ionic-native'; + * import { Insomnia } from '@ionic-native/insomnia'; * + * constructor(private insomnia: Insomnia) { } * - * Insomnia.keepAwake() + * ... + * + * this.insomnia.keepAwake() * .then( * () => console.log('success'), * () => console.log('error') * ); * - * Insomnia.allowSleepAgain() + * this.insomnia.allowSleepAgain() * .then( * () => console.log('success'), * () => console.log('error') @@ -32,6 +36,7 @@ import { Cordova, Plugin } from './plugin'; repo: 'https://github.com/EddyVerbruggen/Insomnia-PhoneGap-Plugin', platforms: ['Android', 'iOS', 'Windows Phone 8'] }) +@Injectable() export class Insomnia { /** @@ -39,13 +44,13 @@ export class Insomnia { * @returns {Promise} */ @Cordova() - static keepAwake(): Promise { return; } + keepAwake(): Promise { return; } /** * Allows the application to sleep again * @returns {Promise} */ @Cordova() - static allowSleepAgain(): Promise { return; } + allowSleepAgain(): Promise { return; } } diff --git a/src/plugins/instagram.ts b/src/@ionic-native/plugins/instagram/index.ts similarity index 73% rename from src/plugins/instagram.ts rename to src/@ionic-native/plugins/instagram/index.ts index f92fb47d3..89135ef10 100644 --- a/src/plugins/instagram.ts +++ b/src/@ionic-native/plugins/instagram/index.ts @@ -1,4 +1,5 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; /** * @name Instagram @@ -6,9 +7,13 @@ import { Plugin, Cordova } from './plugin'; * * @usage * ``` - * import {Instagram} from 'ionic-native'; + * import { Instagram } from '@ionic-native/instagram'; * - * Instagram.share('data:image/png;uhduhf3hfif33', 'Caption') + * constructor(private instagram: Instagram) { } + * + * ... + * + * this.instagram.share('data:image/png;uhduhf3hfif33', 'Caption') * .then(() => console.log('Shared!')) * .catch((error: any) => console.error(error)); * @@ -20,6 +25,7 @@ import { Plugin, Cordova } from './plugin'; pluginRef: 'Instagram', repo: 'https://github.com/vstirbu/InstagramPlugin' }) +@Injectable() export class Instagram { /** @@ -30,7 +36,7 @@ export class Instagram { @Cordova({ callbackStyle: 'node' }) - static isInstalled(): Promise { return; } + isInstalled(): Promise { return; } /** * Share an image on Instagram @@ -43,7 +49,7 @@ export class Instagram { @Cordova({ callbackStyle: 'node' }) - static share(canvasIdOrDataUrl: string, caption?: string): Promise { return; } + share(canvasIdOrDataUrl: string, caption?: string): Promise { return; } /** * Share a library asset or video @@ -53,6 +59,6 @@ export class Instagram { @Cordova({ callbackOrder: 'reverse' }) - static shareAsset(assetLocalIdentifier: string): Promise { return; } + shareAsset(assetLocalIdentifier: string): Promise { return; } } diff --git a/src/plugins/is-debug.ts b/src/@ionic-native/plugins/is-debug/index.ts similarity index 76% rename from src/plugins/is-debug.ts rename to src/@ionic-native/plugins/is-debug/index.ts index 839a79201..19c3949bd 100644 --- a/src/plugins/is-debug.ts +++ b/src/@ionic-native/plugins/is-debug/index.ts @@ -1,16 +1,21 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; /** - * @name IsDebug + * @name Is Debug * @description * Detect if the app is running in debug mode or not. * Debug mode is when the app is built and installed locally via xcode / eclipse / the cordova cli etc, compared to release mode when the app was downloaded from the app / play store via an end user. * * @usage * ``` - * import {IsDebug} from 'ionic-native'; + * import { IsDebug } from '@ionic-native/is-debug'; * - * IsDebug.getIsDebug() + * constructor(private isDebug: IsDebug) { } + * + * ... + * + * this.isDebug.getIsDebug() * .then((isDebug: boolean) => console.log('Is debug:', isDebug)) * .catch((error: any) => console.error(error)); * @@ -22,6 +27,7 @@ import { Plugin, Cordova } from './plugin'; pluginRef: 'cordova.plugins.IsDebug', repo: 'https://github.com/mattlewis92/cordova-plugin-is-debug' }) +@Injectable() export class IsDebug { /** @@ -29,7 +35,7 @@ export class IsDebug { * @returns {Promise} Returns a promise that resolves with true if the app was installed via xcode / eclipse / the ionic CLI etc. It will resolve to false if the app was downloaded from the app / play store by the end user. */ @Cordova() - static getIsDebug(): Promise { + getIsDebug(): Promise { return; } diff --git a/src/plugins/keyboard.ts b/src/@ionic-native/plugins/keyboard/index.ts similarity index 75% rename from src/plugins/keyboard.ts rename to src/@ionic-native/plugins/keyboard/index.ts index aa076df2e..da7749124 100644 --- a/src/plugins/keyboard.ts +++ b/src/@ionic-native/plugins/keyboard/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; @@ -7,9 +8,15 @@ import { Observable } from 'rxjs/Observable'; * @description * @usage * ```typescript - * import { Keyboard } from 'ionic-native'; + * import { Keyboard } from '@ionic-native/keyboard'; * + * constructor(private keyboard: Keyboard) { } * + * ... + * + * this.keyboard.show(); + * + * this.keyboard.close(); * * ``` */ @@ -19,6 +26,7 @@ import { Observable } from 'rxjs/Observable'; pluginRef: 'cordova.plugins.Keyboard', repo: 'https://github.com/driftyco/ionic-plugin-keyboard' }) +@Injectable() export class Keyboard { /** @@ -26,7 +34,7 @@ export class Keyboard { * @param hide {boolean} */ @Cordova({sync: true}) - static hideKeyboardAccessoryBar(hide: boolean): void { } + hideKeyboardAccessoryBar(hide: boolean): void { } /** * Force keyboard to be shown. @@ -35,7 +43,7 @@ export class Keyboard { sync: true, platforms: ['Android', 'BlackBerry 10', 'Windows'] }) - static show(): void { } + show(): void { } /** * Close the keyboard if open. @@ -44,7 +52,7 @@ export class Keyboard { sync: true, platforms: ['iOS', 'Android', 'BlackBerry 10', 'Windows'] }) - static close(): void { } + close(): void { } /** * Prevents the native UIScrollView from moving when an input is focused. @@ -54,7 +62,7 @@ export class Keyboard { sync: true, platforms: ['iOS', 'Windows'] }) - static disableScroll(disable: boolean): void { } + disableScroll(disable: boolean): void { } /** * Creates an observable that notifies you when the keyboard is shown. Unsubscribe to observable to cancel event watch. @@ -65,7 +73,7 @@ export class Keyboard { event: 'native.keyboardshow', platforms: ['iOS', 'Android', 'BlackBerry 10', 'Windows'] }) - static onKeyboardShow(): Observable { return; } + onKeyboardShow(): Observable { return; } /** * Creates an observable that notifies you when the keyboard is hidden. Unsubscribe to observable to cancel event watch. @@ -76,6 +84,6 @@ export class Keyboard { event: 'native.keyboardhide', platforms: ['iOS', 'Android', 'BlackBerry 10', 'Windows'] }) - static onKeyboardHide(): Observable { return; } + onKeyboardHide(): Observable { return; } } diff --git a/src/plugins/launchnavigator.ts b/src/@ionic-native/plugins/launch-navigator/index.ts similarity index 82% rename from src/plugins/launchnavigator.ts rename to src/@ionic-native/plugins/launch-navigator/index.ts index 6eb20a949..f177b0472 100644 --- a/src/plugins/launchnavigator.ts +++ b/src/@ionic-native/plugins/launch-navigator/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; export interface LaunchNavigatorOptions { @@ -66,14 +67,18 @@ export interface LaunchNavigatorOptions { * Please refer to the plugin's repo for detailed usage. This docs page only explains the Native wrapper. * * ```typescript - * import { LaunchNavigator, LaunchNavigatorOptions } from 'ionic-native'; + * import { LaunchNavigator, LaunchNavigatorOptions } from '@ionic-native/launch-navigator'; + * + * constructor(private launchNavigator: LaunchNavigator) { } + * + * ... * * let options: LaunchNavigatorOptions = { * start: 'London, ON', * app: LaunchNavigator.APPS.UBER * }; * - * LaunchNavigator.navigate('Toronto, ON', options) + * this.launchNavigator.navigate('Toronto, ON', options) * .then( * success => console.log('Launched navigator'), * error => console.log('Error launching navigator', error) @@ -88,6 +93,7 @@ export interface LaunchNavigatorOptions { pluginRef: 'launchnavigator', repo: 'https://github.com/dpa99c/phonegap-launch-navigator.git' }) +@Injectable() export class LaunchNavigator { /** @@ -100,7 +106,7 @@ export class LaunchNavigator { successIndex: 1, errorIndex: 2 }) - static navigate( + navigate( destination: string | number[], options?: LaunchNavigatorOptions ): Promise { return; } @@ -111,14 +117,14 @@ export class LaunchNavigator { * @returns {Promise} */ @Cordova() - static isAppAvailable(app: string): Promise { return; } + isAppAvailable(app: string): Promise { return; } /** * Returns a list indicating which apps are installed and available on the current device. * @returns {Promise} */ @Cordova() - static availableApps(): Promise { return; } + availableApps(): Promise { return; } /** * Returns the display name of the specified app. @@ -126,7 +132,7 @@ export class LaunchNavigator { * @returns {string} */ @Cordova({ sync: true }) - static getAppDisplayName(app: string): string { return; } + getAppDisplayName(app: string): string { return; } /** * Returns list of supported apps on a given platform. @@ -134,7 +140,7 @@ export class LaunchNavigator { * @returns {string[]} */ @Cordova({ sync: true }) - static getAppsForPlatform(platform: string): string[] { return; } + getAppsForPlatform(platform: string): string[] { return; } /** * Indicates if an app on a given platform supports specification of transport mode. @@ -143,7 +149,7 @@ export class LaunchNavigator { * @returns {boolean} */ @Cordova({ sync: true }) - static supportsTransportMode(app: string, platform: string): boolean { return; } + supportsTransportMode(app: string, platform: string): boolean { return; } /** * Returns the list of transport modes supported by an app on a given platform. @@ -152,7 +158,7 @@ export class LaunchNavigator { * @returns {string[]} */ @Cordova({ sync: true }) - static getTransportModes(app: string, platform: string): string[] { return; } + getTransportModes(app: string, platform: string): string[] { return; } /** * Indicates if an app on a given platform supports specification of launch mode. @@ -162,7 +168,7 @@ export class LaunchNavigator { * @returns {boolean} */ @Cordova({ sync: true }) - static supportsLaunchMode(app: string, platform: string): boolean { return; } + supportsLaunchMode(app: string, platform: string): boolean { return; } /** * Indicates if an app on a given platform supports specification of start location. @@ -171,7 +177,7 @@ export class LaunchNavigator { * @returns {boolean} */ @Cordova({ sync: true }) - static supportsStart(app: string, platform: string): boolean { return; } + supportsStart(app: string, platform: string): boolean { return; } /** * @param app {string} @@ -179,7 +185,7 @@ export class LaunchNavigator { * @returns {boolean} */ @Cordova({ sync: true }) - static supportsStartName(app: string, platform: string): boolean { return; } + supportsStartName(app: string, platform: string): boolean { return; } /** * @param app {string} @@ -187,16 +193,16 @@ export class LaunchNavigator { * @returns {boolean} */ @Cordova({ sync: true }) - static supportsDestName(app: string, platform: string): boolean { return; } + supportsDestName(app: string, platform: string): boolean { return; } /** * @param destination {string | number[]} * @param options {LaunchNavigatorOptions} */ @Cordova({ sync: true }) - static userSelect(destination: string | number[], options: LaunchNavigatorOptions): void { } + userSelect(destination: string | number[], options: LaunchNavigatorOptions): void { } - static APP: any = { + APP: any = { USER_SELECT: 'user_select', APPLE_MAPS: 'apple_maps', GOOGLE_MAPS: 'google_maps', @@ -213,7 +219,7 @@ export class LaunchNavigator { MOOVIT: 'moovit' }; - static TRANSPORT_MODE: any = { + TRANSPORT_MODE: any = { DRIVING: 'driving', WALKING: 'walking', BICYCLING: 'bicycling', diff --git a/src/plugins/launch-review.ts b/src/@ionic-native/plugins/launch-review/index.ts similarity index 71% rename from src/plugins/launch-review.ts rename to src/@ionic-native/plugins/launch-review/index.ts index dbd8ae69b..9be59eab1 100644 --- a/src/plugins/launch-review.ts +++ b/src/@ionic-native/plugins/launch-review/index.ts @@ -1,7 +1,8 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; /** - * @name LaunchReview + * @name Launch Review * @description * * This launches the native store app in order for the user to leave a review. @@ -10,10 +11,14 @@ import { Plugin, Cordova } from './plugin'; * * @usage * ``` - * import { LaunchReview } from 'ionic-native'; + * import { LaunchReview } from '@ionic-native/launch-review'; + * + * constructor(private launchReview: LaunchReview) { } + * + * ... * * const appId: string = 'yourAppId'; - * LaunchReview.launch(appId) + * this.launchReview.launch(appId) * .then(() => console.log('Successfully launched store app'); * ``` */ @@ -24,6 +29,7 @@ import { Plugin, Cordova } from './plugin'; repo: 'https://github.com/dpa99c/cordova-launch-review', platforms: ['Android', 'iOS'] }) +@Injectable() export class LaunchReview { /** @@ -31,6 +37,6 @@ export class LaunchReview { * @returns {Promise} */ @Cordova() - static launch(appId: string): Promise { return; } + launch(appId: string): Promise { return; } } diff --git a/src/@ionic-native/plugins/linkedin/index.ts b/src/@ionic-native/plugins/linkedin/index.ts new file mode 100644 index 000000000..82b79f230 --- /dev/null +++ b/src/@ionic-native/plugins/linkedin/index.ts @@ -0,0 +1,108 @@ +import { Plugin, Cordova } from '@ionic-native/core'; +import { Injectable } from '@angular/core'; + +export type LinkedInLoginScopes = 'r_basicprofile' | 'r_emailaddress' | 'rw_company_admin' | 'w_share'; + +/** + * @name LinkedIn + * @description + * A Cordova plugin that lets you use LinkedIn Native SDKs for Android and iOS. + * + * Please see the [plugin's repo](https://github.com/zyramedia/cordova-plugin-linkedin#installation) for detailed installation steps. + * + * @usage + * ``` + * import { LinkedIn } from 'ionic-native'; + * + * constructor(private linkedin: LinkedIn) { } + * + * ... + * + * // check if there is an active session + * this.linkedin.hasActiveSession().then((active) => console.log('has active session?', active)); + * + * // login + * const scopes = ['r_basicprofile', 'r_emailaddress', 'rw_company_admin', 'w_share']; + * this.linkedin.login(scopes, true) + * .then(() => console.log('Logged in!') + * .catch(e => console.log('Error logging in', e)); + * + * + * // get connections + * this.linkedin.getRequest('people/~') + * .then(res => console.log(res)) + * .catch(e => console.log(e)); + * + * // share something on profile + * const body = { + * comment: 'Hello world!', + * visibility: { + * code: 'anyone' + * } + * }; + * + * this.linkedin.postRequest('~/shares', body) + * .then(res => console.log(res)) + * .catch(e => console.log(e)); + * + * + * ``` + */ +@Plugin({ + pluginName: 'LinkedIn', + plugin: 'cordova-plugin-linkedin', + pluginRef: 'cordova.plugins.LinkedIn', + repo: 'https://github.com/zyramedia/cordova-plugin-linkedin', + install: 'ionic plugin add cordova-plugin-linkedin --variable APP_ID=YOUR_APP_ID' +}) +@Injectable() +export class LinkedIn { + + /** + * Login with the LinkedIn App + * @param scopes {string[]} Scopes to authorize + * @param promptToInstall {boolean} set to true to prompt the user to download the LinkedIn app if it's not installed + * @return {Promise} + */ + @Cordova() + login(scopes: LinkedInLoginScopes[], promptToInstall: boolean): Promise { return; } + + /** + * Clears the current session + */ + @Cordova({ sync: true }) + logout(): void { } + + /** + * Make a get request + * @param path {string} request path + * @return {Promise} + */ + @Cordova() + getRequest(path: string): Promise { return; } + + /** + * Make a post request + * @param path {string} request path + * @param body {Object} request body + * @return {Promise} + */ + @Cordova() + postRequest(path: string, body: any): Promise { return; } + + /** + * Opens a member's profile + * @param memberId {string} Member id + * @return {Promise} + */ + @Cordova() + openProfile(memberId: string): Promise { return; } + + /** + * Checks if there is already an existing active session. This should be used to avoid unecessary login. + * @return {Promise} returns a promise that resolves with a boolean that indicates whether there is an active session + */ + @Cordova() + hasActiveSession(): Promise { return; } + +} diff --git a/src/plugins/localnotifications.ts b/src/@ionic-native/plugins/local-notifications/index.ts similarity index 81% rename from src/plugins/localnotifications.ts rename to src/@ionic-native/plugins/local-notifications/index.ts index 772767b1a..8aa49a910 100644 --- a/src/plugins/localnotifications.ts +++ b/src/@ionic-native/plugins/local-notifications/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; export interface ILocalNotification { @@ -97,11 +98,16 @@ export interface ILocalNotification { * * @usage * ```typescript - * import { LocalNotifications } from 'ionic-native'; + * import { LocalNotifications } from '@ionic-native/local-notifications'; + * + * + * constructor(private localNotifications: LocalNotifications) { } + * + * ... * * * // Schedule a single notification - * LocalNotifications.schedule({ + * this.localNotifications.schedule({ * id: 1, * text: 'Single ILocalNotification', * sound: isAndroid? 'file://sound.mp3': 'file://beep.caf', @@ -110,7 +116,7 @@ export interface ILocalNotification { * * * // Schedule multiple notifications - * LocalNotifications.schedule([{ + * this.localNotifications.schedule([{ * id: 1, * text: 'Multi ILocalNotification 1', * sound: isAndroid ? 'file://sound.mp3': 'file://beep.caf', @@ -124,7 +130,7 @@ export interface ILocalNotification { * * * // Schedule delayed notification - * LocalNotifications.schedule({ + * this.localNotifications.schedule({ * text: 'Delayed ILocalNotification', * at: new Date(new Date().getTime() + 3600), * led: 'FF0000', @@ -140,6 +146,7 @@ export interface ILocalNotification { pluginRef: 'cordova.plugins.notification.local', repo: 'https://github.com/katzer/cordova-plugin-local-notifications' }) +@Injectable() export class LocalNotifications { /** @@ -149,7 +156,7 @@ export class LocalNotifications { @Cordova({ sync: true }) - static schedule(options?: ILocalNotification | Array): void { } + schedule(options?: ILocalNotification | Array): void { } /** * Updates a previously scheduled notification. Must include the id in the options parameter. @@ -158,7 +165,7 @@ export class LocalNotifications { @Cordova({ sync: true }) - static update(options?: ILocalNotification): void { } + update(options?: ILocalNotification): void { } /** * Clears single or multiple notifications @@ -166,7 +173,7 @@ export class LocalNotifications { * @returns {Promise} Returns a promise when the notification had been cleared */ @Cordova() - static clear(notificationId: any): Promise { return; } + clear(notificationId: any): Promise { return; } /** * Clears all notifications @@ -176,7 +183,7 @@ export class LocalNotifications { successIndex: 0, errorIndex: 2 }) - static clearAll(): Promise { return; } + clearAll(): Promise { return; } /** * Cancels single or multiple notifications @@ -184,7 +191,7 @@ export class LocalNotifications { * @returns {Promise} Returns a promise when the notification is canceled */ @Cordova() - static cancel(notificationId: any): Promise { return; } + cancel(notificationId: any): Promise { return; } /** * Cancels all notifications @@ -194,7 +201,7 @@ export class LocalNotifications { successIndex: 0, errorIndex: 2 }) - static cancelAll(): Promise { return; } + cancelAll(): Promise { return; } /** * Checks presence of a notification @@ -202,7 +209,7 @@ export class LocalNotifications { * @returns {Promise} */ @Cordova() - static isPresent(notificationId: number): Promise { return; } + isPresent(notificationId: number): Promise { return; } /** * Checks is a notification is scheduled @@ -210,7 +217,7 @@ export class LocalNotifications { * @returns {Promise} */ @Cordova() - static isScheduled(notificationId: number): Promise { return; } + isScheduled(notificationId: number): Promise { return; } /** * Checks if a notification is triggered @@ -218,28 +225,28 @@ export class LocalNotifications { * @returns {Promise} */ @Cordova() - static isTriggered(notificationId: number): Promise { return; } + isTriggered(notificationId: number): Promise { return; } /** * Get all the notification ids * @returns {Promise>} */ @Cordova() - static getAllIds(): Promise> { return; } + getAllIds(): Promise> { return; } /** * Get the ids of triggered notifications * @returns {Promise>} */ @Cordova() - static getTriggeredIds(): Promise> { return; } + getTriggeredIds(): Promise> { return; } /** * Get the ids of scheduled notifications * @returns {Promise>} Returns a promise */ @Cordova() - static getScheduledIds(): Promise> { return; } + getScheduledIds(): Promise> { return; } /** * Get a notification object @@ -247,7 +254,7 @@ export class LocalNotifications { * @returns {Promise} */ @Cordova() - static get(notificationId: any): Promise { return; } + get(notificationId: any): Promise { return; } /** * Get a scheduled notification object @@ -255,7 +262,7 @@ export class LocalNotifications { * @returns {Promise} */ @Cordova() - static getScheduled(notificationId: any): Promise { return; } + getScheduled(notificationId: any): Promise { return; } /** * Get a triggered notification object @@ -263,42 +270,42 @@ export class LocalNotifications { * @returns {Promise} */ @Cordova() - static getTriggered(notificationId: any): Promise { return; } + getTriggered(notificationId: any): Promise { return; } /** * Get all notification objects * @returns {Promise>} */ @Cordova() - static getAll(): Promise> { return; } + getAll(): Promise> { return; } /** * Get all scheduled notification objects * @returns {Promise>} */ @Cordova() - static getAllScheduled(): Promise> { return; } + getAllScheduled(): Promise> { return; } /** * Get all triggered notification objects * @returns {Promise>} */ @Cordova() - static getAllTriggered(): Promise> { return; } + getAllTriggered(): Promise> { return; } /** * Register permission to show notifications if not already granted. * @returns {Promise} */ @Cordova() - static registerPermission(): Promise { return; } + registerPermission(): Promise { return; } /** * Informs if the app has the permission to show notifications. * @returns {Promise} */ @Cordova() - static hasPermission(): Promise { return; } + hasPermission(): Promise { return; } /** @@ -309,7 +316,7 @@ export class LocalNotifications { @Cordova({ sync: true }) - static on(eventName: string, callback: any): void { } + on(eventName: string, callback: any): void { } } diff --git a/src/@ionic-native/plugins/location-accuracy/index.ts b/src/@ionic-native/plugins/location-accuracy/index.ts new file mode 100644 index 000000000..c9d0fc4cc --- /dev/null +++ b/src/@ionic-native/plugins/location-accuracy/index.ts @@ -0,0 +1,139 @@ +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; + +/** + * @name LocationAccuracy + * @description + * This Cordova/Phonegap plugin for Android and iOS to request enabling/changing of Location Services by triggering a native dialog from within the app, avoiding the need for the user to leave your app to change location settings manually. + * + * @usage + * ``` + * import { LocationAccuracy } from '@ionic-native/location-accuracy'; + * + * constructor(private locationAccuracy: LocationAccuracy) { } + * + * ... + * + * this.locationAccuracy.canRequest().then((canRequest: boolean) => { + * + * if(canRequest) { + * // the accuracy option will be ignored by iOS + * this.locationAccuracy.request(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).then( + * () => console.log('Request successful'), + * error => console.log('Error requesting location permissions', error) + * ); + * } + * + * }); + * + * ``` + */ +@Plugin({ + pluginName: 'LocationAccuracy', + plugin: 'cordova-plugin-request-location-accuracy', + pluginRef: 'cordova.plugins.locationAccuracy', + repo: 'https://github.com/dpa99c/cordova-plugin-request-location-accuracy' +}) +@Injectable() +export class LocationAccuracy { + /** + * Indicates if you can request accurate location + * @returns {Promise} Returns a promise that resovles with a boolean that indicates if you can request accurate location + */ + @Cordova() + canRequest(): Promise { return; } + + /** + * Indicates if a request is currently in progress + * @returns {Promise} Returns a promise that resolves with a boolean that indicates if a request is currently in progress + */ + @Cordova() + isRequesting(): Promise { return; } + + /** + * Requests accurate location + * @param accuracy {number} Accuracy, from 0 to 4. You can use the static properties of this class that start with REQUEST_PRIORITY_ + * @returns {Promise} Returns a promise that resolves on success and rejects if an error occurred + */ + @Cordova({ callbackOrder: 'reverse' }) + request(accuracy: number): Promise { return; } + + /** + * Convenience constant + * @type {number} + */ + REQUEST_PRIORITY_NO_POWER = 0; + + /** + * Convenience constant + * @type {number} + */ + REQUEST_PRIORITY_LOW_POWER = 1; + + /** + * Convenience constant + * @type {number} + */ + REQUEST_PRIORITY_BALANCED_POWER_ACCURACY = 2; + + /** + * Convenience constant + * @type {number} + */ + REQUEST_PRIORITY_HIGH_ACCURACY = 3; + + /** + * Convenience constant + * @type {number} + */ + SUCCESS_SETTINGS_SATISFIED = 0; + + /** + * Convenience constant + * @type {number} + */ + SUCCESS_USER_AGREED = 1; + + /** + * Convenience constant + * @type {number} + */ + ERROR_ALREADY_REQUESTING = -1; + + /** + * Convenience constant + * @type {number} + */ + ERROR_INVALID_ACTION = 0; + + /** + * Convenience constant + * @type {number} + */ + ERROR_INVALID_ACCURACY = 1; + + /** + * Convenience constant + * @type {number} + */ + ERROR_EXCEPTION = 1; + + /** + * Convenience constant + * @type {number} + */ + ERROR_CANNOT_CHANGE_ACCURACY = 3; + + /** + * Convenience constant + * @type {number} + */ + ERROR_USER_DISAGREED = 4; + + /** + * Convenience constant + * @type {number} + */ + ERROR_GOOGLE_API_CONNECTION_FAILED = 4; + +} diff --git a/src/plugins/market.ts b/src/@ionic-native/plugins/market/index.ts similarity index 68% rename from src/plugins/market.ts rename to src/@ionic-native/plugins/market/index.ts index a55f48724..dc252e024 100644 --- a/src/plugins/market.ts +++ b/src/@ionic-native/plugins/market/index.ts @@ -1,4 +1,5 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; /** * @name Market * @description @@ -6,9 +7,13 @@ import { Plugin, Cordova } from './plugin'; * * @usage * ``` - * import {Market} from 'ionic-native'; + * import { Market } from '@ionic-native/market'; * - * Market.open('your.package.name'); + * constructor(private market: Market) { } + * + * ... + * + * this.market.open('your.package.name'); * * ``` */ @@ -18,6 +23,7 @@ import { Plugin, Cordova } from './plugin'; pluginRef: 'cordova.plugins.market', repo: 'https://github.com/xmartlabs/cordova-plugin-market' }) +@Injectable() export class Market { /** @@ -30,7 +36,7 @@ export class Market { successName: 'success', errorName: 'failure' }) - static open(appId: string): Promise { return; } + open(appId: string): Promise { return; } /** * Search apps by keyword @@ -43,6 +49,6 @@ export class Market { errorName: 'failure', platforms: ['Android'] }) - static search(keyword: string): Promise { return; } + search(keyword: string): Promise { return; } } diff --git a/src/plugins/media-capture.ts b/src/@ionic-native/plugins/media-capture/index.ts similarity index 84% rename from src/plugins/media-capture.ts rename to src/@ionic-native/plugins/media-capture/index.ts index f28793952..1408ee815 100644 --- a/src/plugins/media-capture.ts +++ b/src/@ionic-native/plugins/media-capture/index.ts @@ -1,4 +1,5 @@ -import { Cordova, CordovaProperty, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, CordovaProperty, Plugin } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; declare var navigator: any; @@ -15,15 +16,18 @@ export interface MediaFile { /** * The file's mime type */ - type: string; + type: string; + /** * The date and time when the file was last modified. */ lastModifiedDate: Date; + /** * The size of the file, in bytes. */ size: number; + /** * Retrieves the format information of the media file. * @param {Function} successCallback @@ -113,11 +117,16 @@ export interface ConfigurationData { * @description * @usage * ```typescript - * import { MediaCapture, MediaFile, CaptureError, CaptureImageOptions } from 'ionic-native'; + * import { MediaCapture, MediaFile, CaptureError, CaptureImageOptions } from '@ionic-native/media-capture'; + * + * + * constructor(private mediaCapture: MediaCapture) { } + * + * ... * * * let options: CaptureImageOptions = { limit: 3 }; - * MediaCapture.captureImage(options) + * this.mediaCapture.captureImage(options) * .then( * (data: MediaFile[]) => console.log(data), * (err: CaptureError) => console.error(err) @@ -139,27 +148,28 @@ export interface ConfigurationData { pluginRef: 'navigator.device.capture', repo: 'https://github.com/apache/cordova-plugin-media-capture' }) +@Injectable() export class MediaCapture { /** * The recording image sizes and formats supported by the device. * @returns {ConfigurationData[]} */ @CordovaProperty - static supportedImageModes: ConfigurationData[]; + supportedImageModes: ConfigurationData[]; /** * The audio recording formats supported by the device. * @returns {ConfigurationData[]} */ @CordovaProperty - static supportedAudioModes: ConfigurationData[]; + supportedAudioModes: ConfigurationData[]; /** * The recording video resolutions and formats supported by the device. * @returns {ConfigurationData[]} */ @CordovaProperty - static supportedVideoModes: ConfigurationData[]; + supportedVideoModes: ConfigurationData[]; /** * Start the audio recorder application and return information about captured audio clip files. @@ -169,7 +179,9 @@ export class MediaCapture { @Cordova({ callbackOrder: 'reverse' }) - static captureAudio(options?: CaptureAudioOptions): Promise { return; } + captureAudio(options?: CaptureAudioOptions): Promise { + return; + } /** * Start the camera application and return information about captured image files. @@ -179,7 +191,9 @@ export class MediaCapture { @Cordova({ callbackOrder: 'reverse' }) - static captureImage(options?: CaptureImageOptions): Promise { return; } + captureImage(options?: CaptureImageOptions): Promise { + return; + } /** * Start the video recorder application and return information about captured video clip files. @@ -189,7 +203,9 @@ export class MediaCapture { @Cordova({ callbackOrder: 'reverse' }) - static captureVideo(options?: CaptureVideoOptions): Promise { return; } + captureVideo(options?: CaptureVideoOptions): Promise { + return; + } /** * is fired if the capture call is successful @@ -199,7 +215,9 @@ export class MediaCapture { eventObservable: true, event: 'pendingcaptureresult' }) - static onPendingCaptureResult(): Observable { return; } + onPendingCaptureResult(): Observable { + return; + } /** * is fired if the capture call is unsuccessful @@ -209,6 +227,8 @@ export class MediaCapture { eventObservable: true, event: 'pendingcaptureerror' }) - static onPendingCaptureError(): Observable { return; } + onPendingCaptureError(): Observable { + return; + } } diff --git a/src/plugins/media.ts b/src/@ionic-native/plugins/media/index.ts similarity index 57% rename from src/plugins/media.ts rename to src/@ionic-native/plugins/media/index.ts index d76a3f87d..cbec602dc 100644 --- a/src/plugins/media.ts +++ b/src/@ionic-native/plugins/media/index.ts @@ -1,144 +1,20 @@ -import { CordovaInstance, Plugin, getPlugin, pluginWarn } from './plugin'; +import { Injectable } from '@angular/core'; +import { CordovaInstance, Plugin, CordovaCheck } from '@ionic-native/core'; declare var Media: any; -export interface MediaError { - code: number; - message: string; -} /** - * @name MediaPlugin - * @description - * @usage - * ```typescript - * import { MediaPlugin } from 'ionic-native'; - * - * - * - * // Create a MediaPlugin instance. Expects path to file or url as argument - * // We can optionally pass a second argument to track the status of the media - * - * const onStatusUpdate = (status) => console.log(status); - * - * const file = new MediaPlugin('path/to/file.mp3', onStatusUpdate); - * - * // Catch the Success & Error Output - * // Platform Quirks - * // iOS calls success on completion of playback only - * // Android calls success on completion of playback AND on release() - * file.init.then(() => { - * console.log('Playback Finished'); - * }, (err) => { - * console.log('somthing went wrong! error code: ' + err.code + ' message: ' + err.message); - * }); - * - * // play the file - * file.play(); - * - * // pause the file - * file.pause(); - * - * // get current playback position - * file.getCurrentPosition().then((position) => { - * console.log(position); - * }); - * - * // get file duration - * file.getDuration(); - * - * // skip to 10 seconds (expects int value in ms) - * file.seekTo(10000); - * - * // stop playing the file - * file.stop(); - * - * // release the native audio resource - * // Platform Quirks: - * // iOS simply create a new instance and the old one will be overwritten - * // Android you must call release() to destroy instances of media when you are done - * file.release(); - * - * // Recording to a file - * var newFile = new MediaPlugin('path/to/file.mp3'); - * newFile.startRecord(); - * - * newFile.stopRecord(); - * - * - * - * ``` + * @hidden */ -@Plugin({ - pluginName: 'MediaPlugin', - repo: 'https://github.com/apache/cordova-plugin-media', - plugin: 'cordova-plugin-media', - pluginRef: 'Media' -}) -export class MediaPlugin { +export class MediaObject { - // Constants - /** - * @private - */ - static MEDIA_NONE: number = 0; - /** - * @private - */ - static MEDIA_STARTING: number = 1; - /** - * @private - */ - static MEDIA_RUNNING: number = 2; - /** - * @private - */ - static MEDIA_PAUSED: number = 3; - /** - * @private - */ - static MEDIA_STOPPED: number = 4; - - // error codes - /** - * @private - */ - static MEDIA_ERR_ABORTED: number = 1; - /** - * @private - */ - static MEDIA_ERR_NETWORK: number = 2; - /** - * @private - */ - static MEDIA_ERR_DECODE: number = 3; - /** - * @private - */ - static MEDIA_ERR_NONE_SUPPORTED: number = 4; - - // Properties - private _objectInstance: any; - init: Promise; - - // Methods /** * Open a media file * @param src {string} A URI containing the audio content. * @param onStatusUpdate {Function} A callback function to be invoked when the status of the file changes */ - constructor(src: string, onStatusUpdate?: Function) { - if (!!getPlugin('Media')) { - this.init = new Promise((resolve, reject) => { - this._objectInstance = new Media(src, resolve, reject, onStatusUpdate); - }); - } else { - pluginWarn({ - pluginName: 'MediaPlugin', - plugin: 'cordova-plugin-media' - }); - } - } + constructor(private _objectInstnace: any) {} /** * Get the current amplitude of the current recording. @@ -248,5 +124,141 @@ export class MediaPlugin { sync: true }) stop(): void { } +} + +/** + * @name MediaPlugin + * @description + * @usage + * ```typescript + * import { MediaPlugin, MediaObject } from '@ionic-native/media'; + * + * + * constructor(private media: MediaPlugin) { } + * + * + * ... + * + * + * // Create a MediaPlugin instance. Expects path to file or url as argument + * // We can optionally pass a second argument to track the status of the media + * + * const onStatusUpdate = (status) => console.log(status); + * + * this.media.create('path/to/file.mp3', onStatusUpdate) + * .then((file: MediaObject) => { + * + * // play the file + * file.play(); + * + * // pause the file + * file.pause(); + * + * // get current playback position + * file.getCurrentPosition().then((position) => { + * console.log(position); + * }); + * + * // get file duration + * file.getDuration().then((duration) => { + * console.log(position); + * }); + * + * // skip to 10 seconds (expects int value in ms) + * file.seekTo(10000); + * + * // stop playing the file + * file.stop(); + * + * // release the native audio resource + * // Platform Quirks: + * // iOS simply create a new instance and the old one will be overwritten + * // Android you must call release() to destroy instances of media when you are done + * file.release(); + * + * }) + * .catch(e => console.log('Error opening media file', e)); + * + * + * // Recording to a file + * this.media.create('path/to/file.mp3') + * .then((file: MedieObject) => { + * + * file.startRecord(); + * + * file.stopRecord(); + * + * }); + * + * ``` + * @classes + * MediaObject + */ +@Plugin({ + pluginName: 'MediaPlugin', + repo: 'https://github.com/apache/cordova-plugin-media', + plugin: 'cordova-plugin-media', + pluginRef: 'Media' +}) +@Injectable() +class MediaPlugin { + + // Constants + /** + * @hidden + */ + MEDIA_NONE: number = 0; + /** + * @hidden + */ + MEDIA_STARTING: number = 1; + /** + * @hidden + */ + MEDIA_RUNNING: number = 2; + /** + * @hidden + */ + MEDIA_PAUSED: number = 3; + /** + * @hidden + */ + MEDIA_STOPPED: number = 4; + + // error codes + /** + * @hidden + */ + MEDIA_ERR_ABORTED: number = 1; + /** + * @hidden + */ + MEDIA_ERR_NETWORK: number = 2; + /** + * @hidden + */ + MEDIA_ERR_DECODE: number = 3; + /** + * @hidden + */ + MEDIA_ERR_NONE_SUPPORTED: number = 4; + + /** + * Open a media file + * @param src {string} A URI containing the audio content. + * @param onStatusUpdate {Function} A callback function to be invoked when the status of the file changes + * @return {Promise} + */ + @CordovaCheck() + create(src: string, onStatusUpdate?: Function): Promise { + + return new Promise((resolve, reject) => { + // Creates a new media object + // Resolves with the media object + // or rejects with the error + const instance = new Media(src, () => resolve(new Media(instance)), reject, onStatusUpdate); + }); + + } } diff --git a/src/plugins/mixpanel.ts b/src/@ionic-native/plugins/mixpanel/index.ts similarity index 57% rename from src/plugins/mixpanel.ts rename to src/@ionic-native/plugins/mixpanel/index.ts index e0fbd97c2..78b636fab 100644 --- a/src/plugins/mixpanel.ts +++ b/src/@ionic-native/plugins/mixpanel/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; declare var mixpanel: any; @@ -9,9 +10,13 @@ declare var mixpanel: any; * * @usage * ``` - * import {Mixpanel} from 'ionic-native'; + * import { Mixpanel, MixpanelPeople } from '@ionic-native/mixpanel'; * - * Mixpanel.init(token) + * constructor(private mixpanel: Mixpanel, private mixpanelPeople: MixpanelPeople) { } + * + * ... + * + * this.mixpanel.init(token) * .then(onSuccess) * .catch(onError); * @@ -25,7 +30,9 @@ declare var mixpanel: any; pluginRef: 'mixpanel', repo: 'https://github.com/samzilverberg/cordova-mixpanel-plugin' }) +@Injectable() export class Mixpanel { + /** * * @param aliasId {string} @@ -33,20 +40,20 @@ export class Mixpanel { * @returns {Promise} */ @Cordova() - static alias(aliasId: string, originalId: string): Promise { return; } + alias(aliasId: string, originalId: string): Promise { return; } /** * * @returns {Promise} */ @Cordova() - static distinctId(): Promise { return; } + distinctId(): Promise { return; } /** * @returns {Promise} */ @Cordova() - static flush(): Promise { return; } + flush(): Promise { return; } /** * @@ -54,7 +61,7 @@ export class Mixpanel { * @returns {Promise} */ @Cordova() - static identify(distinctId: string): Promise { return; } + identify(distinctId: string): Promise { return; } /** * @@ -62,7 +69,7 @@ export class Mixpanel { * @returns {Promise} */ @Cordova() - static init(token: string): Promise { return; } + init(token: string): Promise { return; } /** * @@ -70,14 +77,14 @@ export class Mixpanel { * @returns {Promise} */ @Cordova() - static registerSuperProperties(superProperties: any): Promise { return; } + registerSuperProperties(superProperties: any): Promise { return; } /** * * @returns {Promise} */ @Cordova() - static reset(): Promise { return; } + reset(): Promise { return; } /** * @@ -89,36 +96,26 @@ export class Mixpanel { successIndex: 2, errorIndex: 3 }) - static track(eventName: string, eventProperties?: any): Promise { return; } + track(eventName: string, eventProperties?: any): Promise { return; } /** * * @returns {Promise} */ @Cordova() - static showSurvey(): Promise { return; } - - /** - * - * @returns {MixpanelPeople} - */ - static get people(): typeof MixpanelPeople { - return MixpanelPeople; - }; + showSurvey(): Promise { return; } } /** - * @private + * @hidden */ +@Injectable() +@Plugin({ + plugin: 'cordova-plugin-mixpanel', + pluginRef: 'mixpanel.people', + pluginName: 'Mixpanel' +}) export class MixpanelPeople { - /** - * @private - */ - static plugin: string = 'cordova-plugin-mixpanel'; - /** - * @private - */ - static pluginRef: string = 'mixpanel.people'; /** * @@ -126,7 +123,7 @@ export class MixpanelPeople { * @return {Promise} */ @Cordova() - static identify(distinctId: string): Promise { return; } + identify(distinctId: string): Promise { return; } /** * @@ -134,7 +131,7 @@ export class MixpanelPeople { * @return {Promise} */ @Cordova() - static increment(peopleProperties: any): Promise { return; } + increment(peopleProperties: any): Promise { return; } /** * @@ -142,7 +139,7 @@ export class MixpanelPeople { * @return {Promise} */ @Cordova() - static setPushId(pushId: string): Promise { return; } + setPushId(pushId: string): Promise { return; } /** * @@ -150,7 +147,7 @@ export class MixpanelPeople { * @return {Promise} */ @Cordova() - static set(peopleProperties: any): Promise { return; } + set(peopleProperties: any): Promise { return; } /** * @@ -158,5 +155,6 @@ export class MixpanelPeople { * @return {Promise} */ @Cordova() - static setOnce(peopleProperties: any): Promise { return; } + setOnce(peopleProperties: any): Promise { return; } + } diff --git a/src/plugins/music-controls.ts b/src/@ionic-native/plugins/music-controls/index.ts similarity index 82% rename from src/plugins/music-controls.ts rename to src/@ionic-native/plugins/music-controls/index.ts index 23d721420..0828f8916 100644 --- a/src/plugins/music-controls.ts +++ b/src/@ionic-native/plugins/music-controls/index.ts @@ -1,4 +1,5 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; export interface MusicControlsOptions { @@ -10,14 +11,14 @@ export interface MusicControlsOptions { hasPrev: boolean; hasNext: boolean; hasClose: boolean; - album:string; + album: string; duration: number; - elapsed:number; + elapsed: number; ticker: string; } /** - * @name MusicControls + * @name Music Controls * @description * Music controls for Cordova applications. * Display a 'media' notification with play/pause, previous, next buttons, allowing the user to control the play. @@ -25,9 +26,13 @@ export interface MusicControlsOptions { * * @usage * ``` - * import {MusicControls} from 'ionic-native'; + * import { MusicControls } from '@ionic-native/music-controls'; * - * MusicControls.create({ + * constructor(private musicControls: MusicControls) { } + * + * ... + * + * this.musicControls.create({ * track : 'Time is Running Out', // optional, default : '' * artist : 'Muse', // optional, default : '' * cover : 'albums/absolution.jpg', // optional, default : nothing @@ -51,7 +56,7 @@ export interface MusicControlsOptions { * ticker : 'Now playing "Time is Running Out"' * }); * - * MusicControls.subscribe().subscribe(action => { + * this.musicControls.subscribe().subscribe(action => { * * switch(action) { * case 'music-controls-next': @@ -86,9 +91,9 @@ export interface MusicControlsOptions { * * }); * - * MusicControls.listen(); // activates the observable above + * this.musicControls.listen(); // activates the observable above * - * MusicControls.updateIsPlaying(true); + * this.musicControls.updateIsPlaying(true); * * * ``` @@ -101,6 +106,7 @@ export interface MusicControlsOptions { pluginRef: 'MusicControls', repo: 'https://github.com/homerours/cordova-music-controls-plugin' }) +@Injectable() export class MusicControls { /** @@ -109,14 +115,14 @@ export class MusicControls { * @returns {Promise} */ @Cordova() - static create(options: MusicControlsOptions): Promise {return; } + create(options: MusicControlsOptions): Promise {return; } /** * Destroy the media controller * @returns {Promise} */ @Cordova() - static destroy(): Promise {return; } + destroy(): Promise {return; } /** * Subscribe to the events of the media controller @@ -125,25 +131,25 @@ export class MusicControls { @Cordova({ observable: true }) - static subscribe(): Observable {return; } + subscribe(): Observable {return; } /** * Start listening for events, this enables the Observable from the subscribe method */ @Cordova({sync: true}) - static listen(): void {} + listen(): void {} /** * Toggle play/pause: * @param isPlaying {boolean} */ @Cordova() - static updateIsPlaying(isPlaying: boolean): void {} + updateIsPlaying(isPlaying: boolean): void {} /** * Toggle dismissable: * @param dismissable {boolean} */ @Cordova() - static updateDismissable(dismissable: boolean): void {} + updateDismissable(dismissable: boolean): void {} } diff --git a/src/plugins/native-audio.ts b/src/@ionic-native/plugins/native-audio/index.ts similarity index 63% rename from src/plugins/native-audio.ts rename to src/@ionic-native/plugins/native-audio/index.ts index 5af8a6d4c..01cfdf6f3 100644 --- a/src/plugins/native-audio.ts +++ b/src/@ionic-native/plugins/native-audio/index.ts @@ -1,26 +1,31 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; /** - * @name NativeAudio + * @name Native Audio * @description Native Audio Playback * @usage * ```typescript - * import {NativeAudio} from 'ionic-native'; + * import { NativeAudio } from '@ionic-native/native-audio'; * - * NativeAudio.preloadSimple('uniqueId1', 'path/to/file.mp3').then(onSuccess, onError); - * NativeAudio.preloadComplex('uniqueId2', 'path/to/file2.mp3', 1, 1, 0).then(onSuccess, onError); + * constructor(private nativeAudio: NativeAudio) { } * - * NativeAudio.play('uniqueId1').then(onSuccess, onError); + * ... + * + * this.nativeAudio.preloadSimple('uniqueId1', 'path/to/file.mp3').then(onSuccess, onError); + * this.nativeAudio.preloadComplex('uniqueId2', 'path/to/file2.mp3', 1, 1, 0).then(onSuccess, onError); + * + * this.nativeAudio.play('uniqueId1').then(onSuccess, onError); * * // can optionally pass a callback to be called when the file is done playing - * NativeAudio.play('uniqueId1', () => console.log('uniqueId1 is done playing')); + * this.nativeAudio.play('uniqueId1', () => console.log('uniqueId1 is done playing')); * - * NativeAudio.loop('uniqueId2').then(onSuccess, onError); + * this.nativeAudio.loop('uniqueId2').then(onSuccess, onError); * - * NativeAudio.setVolumeForComplexAsset('uniqueId2', 0.6).then(onSuccess,onError); + * this.nativeAudio.setVolumeForComplexAsset('uniqueId2', 0.6).then(onSuccess,onError); * - * NativeAudio.stop('uniqueId1').then(onSuccess,onError); + * this.nativeAudio.stop('uniqueId1').then(onSuccess,onError); * - * NativeAudio.unload('uniqueId1').then(onSuccess,onError); + * this.nativeAudio.unload('uniqueId1').then(onSuccess,onError); * * ``` */ @@ -30,6 +35,7 @@ import { Plugin, Cordova } from './plugin'; pluginRef: 'plugins.NativeAudio', repo: 'https://github.com/floatinghotpot/cordova-plugin-nativeaudio' }) +@Injectable() export class NativeAudio { /** * Loads an audio file into memory. Optimized for short clips / single shots (up to five seconds). Cannot be stopped / looped. @@ -38,7 +44,7 @@ export class NativeAudio { * @returns {Promise} */ @Cordova() - static preloadSimple(id: string, assetPath: string): Promise {return; } + preloadSimple(id: string, assetPath: string): Promise {return; } /** * Loads an audio file into memory. Optimized for background music / ambient sound. Uses highlevel native APIs with a larger footprint. (iOS: AVAudioPlayer). Can be stopped / looped and used with multiple voices. Can be faded in and out using the delay parameter. @@ -50,7 +56,7 @@ export class NativeAudio { * @returns {Promise} */ @Cordova() - static preloadComplex(id: string, assetPath: string, volume: number, voices: number, delay: number): Promise {return; } + preloadComplex(id: string, assetPath: string, volume: number, voices: number, delay: number): Promise {return; } /** * Plays an audio asset @@ -62,7 +68,7 @@ export class NativeAudio { successIndex: 1, errorIndex: 2 }) - static play(id: string, completeCallback?: Function): Promise {return; } + play(id: string, completeCallback?: Function): Promise {return; } /** * Stops playing an audio @@ -70,7 +76,7 @@ export class NativeAudio { * @returns {Promise} */ @Cordova() - static stop(id: string): Promise {return; } + stop(id: string): Promise {return; } /** * Loops an audio asset infinitely, this only works for complex assets @@ -78,7 +84,7 @@ export class NativeAudio { * @return {Promise} */ @Cordova() - static loop(id: string): Promise {return; } + loop(id: string): Promise {return; } /** * Unloads an audio file from memory @@ -86,7 +92,7 @@ export class NativeAudio { * @returns {Promise} */ @Cordova() - static unload(id: string): Promise {return; } + unload(id: string): Promise {return; } /** * Changes the volume for preloaded complex assets. @@ -95,6 +101,6 @@ export class NativeAudio { * @returns {Promise} */ @Cordova() - static setVolumeForComplexAsset(id: string, volume: number): Promise {return; } + setVolumeForComplexAsset(id: string, volume: number): Promise {return; } } diff --git a/src/plugins/native-geocoder.ts b/src/@ionic-native/plugins/native-geocoder/index.ts similarity index 78% rename from src/plugins/native-geocoder.ts rename to src/@ionic-native/plugins/native-geocoder/index.ts index 9841286f5..19e9ef7b1 100644 --- a/src/plugins/native-geocoder.ts +++ b/src/@ionic-native/plugins/native-geocoder/index.ts @@ -1,20 +1,25 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; /** * @beta - * @name NativeGeocoder + * @name Native Geocoder * @description * Cordova plugin for native forward and reverse geocoding * * @usage * ```typescript - * import { NativeGeocoder, NativeGeocoderReverseResult, NativeGeocoderForwardResult } from 'ionic-native'; + * import { NativeGeocoder, NativeGeocoderReverseResult, NativeGeocoderForwardResult } from '@ionic-native/native-geocoder'; * - * NativeGeocoder.reverseGeocode(52.5072095, 13.1452818) + * constructor(private nativeGeocoder: NativeGeocoder) { } + * + * ... + * + * this.nativeGeocoder.reverseGeocode(52.5072095, 13.1452818) * .then((result: NativeGeocoderReverseResult) => console.log("The address is " + result.street + " in " + result.countryCode)) * .catch((error: any) => console.log(error)); * - * NativeGeocoder.forwardGeocode("Berlin") + * this.nativeGeocoder.forwardGeocode("Berlin") * .then((coordinates: NativeGeocoderForwardResult) => console.log("The coordinates are latitude=" + coordinates.latitude + " and longitude=" + coordinates.longitude)) * .catch((error: any) => console.log(error)); * ``` @@ -29,6 +34,7 @@ import { Plugin, Cordova } from './plugin'; repo: 'https://github.com/sebastianbaar/cordova-plugin-nativegeocoder', platforms: ['iOS', 'Android'] }) +@Injectable() export class NativeGeocoder { /** @@ -40,7 +46,7 @@ export class NativeGeocoder { @Cordova({ callbackOrder: 'reverse' }) - static reverseGeocode(latitude: number, longitude: number): Promise { return; } + reverseGeocode(latitude: number, longitude: number): Promise { return; } /** * Forward geocode a given address to find coordinates @@ -50,7 +56,7 @@ export class NativeGeocoder { @Cordova({ callbackOrder: 'reverse' }) - static forwardGeocode(addressString: string): Promise { return; } + forwardGeocode(addressString: string): Promise { return; } } diff --git a/src/plugins/native-page-transitions.ts b/src/@ionic-native/plugins/native-page-transitions/index.ts similarity index 74% rename from src/plugins/native-page-transitions.ts rename to src/@ionic-native/plugins/native-page-transitions/index.ts index fbe367740..6b123df95 100644 --- a/src/plugins/native-page-transitions.ts +++ b/src/@ionic-native/plugins/native-page-transitions/index.ts @@ -1,4 +1,5 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; export interface NativeTransitionOptions { direction?: string; @@ -16,13 +17,17 @@ export interface NativeTransitionOptions { } /** - * @name NativePageTransitions + * @name Native Page Transitions * @description * The Native Page Transitions plugin uses native hardware acceleration to animate your transitions between views. You have complete control over the type of transition, the duration, and direction. * * @usage * ``` - * import {NativePageTransitions, NativeTransitionOptions} from 'ionic-native'; + * import { NativePageTransitions, NativeTransitionOptions } from '@ionic-native/native-page-transitions'; + * + * constructor(private nativePageTransitions: NativePageTransitions) { } + * + * ... * * let options: NativeTransitionOptions = { * direction: 'up', @@ -36,7 +41,7 @@ export interface NativeTransitionOptions { * fixedPixelsBottom: 60 * }; * - * NativePageTransitions.slide(options) + * this.nativePageTransitions.slide(options) * .then(onSuccess) * .catch(onError); * @@ -49,6 +54,7 @@ export interface NativeTransitionOptions { repo: 'https://github.com/Telerik-Verified-Plugins/NativePageTransitions', platforms: ['iOS', 'Android', 'Windows Phone'] }) +@Injectable() export class NativePageTransitions { /** * Perform a slide animation @@ -56,7 +62,7 @@ export class NativePageTransitions { * @returns {Promise} */ @Cordova() - static slide(options: NativeTransitionOptions): Promise { return; } + slide(options: NativeTransitionOptions): Promise { return; } /** * Perform a flip animation @@ -64,7 +70,7 @@ export class NativePageTransitions { * @returns {Promise} */ @Cordova() - static flip(options: NativeTransitionOptions): Promise { return; } + flip(options: NativeTransitionOptions): Promise { return; } /** * Perform a fade animation @@ -72,7 +78,7 @@ export class NativePageTransitions { * @returns {Promise} */ @Cordova({platforms: ['iOS', 'Android']}) - static fade(options: NativeTransitionOptions): Promise { return; } + fade(options: NativeTransitionOptions): Promise { return; } /** @@ -81,7 +87,7 @@ export class NativePageTransitions { * @returns {Promise} */ @Cordova({platforms: ['iOS', 'Android']}) - static drawer(options: NativeTransitionOptions): Promise { return; } + drawer(options: NativeTransitionOptions): Promise { return; } @@ -91,7 +97,6 @@ export class NativePageTransitions { * @returns {Promise} */ @Cordova({platforms: ['iOS']}) - static curl(options: NativeTransitionOptions): Promise { return; } + curl(options: NativeTransitionOptions): Promise { return; } } - diff --git a/src/plugins/nativestorage.ts b/src/@ionic-native/plugins/native-storage/index.ts similarity index 61% rename from src/plugins/nativestorage.ts rename to src/@ionic-native/plugins/native-storage/index.ts index a0b0a2572..6d730cf5e 100644 --- a/src/plugins/nativestorage.ts +++ b/src/@ionic-native/plugins/native-storage/index.ts @@ -1,21 +1,26 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; /** - * @name NativeStorage + * @name Native Storage * @description Native storage of variables in Android and iOS * * @usage * ```typescript - * import { NativeStorage } from 'ionic-native'; + * import { NativeStorage } from '@ionic-native/native-storage'; * - * NativeStorage.setItem('myitem', {property: 'value', anotherProperty: 'anotherValue'}) + * constructor(private nativeStorage: NativeStorage) { } + * + * ... + * + * this.nativeStorage.setItem('myitem', {property: 'value', anotherProperty: 'anotherValue'}) * .then( * () => console.log('Stored item!'), * error => console.error('Error storing item', error) * ); * - * NativeStorage.getItem('myitem') + * this.nativeStorage.getItem('myitem') * .then( * data => console.log(data), * error => console.error(error) @@ -28,6 +33,7 @@ import { Cordova, Plugin } from './plugin'; pluginRef: 'NativeStorage', repo: 'https://github.com/TheCocoaProject/cordova-plugin-nativestorage' }) +@Injectable() export class NativeStorage { /** * Stores a value @@ -36,7 +42,7 @@ export class NativeStorage { * @returns {Promise} */ @Cordova() - static setItem(reference: string, value: any): Promise {return; } + setItem(reference: string, value: any): Promise {return; } /** * Gets a stored item @@ -44,7 +50,7 @@ export class NativeStorage { * @returns {Promise} */ @Cordova() - static getItem(reference: string): Promise {return; } + getItem(reference: string): Promise {return; } /** * Removes a single stored item @@ -52,13 +58,13 @@ export class NativeStorage { * @returns {Promise} */ @Cordova() - static remove(reference: string): Promise {return; } + remove(reference: string): Promise {return; } /** * Removes all stored values. * @returns {Promise} */ @Cordova() - static clear(): Promise {return; } + clear(): Promise {return; } } diff --git a/src/plugins/navigationbar.ts b/src/@ionic-native/plugins/navigation-bar/index.ts similarity index 67% rename from src/plugins/navigationbar.ts rename to src/@ionic-native/plugins/navigation-bar/index.ts index 302fc1e8c..0882d426b 100644 --- a/src/plugins/navigationbar.ts +++ b/src/@ionic-native/plugins/navigation-bar/index.ts @@ -1,18 +1,23 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; /** * @beta - * @name NavigationBar + * @name Navigation Bar * @description * The NavigationBar plugin can you to hide and auto hide the android navigation bar. * * @usage * ```typescript - * import { NavigationBar } from 'ionic-native'; + * import { NavigationBar } from '@ionic-native/navigation-bar'; + * + * constructor(private navigationBar: NavigationBar) { } + * + * ... * * let autoHide: boolean = true; - * NavigationBar.hide(autoHide); + * this.navigationBar.hide(autoHide); * ``` */ @Plugin({ @@ -22,6 +27,7 @@ import { Cordova, Plugin } from './plugin'; repo: 'https://github.com/cranberrygame/cordova-plugin-navigationbar', platforms: ['Android'] }) +@Injectable() export class NavigationBar { /** @@ -34,7 +40,7 @@ export class NavigationBar { successName: 'success', errorName: 'failure' }) - static setUp(autohide?: boolean): Promise { return; } + setUp(autohide?: boolean): Promise { return; } /** * Hide the navigation bar.  @@ -45,6 +51,6 @@ export class NavigationBar { successName: 'success', errorName: 'failure' }) - static hideNavigationBar(): Promise { return; } + hideNavigationBar(): Promise { return; } } diff --git a/src/plugins/network.ts b/src/@ionic-native/plugins/network/index.ts similarity index 80% rename from src/plugins/network.ts rename to src/@ionic-native/plugins/network/index.ts index 36199ebbe..ff028dd3a 100644 --- a/src/plugins/network.ts +++ b/src/@ionic-native/plugins/network/index.ts @@ -1,4 +1,5 @@ -import {Cordova, CordovaProperty, Plugin, CordovaFunctionOverride} from './plugin'; +import { Injectable } from '@angular/core'; +import {Cordova, CordovaProperty, Plugin, CordovaFunctionOverride} from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; @@ -11,10 +12,14 @@ declare var navigator: any; * * @usage * ```typescript - * import { Network } from 'ionic-native'; + * import { Network } from '@ionic-native/network'; + * + * constructor(private network: Network) { } + * + * ... * * // watch network for a disconnect - * let disconnectSubscription = Network.onDisconnect().subscribe(() => { + * let disconnectSubscription = this.network.onDisconnect().subscribe(() => { * console.log('network was disconnected :-('); * }); * @@ -23,7 +28,7 @@ declare var navigator: any; * * * // watch network for a connection - * let connectSubscription = Network.onConnect().subscribe(() => { + * let connectSubscription = this.network.onConnect().subscribe(() => { * console.log('network connected!');
 * // We just got a connection but we need to wait briefly *
 // before we determine the connection type. Might need to wait
 @@ -49,6 +54,7 @@ declare var navigator: any; platforms: ['Amazon Fire OS', 'iOS', 'Android', 'BlackBerry 10', 'Windows Phone 7', 'Windows Phone 8', 'Windows', 'Firefox OS', 'Browser'], pluginRef: 'navigator.connection' }) +@Injectable() export class Network { /** @@ -56,28 +62,28 @@ export class Network { * @return {string} */ @CordovaProperty - static type: string; + type: string; /** * Downlink Max Speed * @return {string} */ @CordovaProperty - static downlinkMax: string; + downlinkMax: string; /** * Returns an observable to watch connection changes * @return {Observable} */ @CordovaFunctionOverride() - static onchange(): Observable { return; } + onchange(): Observable { return; } /** * Returns an observable to watch connection type changes * @return {Observable} */ @CordovaFunctionOverride() - static ontypechange(): Observable { return; } + ontypechange(): Observable { return; } /** * Get notified when the device goes offline @@ -87,7 +93,7 @@ export class Network { eventObservable: true, event: 'offline' }) - static onDisconnect(): Observable { return; } + onDisconnect(): Observable { return; } /** * Get notified when the device goes online @@ -97,6 +103,6 @@ export class Network { eventObservable: true, event: 'online' }) - static onConnect(): Observable { return; } + onConnect(): Observable { return; } } diff --git a/src/plugins/nfc.ts b/src/@ionic-native/plugins/nfc/index.ts similarity index 66% rename from src/plugins/nfc.ts rename to src/@ionic-native/plugins/nfc/index.ts index 9629d8a17..b20f141dd 100644 --- a/src/plugins/nfc.ts +++ b/src/@ionic-native/plugins/nfc/index.ts @@ -1,4 +1,5 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; declare let window: any; /** @@ -16,10 +17,14 @@ declare let window: any; * * @usage * ``` - * import {NFC, Ndef} from 'ionic-native'; + * import { NFC, Ndef } from '@ionic-native/nfc'; * - * let message = Ndef.textRecord('Hello world'); - * NFC.share([message]).then(onSuccess).catch(onError); + * constructor(private nfc: NFC, private ndef: Ndef) { } + * + * ... + * + * let message = this.ndef.textRecord('Hello world'); + * this.nfc.share([message]).then(onSuccess).catch(onError); * * ``` */ @@ -29,6 +34,7 @@ declare let window: any; pluginRef: 'nfc', repo: 'https://github.com/chariotsolutions/phonegap-nfc' }) +@Injectable() export class NFC { /** * Registers an event listener for any NDEF tag. @@ -43,7 +49,7 @@ export class NFC { clearFunction: 'removeNdefListener', clearWithArgs: true }) - static addNdefListener(onSuccess?: Function, onFailure?: Function): Observable {return; } + addNdefListener(onSuccess?: Function, onFailure?: Function): Observable {return; } /** * Registers an event listener for tags matching any tag type. @@ -58,7 +64,7 @@ export class NFC { clearFunction: 'removeTagDiscoveredListener', clearWithArgs: true }) - static addTagDiscoveredListener(onSuccess?: Function, onFailure?: Function): Observable {return; } + addTagDiscoveredListener(onSuccess?: Function, onFailure?: Function): Observable {return; } /** * Registers an event listener for NDEF tags matching a specified MIME type. @@ -74,7 +80,7 @@ export class NFC { clearFunction: 'removeMimeTypeListener', clearWithArgs: true }) - static addMimeTypeListener(mimeType: string, onSuccess?: Function, onFailure?: Function): Observable {return; } + addMimeTypeListener(mimeType: string, onSuccess?: Function, onFailure?: Function): Observable {return; } /** * Registers an event listener for formatable NDEF tags. @@ -87,7 +93,7 @@ export class NFC { successIndex: 0, errorIndex: 3 }) - static addNdefFormatableListener(onSuccess?: Function, onFailure?: Function): Observable {return; } + addNdefFormatableListener(onSuccess?: Function, onFailure?: Function): Observable {return; } /** * Qrites an NdefMessage to a NFC tag. @@ -95,13 +101,13 @@ export class NFC { * @returns {Promise} */ @Cordova() - static write(message: any[]): Promise {return; } + write(message: any[]): Promise {return; } /** * Makes a NFC tag read only. **Warning** this is permanent. * @returns {Promise} */ @Cordova() - static makeReadyOnly(): Promise {return; } + makeReadyOnly(): Promise {return; } /** * Shares an NDEF Message via peer-to-peer. @@ -109,20 +115,20 @@ export class NFC { * @returns {Promise} */ @Cordova() - static share(message: any[]): Promise {return; } + share(message: any[]): Promise {return; } /** * Stop sharing NDEF data via peer-to-peer. * @returns {Promise} */ @Cordova() - static unshare(): Promise {return; } + unshare(): Promise {return; } /** * Erase a NDEF tag */ @Cordova() - static erase(): Promise {return; } + erase(): Promise {return; } /** * Send a file to another device via NFC handover. @@ -130,77 +136,71 @@ export class NFC { * @returns {Promise} */ @Cordova() - static handover(uris: string[]): Promise {return; } + handover(uris: string[]): Promise {return; } /** * Stop sharing NDEF data via NFC handover. * @returns {Promise} */ @Cordova() - static stopHandover(): Promise {return; } + stopHandover(): Promise {return; } /** * Show the NFC settings on the device. * @returns {Promise} */ @Cordova() - static showSettings(): Promise {return; } + showSettings(): Promise {return; } /** * Check if NFC is available and enabled on this device. * @returns {Promise} */ @Cordova() - static enabled(): Promise {return; } + enabled(): Promise {return; } /** * Convert bytes to string * @param bytes {number[]} * @returns {string} */ @Cordova({ sync: true }) - static bytesToString(bytes: number[]): string {return; } + bytesToString(bytes: number[]): string {return; } /** * Convert string to bytes * @param str {string} * @returns {number[]} */ @Cordova({ sync: true }) - static stringToBytes(str: string): number[] {return; }; + stringToBytes(str: string): number[] {return; }; /** * Convert bytes to hex string * @param bytes {number[]} * @returns {string} */ @Cordova({ sync: true }) - static bytesToHexString(bytes: number[]): string {return; }; + bytesToHexString(bytes: number[]): string {return; }; } /** - * @private + * @hidden */ +@Injectable() +@Plugin({ + pluginName: 'NFC', + plugin: 'phonegap-nfc', + pluginRef: 'ndef' +}) export class Ndef { - /** - * @private - */ - static pluginName = 'NFC'; - /** - * @private - */ - static plugin = 'phonegap-nfc'; - /** - * @private - */ - static pluginRef = 'ndef'; @Cordova({ sync: true }) - static uriRecord(uri: string): any { return; } + uriRecord(uri: string): any { return; } @Cordova({ sync: true }) - static textRecord(text: string): any { return; } + textRecord(text: string): any { return; } @Cordova({ sync: true }) - static mimeMediaRecord(mimeType: string, payload: string): any { return; } + mimeMediaRecord(mimeType: string, payload: string): any { return; } @Cordova({ sync: true }) - static androidApplicationRecord(packageName: string): any { return; } + androidApplicationRecord(packageName: string): any { return; } } diff --git a/src/plugins/onesignal.ts b/src/@ionic-native/plugins/onesignal/index.ts similarity index 90% rename from src/plugins/onesignal.ts rename to src/@ionic-native/plugins/onesignal/index.ts index f19b8867c..3b505334e 100644 --- a/src/plugins/onesignal.ts +++ b/src/@ionic-native/plugins/onesignal/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; export interface OSNotification { @@ -269,21 +270,25 @@ export enum OSActionType { * * @usage * ```typescript - * import { OneSignal } from 'ionic-native'; + * import { OneSignal } from '@ionic-native/onesignal'; * - * OneSignal.startInit('b2f7f966-d8cc-11e4-bed1-df8f05be55ba', '703322744261'); + * constructor(private oneSignal: OneSignal) { } * - * OneSignal.inFocusDisplaying(OneSignal.OSInFocusDisplayOption.InAppAlert); + * ... * - * OneSignal.handleNotificationReceived().subscribe(() => { + * this.oneSignal.startInit('b2f7f966-d8cc-11e4-bed1-df8f05be55ba', '703322744261'); + * + * this.oneSignal.inFocusDisplaying(this.oneSignal.OSInFocusDisplayOption.InAppAlert); + * + * this.oneSignal.handleNotificationReceived().subscribe(() => { * // do something when notification is received * }); * - * OneSignal.handleNotificationOpened().subscribe(() => { + * this.oneSignal.handleNotificationOpened().subscribe(() => { * // do something when a notification is opened * }); * - * OneSignal.endInit(); + * this.oneSignal.endInit(); * ``` * @interfaces * OSNotification @@ -302,12 +307,13 @@ export enum OSActionType { repo: 'https://github.com/OneSignal/OneSignal-Cordova-SDK', platforms: ['Android', 'iOS', 'Windows', 'FireOS'] }) +@Injectable() export class OneSignal { /** * constants to use in inFocusDisplaying() */ - static OSInFocusDisplayOption = { + OSInFocusDisplayOption = { None: 0, InAppAlert : 1, Notification : 2 @@ -321,7 +327,7 @@ export class OneSignal { * @returns {any} */ @Cordova({ sync: true }) - static startInit(appId: string, googleProjectNumber?: string): any { return; } + startInit(appId: string, googleProjectNumber?: string): any { return; } /** * Callback to run when a notification is received, whether it was displayed or not. @@ -331,7 +337,7 @@ export class OneSignal { @Cordova({ observable: true }) - static handleNotificationReceived(): Observable { return; } + handleNotificationReceived(): Observable { return; } /** * Callback to run when a notification is tapped on from the notification shade (**ANDROID**) or notification @@ -343,7 +349,7 @@ export class OneSignal { @Cordova({ observable: true }) - static handleNotificationOpened(): Observable { return; } + handleNotificationOpened(): Observable { return; } /** * **iOS** - Settings for iOS apps @@ -357,7 +363,7 @@ export class OneSignal { * @returns {any} */ @Cordova({ sync: true }) - static iOSSettings(settings: { + iOSSettings(settings: { kOSSettingsKeyAutoPrompt: boolean; kOSSettingsKeyInAppLaunchURL: boolean; }): any { return; } @@ -368,7 +374,7 @@ export class OneSignal { * @returns {any} */ @Cordova({ sync: true }) - static endInit(): any { return; } + endInit(): any { return; } /** * Retrieve a list of tags that have been set on the user from the OneSignal server. @@ -376,7 +382,7 @@ export class OneSignal { * @returns {Promise} Returns a Promise that resolves when tags are recieved. */ @Cordova() - static getTags(): Promise { return; } + getTags(): Promise { return; } /** * Lets you retrieve the OneSignal user id and device token. @@ -389,7 +395,7 @@ export class OneSignal { * pushToken {string} A push token is a Google/Apple assigned identifier(unique per device per app). */ @Cordova() - static getIds(): Promise<{userId: string; pushToken: string}> { return; } + getIds(): Promise<{userId: string; pushToken: string}> { return; } /** @@ -400,7 +406,7 @@ export class OneSignal { * @param {string} Value to set on the key. NOTE: Passing in a blank String deletes the key, you can also call deleteTag. */ @Cordova({ sync: true }) - static sendTag(key: string, value: string): void { } + sendTag(key: string, value: string): void { } /** * Tag a user based on an app event of your choosing so later you can create segments on [onesignal.com](https://onesignal.com/) to target these users. @@ -409,7 +415,7 @@ export class OneSignal { * @param {string} Pass a json object with key/value pairs like: {key: "value", key2: "value2"} */ @Cordova({ sync: true }) - static sendTags(json: any): void { } + sendTags(json: any): void { } /** * Deletes a tag that was previously set on a user with `sendTag` or `sendTags`. Use `deleteTags` if you need to delete more than one. @@ -417,7 +423,7 @@ export class OneSignal { * @param {string} Key to remove. */ @Cordova({ sync: true }) - static deleteTag(key: string): void { } + deleteTag(key: string): void { } /** * Deletes tags that were previously set on a user with `sendTag` or `sendTags`. @@ -425,14 +431,14 @@ export class OneSignal { * @param {Array} Keys to remove. */ @Cordova({ sync: true }) - static deleteTags(keys: string[]): void { } + deleteTags(keys: string[]): void { } /** * Call this when you would like to prompt an iOS user to accept push notifications with the default system prompt. * Only works if you set `kOSSettingsAutoPrompt` to `false` in `iOSSettings` */ @Cordova({ sync: true }) - static registerForPushNotifications(): void { } + registerForPushNotifications(): void { } /** * Warning: @@ -444,7 +450,7 @@ export class OneSignal { * @param {boolean} false to disable vibrate, true to re-enable it. */ @Cordova({ sync: true }) - static enableVibrate(enable: boolean): void { } + enableVibrate(enable: boolean): void { } /** * Warning: @@ -456,7 +462,7 @@ export class OneSignal { * @param {boolean} false to disable sound, true to re-enable it. */ @Cordova({ sync: true }) - static enableSound(enable: boolean): void { } + enableSound(enable: boolean): void { } /** * @@ -466,7 +472,7 @@ export class OneSignal { * @returns {any} */ @Cordova({ sync: true }) - static inFocusDisplaying(displayOption: OSDisplayType): any { return; } + inFocusDisplaying(displayOption: OSDisplayType): any { return; } /** * You can call this method with false to opt users out of receiving all notifications through OneSignal. @@ -475,7 +481,7 @@ export class OneSignal { * @param {boolean} enable */ @Cordova({ sync: true }) - static setSubscription(enable: boolean): void { } + setSubscription(enable: boolean): void { } /** * @@ -483,20 +489,20 @@ export class OneSignal { * @returns {Promise} Returns a Promise that resolves if the notification was send successfully. */ @Cordova() - static postNotification(notificationObj: OSNotification): Promise { return; } + postNotification(notificationObj: OSNotification): Promise { return; } /** * Prompts the user for location permission to allow geotagging based on the "Location radius" filter on the OneSignal dashboard. */ @Cordova({ sync: true }) - static promptLocation(): void { } + promptLocation(): void { } /** * * @param email {string} */ @Cordova({ sync: true }) - static syncHashedEmail(email: string): void { } + syncHashedEmail(email: string): void { } /** * Enable logging to help debug if you run into an issue setting up OneSignal. @@ -507,7 +513,7 @@ export class OneSignal { * @param {loglevel} contains two properties: logLevel (for console logging) and visualLevel (for dialog messages) */ @Cordova({ sync: true }) - static setLogLevel(logLevel: { + setLogLevel(logLevel: { logLevel: number, visualLevel: number }): void { } diff --git a/src/plugins/pay-pal.ts b/src/@ionic-native/plugins/paypal/index.ts similarity index 93% rename from src/plugins/pay-pal.ts rename to src/@ionic-native/plugins/paypal/index.ts index ef043f1fc..e81e744ef 100644 --- a/src/plugins/pay-pal.ts +++ b/src/@ionic-native/plugins/paypal/index.ts @@ -1,4 +1,5 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; /** * @name PayPal * @description @@ -6,19 +7,24 @@ import { Plugin, Cordova } from './plugin'; * * @usage * ``` - * import {PayPal, PayPalPayment, PayPalConfiguration} from "ionic-native"; + * import { PayPal, PayPalPayment, PayPalConfiguration } from '@ionic-native/pay-pal'; * - * PayPal.init({ - * "PayPalEnvironmentProduction": "YOUR_PRODUCTION_CLIENT_ID", - * "PayPalEnvironmentSandbox": "YOUR_SANDBOX_CLIENT_ID" + * constructor(private payPal: PayPal) { } + * + * ... + * + * + * this.payPal.init({ + * PayPalEnvironmentProduction: "YOUR_PRODUCTION_CLIENT_ID", + * PayPalEnvironmentSandbox: "YOUR_SANDBOX_CLIENT_ID" * }).then(() => { * // Environments: PayPalEnvironmentNoNetwork, PayPalEnvironmentSandbox, PayPalEnvironmentProduction - * PayPal.prepareToRender('PayPalEnvironmentSandbox', new PayPalConfiguration({ + * this.payPal.prepareToRender('PayPalEnvironmentSandbox', new PayPalConfiguration({ * // Only needed if you get an "Internal Service Error" after PayPal login! * //payPalShippingAddressOption: 2 // PayPalShippingAddressOptionPayPal * })).then(() => { * let payment = new PayPalPayment('3.33', 'USD', 'Description', 'sale'); - * PayPal.renderSinglePaymentUI(payment).then(() => { + * this.payPal.renderSinglePaymentUI(payment).then(() => { * // Successfully paid * * // Example sandbox response @@ -63,13 +69,14 @@ import { Plugin, Cordova } from './plugin'; pluginRef: 'PayPalMobile', repo: 'https://github.com/paypal/PayPal-Cordova-Plugin' }) +@Injectable() export class PayPal { /** * Retrieve the version of the PayPal iOS SDK library. Useful when contacting support. * @returns {Promise} */ @Cordova() - static version(): Promise {return; } + version(): Promise {return; } /** * You must preconnect to PayPal to prepare the device for processing payments. @@ -81,7 +88,7 @@ export class PayPal { * @returns {Promise} */ @Cordova() - static init(clientIdsForEnvironments: PayPalEnvironment): Promise {return; } + init(clientIdsForEnvironments: PayPalEnvironment): Promise {return; } /** * You must preconnect to PayPal to prepare the device for processing payments. @@ -93,7 +100,7 @@ export class PayPal { * @returns {Promise} */ @Cordova() - static prepareToRender(environment: string, configuration: PayPalConfiguration): Promise {return; } + prepareToRender(environment: string, configuration: PayPalConfiguration): Promise {return; } /** * Start PayPal UI to collect payment from the user. @@ -104,7 +111,7 @@ export class PayPal { * @returns {Promise} */ @Cordova() - static renderSinglePaymentUI(payment: PayPalPayment): Promise {return; } + renderSinglePaymentUI(payment: PayPalPayment): Promise {return; } /** * Once a user has consented to future payments, when the user subsequently initiates a PayPal payment @@ -117,14 +124,14 @@ export class PayPal { * @returns {Promise} */ @Cordova() - static clientMetadataID(): Promise {return; } + clientMetadataID(): Promise {return; } /** * Please Read Docs on Future Payments at https://github.com/paypal/PayPal-iOS-SDK#future-payments * @returns {Promise} */ @Cordova() - static renderFuturePaymentUI(): Promise {return; } + renderFuturePaymentUI(): Promise {return; } /** * Please Read Docs on Profile Sharing at https://github.com/paypal/PayPal-iOS-SDK#profile-sharing @@ -134,7 +141,7 @@ export class PayPal { * @returns {Promise} */ @Cordova() - static renderProfileSharingUI(scopes: string[]): Promise {return; } + renderProfileSharingUI(scopes: string[]): Promise {return; } } export interface PayPalEnvironment { @@ -143,7 +150,7 @@ export interface PayPalEnvironment { } /** - * @private + * @hidden */ export class PayPalPayment { constructor(amount: string, currency: string, shortDescription: string, intent: string, details?: PayPalPaymentDetails) { @@ -207,7 +214,7 @@ export class PayPalPayment { } /** - * @private + * @hidden */ export class PayPalItem { /** @@ -250,7 +257,7 @@ export class PayPalItem { } /** - * @private + * @hidden */ export class PayPalPaymentDetails { /** @@ -279,7 +286,7 @@ export class PayPalPaymentDetails { } /** - * @private + * @hidden */ export interface PayPalConfigurationOptions { /** @@ -377,7 +384,7 @@ export interface PayPalConfigurationOptions { sandboxUserPin?: string; } /** - * @private + * @hidden */ export class PayPalConfiguration implements PayPalConfigurationOptions { /** @@ -417,7 +424,7 @@ export class PayPalConfiguration implements PayPalConfigurationOptions { } /** - * @private + * @hidden */ export class PayPalShippingAddress { /** diff --git a/src/plugins/pedometer.ts b/src/@ionic-native/plugins/pedometer/index.ts similarity index 84% rename from src/plugins/pedometer.ts rename to src/@ionic-native/plugins/pedometer/index.ts index 770881756..b88f9a9e8 100644 --- a/src/plugins/pedometer.ts +++ b/src/@ionic-native/plugins/pedometer/index.ts @@ -1,10 +1,10 @@ -import { Plugin, Cordova } from './plugin'; +import { Plugin, Cordova } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; +import { Injectable } from '@angular/core'; /** * Interface of a pedometer data object which is returned by watching for new data or by recieving historical data */ - export interface IPedometerData { startDate?: number; endDate?: number; @@ -17,7 +17,7 @@ export interface IPedometerData { /** * @name Pedometer * @description - * Fetch pedestrian-related pedometer data, + * Fetch pedestrian-related pedometer data, * such as step counts and other information about the distance travelled. * * @usage @@ -41,6 +41,7 @@ export interface IPedometerData { repo: 'https://github.com/leecrossley/cordova-plugin-pedometer', platforms: ['Android', 'iOS'] }) +@Injectable() export class Pedometer { /** @@ -48,7 +49,7 @@ export class Pedometer { * @return {Promise} Returns a promise that resolves when feature is supported (true) or not supported (false) */ @Cordova() - static isStepCountingAvailable(): Promise { return; } + isStepCountingAvailable(): Promise { return; } /** * Distance estimation indicates the ability to use step information to supply the approximate distance travelled by the user. @@ -57,7 +58,7 @@ export class Pedometer { * @return {Promise} Returns a promise that resolves when feature is supported (true) or not supported (false) */ @Cordova() - static isDistanceAvailable(): Promise { return; } + isDistanceAvailable(): Promise { return; } /** * Floor counting indicates the ability to count the number of floors the user walks up or down using stairs. @@ -66,12 +67,12 @@ export class Pedometer { * @return {Promise} Returns a promise that resolves when feature is supported (true) or not supported (false) */ @Cordova() - static isFloorCountingAvailable(): Promise { return; } + isFloorCountingAvailable(): Promise { return; } /** * Starts the delivery of recent pedestrian-related data to your Cordova app. - * - * When the app is suspended, the delivery of updates stops temporarily. + * + * When the app is suspended, the delivery of updates stops temporarily. * Upon returning to foreground or background execution, the pedometer object begins updates again. * @return {Observable} Returns a Observable that recieves repeatly data from pedometer in background. */ @@ -79,18 +80,18 @@ export class Pedometer { observable: true, clearFunction: 'stopPedometerUpdates' }) - static startPedometerUpdates(): Observable { return; } + startPedometerUpdates(): Observable { return; } /** * Stops the delivery of recent pedestrian data updates to your Cordova app. * @return {Promise} Returns a promise that resolves when pedometer watching was stopped */ @Cordova() - static stopPedometerUpdates(): Promise { return; } + stopPedometerUpdates(): Promise { return; } /** * Retrieves the data between the specified start and end dates. - * The startDate and endDate options are required and can be constructed in any valid JavaScript way + * The startDate and endDate options are required and can be constructed in any valid JavaScript way * (e.g. new Date(2015, 4, 1, 15, 20, 00) is also valid, as is milliseconds). * Only works on iOS. * @param {any} options start date and en date where you want to get pedometer data @@ -99,5 +100,6 @@ export class Pedometer { @Cordova({ callbackOrder: 'reverse' }) - static queryData(options: { startDate: Date, endDate: Date }): Promise { return; } + queryData(options: { startDate: Date, endDate: Date }): Promise { return; } + } diff --git a/src/plugins/photo-library.ts b/src/@ionic-native/plugins/photo-library/index.ts similarity index 82% rename from src/plugins/photo-library.ts rename to src/@ionic-native/plugins/photo-library/index.ts index 5c31b5c10..9bd605978 100644 --- a/src/plugins/photo-library.ts +++ b/src/@ionic-native/plugins/photo-library/index.ts @@ -1,8 +1,9 @@ -import { Plugin, Cordova, CordovaFiniteObservable } from './plugin'; +import { Plugin, Cordova, CordovaFiniteObservable } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; +import { Injectable } from '@angular/core'; /** - * @name PhotoLibrary + * @name Photo Library * @description * The PhotoLibrary plugin allows access to photos from device by url. So you can use plain img tag to display photos and their thumbnails, and different 3rd party libraries as well. * Saving photos and videos to the library is also supported. @@ -10,10 +11,12 @@ import { Observable } from 'rxjs/Observable'; * * @usage * ``` - * import { PhotoLibrary } from 'ionic-native'; + * import { PhotoLibrary } from '@ionic-native/photo-library'; * - * PhotoLibrary.requestAuthorization().then(() => { - * PhotoLibrary.getLibrary().subscribe({ + * constructor(private photoLibrary: PhotoLibrary) { } + * + * this.photoLibrary.requestAuthorization().then(() => { + * this.photoLibrary.getLibrary().subscribe({ * next: library => { * library.forEach(function(libraryItem) { * console.log(libraryItem.id); // ID of the photo @@ -43,6 +46,7 @@ import { Observable } from 'rxjs/Observable'; repo: 'https://github.com/terikon/cordova-plugin-photo-library', install: 'ionic plugin add cordova-plugin-photo-library --variable PHOTO_LIBRARY_USAGE_DESCRIPTION="To choose photos"' }) +@Injectable() export class PhotoLibrary { /** @@ -55,7 +59,7 @@ export class PhotoLibrary { resultFinalPredicate: (result: {isLastChunk: boolean}) => { return result.isLastChunk; }, resultTransform: (result: {library: LibraryItem[]}) => { return result.library; }, }) - static getLibrary(options?: GetLibraryOptions): Observable { return; } + getLibrary(options?: GetLibraryOptions): Observable { return; } /** * Asks user permission to access photo library. @@ -65,7 +69,7 @@ export class PhotoLibrary { @Cordova({ callbackOrder: 'reverse', }) - static requestAuthorization(options?: RequestAuthorizationOptions): Promise { return; } + requestAuthorization(options?: RequestAuthorizationOptions): Promise { return; } /** * Returns list of photo albums on device. @@ -74,7 +78,7 @@ export class PhotoLibrary { @Cordova({ callbackOrder: 'reverse', }) - static getAlbums(): Promise { return; } + getAlbums(): Promise { return; } /** * Provides means to request URL of thumbnail, with specified size or quality. @@ -86,7 +90,7 @@ export class PhotoLibrary { successIndex: 1, errorIndex: 2 }) - static getThumbnailURL(photo: string | LibraryItem, options?: GetThumbnailOptions): Promise { return; } + getThumbnailURL(photo: string | LibraryItem, options?: GetThumbnailOptions): Promise { return; } /** * Provides means to request photo URL by id. @@ -98,7 +102,7 @@ export class PhotoLibrary { successIndex: 1, errorIndex: 2 }) - static getPhotoURL(photo: string | LibraryItem, options?: GetPhotoOptions): Promise { return; } + getPhotoURL(photo: string | LibraryItem, options?: any): Promise { return; } /** * Returns thumbnail as Blob. @@ -110,7 +114,7 @@ export class PhotoLibrary { successIndex: 1, errorIndex: 2 }) - static getThumbnail(photo: string | LibraryItem, options?: GetThumbnailOptions): Promise { return; } + getThumbnail(photo: string | LibraryItem, options?: GetThumbnailOptions): Promise { return; } /** * Returns photo as Blob. @@ -122,7 +126,7 @@ export class PhotoLibrary { successIndex: 1, errorIndex: 2 }) - static getPhoto(photo: string | LibraryItem, options?: GetPhotoOptions): Promise { return; } + getPhoto(photo: string | LibraryItem, options?: any): Promise { return; } /** * Saves image to specified album. Album will be created if not exists. @@ -136,7 +140,7 @@ export class PhotoLibrary { successIndex: 2, errorIndex: 3 }) - static saveImage(url: string, album: AlbumItem | string, options?: GetThumbnailOptions): Promise { return; } + saveImage(url: string, album: AlbumItem | string, options?: GetThumbnailOptions): Promise { return; } /** * Saves video to specified album. Album will be created if not exists. @@ -148,10 +152,13 @@ export class PhotoLibrary { successIndex: 2, errorIndex: 3 }) - static saveVideo(url: string, album: AlbumItem | string): Promise { return; } + saveVideo(url: string, album: AlbumItem | string): Promise { return; } } +/** + * @hidden + */ export interface LibraryItem { /** * Local id of the photo @@ -174,6 +181,9 @@ export interface LibraryItem { albumIds?: string[]; } +/** + * @hidden + */ export interface AlbumItem { /** * Local id of the album @@ -182,6 +192,9 @@ export interface AlbumItem { title: string; } +/** + * @hidden + */ export interface GetLibraryOptions { thumbnailWidth?: number; thumbnailHeight?: number; @@ -192,16 +205,19 @@ export interface GetLibraryOptions { includeAlbumData?: boolean; } +/** + * @hidden + */ export interface RequestAuthorizationOptions { read?: boolean; write?: boolean; } +/** + * @hidden + */ export interface GetThumbnailOptions { thumbnailWidth?: number; thumbnailHeight?: number; quality?: number; } - -export interface GetPhotoOptions { -} diff --git a/src/plugins/photo-viewer.ts b/src/@ionic-native/plugins/photo-viewer/index.ts similarity index 53% rename from src/plugins/photo-viewer.ts rename to src/@ionic-native/plugins/photo-viewer/index.ts index 26aeab94a..8636d564a 100644 --- a/src/plugins/photo-viewer.ts +++ b/src/@ionic-native/plugins/photo-viewer/index.ts @@ -1,14 +1,19 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; /** * @name Photo Viewer * @description This plugin can display your image in full screen with the ability to pan, zoom, and share the image. * @usage * ```typescript - * import { PhotoViewer } from 'ionic-native'; + * import { PhotoViewer } from '@ionic-native/photo-viewer'; * - * PhotoViewer.show('https://mysite.com/path/to/image.jpg'); + * constructor(private photoViewer: PhotoViewer) { } * - * PhotoViewer.show('https://mysite.com/path/to/image.jpg', 'My image title', {share: false}); + * ... + * + * this.photoViewer.show('https://mysite.com/path/to/image.jpg'); + * + * this.photoViewer.show('https://mysite.com/path/to/image.jpg', 'My image title', {share: false}); * ``` */ @Plugin({ @@ -17,6 +22,7 @@ import { Plugin, Cordova } from './plugin'; pluginRef: 'PhotoViewer', repo: 'https://github.com/sarriaroman/photoviewer' }) +@Injectable() export class PhotoViewer { /** * Shows an image in full screen @@ -25,5 +31,5 @@ export class PhotoViewer { * @param options {any} */ @Cordova({sync: true}) - static show(url: string, title?: string, options?: {share?: boolean}): void { } + show(url: string, title?: string, options?: {share?: boolean}): void { } } diff --git a/src/plugins/pin-dialog.ts b/src/@ionic-native/plugins/pin-dialog/index.ts similarity index 65% rename from src/plugins/pin-dialog.ts rename to src/@ionic-native/plugins/pin-dialog/index.ts index bd5d3547d..b0597f8c8 100644 --- a/src/plugins/pin-dialog.ts +++ b/src/@ionic-native/plugins/pin-dialog/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; /** @@ -7,10 +8,14 @@ import { Cordova, Plugin } from './plugin'; * * @usage * ```typescript - * import { PinDialog } from 'ionic-native'; + * import { PinDialog } from '@ionic-native/pin-dialog'; * * - * PinDialog.prompt('Enter your PIN', 'Verify PIN', ['OK', 'Cancel']) + * constructor(private pinDialog: PinDialog) { } + * + * ... + * + * this.pinDialog.prompt('Enter your PIN', 'Verify PIN', ['OK', 'Cancel']) * .then( * (result: any) => { * if (result.buttonIndex == 1) console.log('User clicked OK, value is: ', result.input1); @@ -25,6 +30,7 @@ import { Cordova, Plugin } from './plugin'; pluginRef: 'plugins.pinDialog', repo: 'https://github.com/Paldom/PinDialog' }) +@Injectable() export class PinDialog { /** * Show pin dialog @@ -37,6 +43,6 @@ export class PinDialog { successIndex: 1, errorIndex: 4 // no error callback }) - static prompt(message: string, title: string, buttons: string[]): Promise<{ buttonIndex: number, input1: string }> { return; } + prompt(message: string, title: string, buttons: string[]): Promise<{ buttonIndex: number, input1: string }> { return; } } diff --git a/src/plugins/pinterest.ts b/src/@ionic-native/plugins/pinterest/index.ts similarity index 81% rename from src/plugins/pinterest.ts rename to src/@ionic-native/plugins/pinterest/index.ts index dc667c7fd..8779111f7 100644 --- a/src/plugins/pinterest.ts +++ b/src/@ionic-native/plugins/pinterest/index.ts @@ -1,4 +1,5 @@ -import { Plugin, Cordova, CordovaProperty } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova, CordovaProperty } from '@ionic-native/core'; export interface PinterestUser { /** @@ -133,27 +134,31 @@ export interface PinterestPin { * * @usage * ``` - * import { Pinterest, PinterestUser, PinterestPin, PinterestBoard } from 'ionic-native'; + * import { Pinterest, PinterestUser, PinterestPin, PinterestBoard } from '@ionic-native/pinterest'; + * + * constructor(private pinterest: Pinterest) { } + * + * ... * * const scopes = [ - * Pinterest.SCOPES.READ_PUBLIC, - * Pinterest.SCOPES.WRITE_PUBLIC, - * Pinterest.SCOPES.READ_RELATIONSHIPS, - * Pinterest.SCOPES.WRITE_RELATIONSHIPS + * this.pinterest.SCOPES.READ_PUBLIC, + * this.pinterest.SCOPES.WRITE_PUBLIC, + * this.pinterest.SCOPES.READ_RELATIONSHIPS, + * this.pinterest.SCOPES.WRITE_RELATIONSHIPS * ]; * - * Pinterest.login(scopes) + * this.pinterest.login(scopes) * .then(res => console.log('Logged in!', res)) * .catch(err => console.error('Error loggin in', err)); * - * Pinterest.getMyPins() + * this.pinterest.getMyPins() * .then((pins: Array) => console.log(pins)) * .catch(err => console.error(err)); * - * Pinterest.getMe() + * this.pinterest.getMe() * .then((user: PinterestUser) => console.log(user)); * - * Pinterest.getMyBoards() + * this.pinterest.getMyBoards() * .then((boards: Array) => console.log(boards)); * * ``` @@ -168,8 +173,10 @@ export interface PinterestPin { pluginRef: 'cordova.plugins.Pinterest', repo: 'https://github.com/zyramedia/cordova-plugin-pinterest', install: 'ionic plugin add cordova-plugin-pinterest --variable APP_ID=YOUR_APP_ID', + installVariables: ['APP_ID'], platforms: ['Android', 'iOS'] }) +@Injectable() export class Pinterest { /** @@ -189,7 +196,7 @@ export class Pinterest { * @returns {Promise} The response object will contain the user's profile data, as well as the access token (if you need to use it elsewhere, example: send it to your server and perform actions on behalf of the user). */ @Cordova() - static login(scopes: string[]): Promise { return; } + login(scopes: string[]): Promise { return; } /** * Gets the authenticated user's profile @@ -199,7 +206,7 @@ export class Pinterest { @Cordova({ callbackOrder: 'reverse' }) - static getMe(fields?: string): Promise { return; } + getMe(fields?: string): Promise { return; } /** * @@ -210,7 +217,7 @@ export class Pinterest { @Cordova({ callbackOrder: 'reverse' }) - static getMyPins(fields?: string, limit?: number): Promise> { return; } + getMyPins(fields?: string, limit?: number): Promise> { return; } /** * @@ -221,7 +228,7 @@ export class Pinterest { @Cordova({ callbackOrder: 'reverse' }) - static getMyBoards(fields?: string, limit?: number): Promise> { return; } + getMyBoards(fields?: string, limit?: number): Promise> { return; } /** * Get the authenticated user's likes. @@ -232,7 +239,7 @@ export class Pinterest { @Cordova({ callbackOrder: 'reverse' }) - static getMyLikes(fields?: string, limit?: number): Promise> { return; } + getMyLikes(fields?: string, limit?: number): Promise> { return; } /** * Get the authenticated user's followers. @@ -243,7 +250,7 @@ export class Pinterest { @Cordova({ callbackOrder: 'reverse' }) - static getMyFollowers(fields?: string, limit?: number): Promise> { return; } + getMyFollowers(fields?: string, limit?: number): Promise> { return; } /** * Get the authenticated user's followed boards. @@ -254,7 +261,7 @@ export class Pinterest { @Cordova({ callbackOrder: 'reverse' }) - static getMyFollowedBoards(fields?: string, limit?: number): Promise> { return; } + getMyFollowedBoards(fields?: string, limit?: number): Promise> { return; } /** * Get the authenticated user's followed interests. @@ -265,7 +272,7 @@ export class Pinterest { @Cordova({ callbackOrder: 'reverse' }) - static getMyFollowedInterests(fields?: string, limit?: number): Promise { return; } + getMyFollowedInterests(fields?: string, limit?: number): Promise { return; } /** * Get a user's profile. @@ -277,7 +284,7 @@ export class Pinterest { successIndex: 1, errorIndex: 2 }) - static getUser(username: string, fields?: string): Promise { return; } + getUser(username: string, fields?: string): Promise { return; } /** * Get a board's data. @@ -289,7 +296,7 @@ export class Pinterest { successIndex: 1, errorIndex: 2 }) - static getBoard(boardId: string, fields?: string): Promise { return; } + getBoard(boardId: string, fields?: string): Promise { return; } /** * Get Pins of a specific board. @@ -302,7 +309,7 @@ export class Pinterest { successIndex: 1, errorIndex: 2 }) - static getBoardPins(boardId: string, fields?: string, limit?: number): Promise> { return; } + getBoardPins(boardId: string, fields?: string, limit?: number): Promise> { return; } /** * Delete a board. @@ -310,7 +317,7 @@ export class Pinterest { * @returns {Promise} */ @Cordova() - static deleteBoard(boardId: string): Promise { return; } + deleteBoard(boardId: string): Promise { return; } /** * Create a new board for the authenticated user. @@ -322,7 +329,7 @@ export class Pinterest { successIndex: 2, errorIndex: 3 }) - static createBoard(name: string, desc?: string): Promise { return; } + createBoard(name: string, desc?: string): Promise { return; } /** * Get a Pin by ID. @@ -334,7 +341,7 @@ export class Pinterest { successIndex: 1, errorIndex: 2 }) - static getPin(pinId: string, fields?: string): Promise { return; } + getPin(pinId: string, fields?: string): Promise { return; } /** * Deletes a pin @@ -342,7 +349,7 @@ export class Pinterest { * @returns {Promise} */ @Cordova() - static deletePin(pinId: string): Promise { return; } + deletePin(pinId: string): Promise { return; } /** * Creates a Pin @@ -356,6 +363,6 @@ export class Pinterest { successIndex: 4, errorIndex: 5 }) - static createPin(note: string, boardId: string, imageUrl: string, link?: string): Promise { return; } + createPin(note: string, boardId: string, imageUrl: string, link?: string): Promise { return; } } diff --git a/src/plugins/power-management.ts b/src/@ionic-native/plugins/power-management/index.ts similarity index 73% rename from src/plugins/power-management.ts rename to src/@ionic-native/plugins/power-management/index.ts index 3e60aff1f..911940d6a 100644 --- a/src/plugins/power-management.ts +++ b/src/@ionic-native/plugins/power-management/index.ts @@ -1,15 +1,20 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; /** - * @name PowerManagement + * @name Power Management * @description * The PowerManagement plugin offers access to the devices power-management functionality. * It should be used for applications which keep running for a long time without any user interaction. * * @usage * ``` - * import {PowerManagement} from 'ionic-native'; + * import { PowerManagement } from '@ionic-native/power-management'; * - * PowerManagement.acquire() + * constructor(private powerManagement: PowerManagement) { } + * + * ... + * + * this.powerManagement.acquire() * .then(onSuccess) * .catch(onError); * @@ -21,27 +26,28 @@ import { Plugin, Cordova } from './plugin'; pluginRef: 'powerManagement', repo: 'https://github.com/Viras-/cordova-plugin-powermanagement' }) +@Injectable() export class PowerManagement { /** * Acquire a wakelock by calling this. * @returns {Promise} */ @Cordova() - static acquire(): Promise {return; } + acquire(): Promise {return; } /** * This acquires a partial wakelock, allowing the screen to be dimmed. * @returns {Promise} */ @Cordova() - static dim(): Promise {return; } + dim(): Promise {return; } /** * Release the wakelock. It's important to do this when you're finished with the wakelock, to avoid unnecessary battery drain. * @returns {Promise} */ @Cordova() - static release(): Promise {return; } + release(): Promise {return; } /** * By default, the plugin will automatically release a wakelock when your app is paused (e.g. when the screen is turned off, or the user switches to another app). @@ -50,5 +56,5 @@ export class PowerManagement { * @returns {Promise} */ @Cordova() - static setReleaseOnPause(set: boolean): Promise {return; } + setReleaseOnPause(set: boolean): Promise {return; } } diff --git a/src/plugins/printer.ts b/src/@ionic-native/plugins/printer/index.ts similarity index 79% rename from src/plugins/printer.ts rename to src/@ionic-native/plugins/printer/index.ts index 92feab752..69d5e2470 100644 --- a/src/plugins/printer.ts +++ b/src/@ionic-native/plugins/printer/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; declare var cordova: any; @@ -45,9 +46,13 @@ export interface PrintOptions { * @description Prints documents or HTML rendered content * @usage * ```typescript - * import {Printer, PrintOptions} from 'ionic-native'; + * import { Printer, PrintOptions } from '@ionic-native/printer'; * - * Printer.isAvailable().then(onSuccess, onError); + * constructor(private printer: Printer) { } + * + * ... + * + * this.printer.isAvailable().then(onSuccess, onError); * * let options: PrintOptions = { * name: 'MyDocument', @@ -57,7 +62,7 @@ export interface PrintOptions { * grayscale: true * }; * - * Printer.print(content, options).then(onSuccess, onError); + * this.p.print(content, options).then(onSuccess, onError); * ``` * @interfaces * PrintOptions @@ -69,6 +74,7 @@ export interface PrintOptions { repo: 'https://github.com/katzer/cordova-plugin-printer.git', platforms: ['Android', 'iOS'] }) +@Injectable() export class Printer { /** @@ -76,7 +82,7 @@ export class Printer { * @returns {Promise} */ @Cordova() - static isAvailable(): Promise { return; } + isAvailable(): Promise { return; } /** * Sends content to the printer. @@ -85,6 +91,6 @@ export class Printer { * @returns {Promise} */ @Cordova() - static print(content: string | HTMLElement, options?: PrintOptions): Promise { return; } + print(content: string | HTMLElement, options?: PrintOptions): Promise { return; } } diff --git a/src/plugins/push.ts b/src/@ionic-native/plugins/push/index.ts similarity index 65% rename from src/plugins/push.ts rename to src/@ionic-native/plugins/push/index.ts index c8e8d144a..cba37b291 100644 --- a/src/plugins/push.ts +++ b/src/@ionic-native/plugins/push/index.ts @@ -1,5 +1,8 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin, CordovaInstance, checkAvailability } from '@ionic-native/core'; +import { Observable } from 'rxjs/Observable'; +declare var window: any; export type EventResponse = RegistrationEventResponse | NotificationEventResponse | Error; @@ -40,8 +43,6 @@ export interface NotificationEventResponse { } /** - * TODO: document all possible properties (not just Android) - * * Loosened up with a dictionary notation, but all non-defined properties need to use (map['prop']) notation * * Ideally the developer would overload (merged declaration) this or create a new interface that would extend this one @@ -60,117 +61,6 @@ export interface NotificationEventAdditionalData { notId?: string; } -export interface PushNotification { - /** - * The event registration will be triggered on each successful registration with the 3rd party push service. - * @param event - * @param callback - */ - on(event: 'registration', callback: (response: RegistrationEventResponse) => any): void; - /** - * The event notification will be triggered each time a push notification is received by a 3rd party push service on the device. - * @param event - * @param callback - */ - on(event: 'notification', callback: (response: NotificationEventResponse) => any): void; - /** - * The event error will trigger when an internal error occurs and the cache is aborted. - * @param event - * @param callback - */ - on(event: 'error', callback: (response: Error) => any): void; - /** - * - * @param event Name of the event to listen to. See below(above) for all the event names. - * @param callback is called when the event is triggered. - * @param event - * @param callback - */ - on(event: string, callback: (response: EventResponse) => any): void; - - off(event: 'registration', callback: (response: RegistrationEventResponse) => any): void; - off(event: 'notification', callback: (response: NotificationEventResponse) => any): void; - off(event: 'error', callback: (response: Error) => any): void; - /** - * As stated in the example, you will have to store your event handler if you are planning to remove it. - * @param event Name of the event type. The possible event names are the same as for the push.on function. - * @param callback handle to the function to get removed. - * @param event - * @param callback - */ - off(event: string, callback: (response: EventResponse) => any): void; - - /** - * The unregister method is used when the application no longer wants to receive push notifications. - * Beware that this cleans up all event handlers previously registered, - * so you will need to re-register them if you want them to function again without an application reload. - * @param successHandler - * @param errorHandler - */ - unregister(successHandler: () => any, errorHandler?: () => any): void; - - /** - * The subscribe method is used when the application wants to subscribe a new topic to receive push notifications. - * @param {string} topic: Topic to subscribe to. - * @param successHandler - * @param errorHandler - */ - subscribe(topic: string, successHandler: () => any, errorHandler?: () => any): void; - - /** - * The unsubscribe method is used when the application no longer wants to receive push notifications - * from a specific topic but continue to receive other push messages. - * @param {string} topic: Topic to subscribe to. - * @param successHandler - * @param errorHandler - */ - unsubscribe(topic: string, successHandler: () => any, errorHandler?: () => any): void; - - /** - * iOS & android only - * - * Set the badge count visible when the app is not running - * - * The count is an integer indicating what number should show up in the badge. - * Passing 0 will clear the badge. - * Each notification event contains a data.count value which can be used to set the badge to correct number. - * @param successHandler - * @param errorHandler - * @param count - */ - setApplicationIconBadgeNumber(successHandler: () => any, errorHandler: () => any, count?: number): void; - /** - * iOS only - * - * Get the current badge count visible when the app is not running - * successHandler gets called with an integer which is the current badge count - * @param successHandler - * @param errorHandler - */ - getApplicationIconBadgeNumber(successHandler: (count: number) => any, errorHandler: () => any): void; - - /** - * iOS only - * - * Tells the OS that you are done processing a background push notification. - * successHandler gets called when background push processing is successfully completed. - * @param successHandler - * @param errorHandler - * @param id - */ - finish(successHandler: () => any, errorHandler: () => any, id?: string): void; - - /** - * iOS & android only - * - * Tells the OS to clear all notifications from the Notification Center. - * successHandler gets called when the api successfully clears the notifications - * @param successHandler - * @param errorHandler - */ - clearAllNotifications(successHandler: () => any, errorHandler: () => any): void; -} - export interface IOSPushOptions { /** * Maps to the project number in the Google Developer Console. Setting this @@ -301,12 +191,10 @@ export interface AndroidPushOptions { export interface PushOptions { ios?: IOSPushOptions; android?: AndroidPushOptions; - windows?: {}; + windows?: any; } -declare var PushNotification: { - new (): PushNotification -}; +export type PushEvent = 'registration' | 'error' | 'notification'; /** * @name Push @@ -319,48 +207,150 @@ declare var PushNotification: { * * @usage * ```typescript - * import { Push } from 'ionic-native'; + * import { Push, PushObject, PushOptions } from '@ionic-native/push'; + * + * constructor(private push: Push) { } + * + * ... + * + * const options: PushOptions = { + * android: { + * senderID: '12345679' + * }, + * ios: { + * alert: 'true', + * badge: true, + * sound: 'false' + * }, + * windows: {} + * }; + * + * const pushObject: PushObject = this.push.init(options); + * + * pushObject.on('notification').subscribe(notification => console.log('Received a notification', notification)); + * + * pushObject.on('error').subscribe(error => console.error('Error with Push plugin', error)); + * + * * ``` + * + * @interfaces + * RegistrationEventResponse + * NotificationEventResponse + * NotificationEventAdditionalData + * IOSPushOptions + * AndroidPushOptions + * PushOptions */ @Plugin({ pluginName: 'Push', plugin: 'phonegap-plugin-push', pluginRef: 'PushNotification', repo: 'https://github.com/phonegap/phonegap-plugin-push', - install: 'ionic plugin add phonegap-plugin-push --variable SENDER_ID=XXXXXXXXX' + install: 'ionic plugin add phonegap-plugin-push --variable SENDER_ID=XXXXXXXXX', + installVariables: ['SENDER_ID'] }) +@Injectable() export class Push { /** - * Initialize the plugin on the native side. - * - * ``` - * var push = Push.init({ - * android: { - * senderID: '12345679' - * }, - * ios: { - * alert: 'true', - * badge: true, - * sound: 'false' - * }, - * windows: {} - * }); - * ``` - * - * @param {PushOptions} options The Push [options](https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/API.md#parameters). - * @returns {PushNotification} Returns a new [PushNotification](https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/API.md#pushonevent-callback) object. + * Init push notifications + * @param options {PushOptions} + * @return {PushObject} */ - @Cordova({ - sync: true - }) - static init(options: PushOptions): PushNotification { return; } + init(options: PushOptions): PushObject { + return new PushObject(options); + } + +} + +/** + * @hidden + */ +export class PushObject { + + private _objectInstance: any; + + constructor(options: PushOptions) { + if (checkAvailability('PushNotification', 'init', 'PushNotification') === true) { + this._objectInstance = window.PushNotification.init(options); + } + } /** * Check whether the push notification permission has been granted. * @return {Promise<{isEnabled: boolean}>} Returns a Promise that resolves with an object with one property: isEnabled, a boolean that indicates if permission has been granted. */ @Cordova() - static hasPermission(): Promise<{ isEnabled: boolean }> { return; } + hasPermission(): Promise<{ isEnabled: boolean }> { return; } + + /** + * Adds an event listener + * @param event {string} + * @return {Observable} + */ + @CordovaInstance({ + observable: true, + clearFunction: 'off', + clearWithArgs: true + }) + on(event: PushEvent): Observable { return; } + + /** + * The unregister method is used when the application no longer wants to receive push notifications. + * Beware that this cleans up all event handlers previously registered, + * so you will need to re-register them if you want them to function again without an application reload. + */ + @CordovaInstance() + unregister(): Promise { return; } + + /** + * Set the badge count visible when the app is not running + * + * The count is an integer indicating what number should show up in the badge. + * Passing 0 will clear the badge. + * Each notification event contains a data.count value which can be used to set the badge to correct number. + * @param count + */ + @CordovaInstance({ + callbackOrder: 'reverse' + }) + setApplicationIconBadgeNumber(count?: number): Promise { return; }; + /** + * Get the current badge count visible when the app is not running + * successHandler gets called with an integer which is the current badge count + */ + @CordovaInstance() + getApplicationIconBadgeNumber(): Promise { return; } + + /** + * iOS only + * Tells the OS that you are done processing a background push notification. + * successHandler gets called when background push processing is successfully completed. + */ + @CordovaInstance() + finish(): Promise { return; } + + /** + * Tells the OS to clear all notifications from the Notification Center + */ + @CordovaInstance() + clearAllNotifications(): Promise { return; } + + /** + * The subscribe method is used when the application wants to subscribe a new topic to receive push notifications. + * @param topic {string} Topic to subscribe to. + * @return {Promise} + */ + @CordovaInstance() + subscribe(topic: string): Promise { return; } + + /** + * The unsubscribe method is used when the application no longer wants to receive push notifications from a specific topic but continue to receive other push messages. + * @param topic {string} Topic to unsubscribe from. + * @return {Promise} + */ + @CordovaInstance() + unsubscribe(topic: string): Promise { return; } } diff --git a/src/plugins/rollbar.ts b/src/@ionic-native/plugins/rollbar/index.ts similarity index 63% rename from src/plugins/rollbar.ts rename to src/@ionic-native/plugins/rollbar/index.ts index 3ef3ac788..2a8a1e4c6 100644 --- a/src/plugins/rollbar.ts +++ b/src/@ionic-native/plugins/rollbar/index.ts @@ -1,4 +1,5 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; /** * @beta @@ -8,9 +9,13 @@ import { Plugin, Cordova } from './plugin'; * * @usage * ``` - * import { Rollbar } from 'ionic-native'; + * import { Rollbar } from '@ionic-native/rollbar'; * - * Rollbar.init(); + * constructor(private rollbar: Rollbar) { } + * + * ... + * + * this.rollbar.init(); * * ``` */ @@ -20,8 +25,10 @@ import { Plugin, Cordova } from './plugin'; pluginRef: 'Rollbar', repo: 'https://github.com/Resgrid/cordova-plugins-rollbar', platforms: ['Android', 'iOS'], - install: 'ionic plugin add resgrid-cordova-plugins-rollbar --variable ROLLBAR_ACCESS_TOKEN="YOUR_ROLLBAR_ACCEESS_TOKEN" --variable ROLLBAR_ENVIRONMENT="ROLLBAR_ENVIRONMENT"' + install: 'ionic plugin add resgrid-cordova-plugins-rollbar --variable ROLLBAR_ACCESS_TOKEN="YOUR_ROLLBAR_ACCEESS_TOKEN" --variable ROLLBAR_ENVIRONMENT="ROLLBAR_ENVIRONMENT"', + installVariables: ['ROLLBAR_ACCESS_TOKEN', 'ROLLBAR_ENVIRONMENT'] }) +@Injectable() export class Rollbar { /** @@ -29,6 +36,6 @@ export class Rollbar { * @return {Promise} Returns a promise that resolves when the plugin successfully initializes */ @Cordova() - static init(): Promise { return; } + init(): Promise { return; } } diff --git a/src/plugins/safari-view-controller.ts b/src/@ionic-native/plugins/safari-view-controller/index.ts similarity index 73% rename from src/plugins/safari-view-controller.ts rename to src/@ionic-native/plugins/safari-view-controller/index.ts index dd5012ed7..7b503f613 100644 --- a/src/plugins/safari-view-controller.ts +++ b/src/@ionic-native/plugins/safari-view-controller/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; export interface SafariViewControllerOptions { url?: string; @@ -12,19 +13,21 @@ export interface SafariViewControllerOptions { } /** - * @name SafariViewController + * @name Safari View Controller * @description * @usage * ``` - * import { SafariViewController } from 'ionic-native'; + * import { SafariViewController } from '@ionic-native/safari-view-controller'; * + * constructor(private safariViewController: SafariViewController) { } * - * SafariViewController.isAvailable() - * .then( - * (available: boolean) => { - * if(available){ + * ... * - * SafariViewController.show({ + * this.safariViewController.isAvailable() + * .then((available: boolean) => { + * if (available) { + * + * this.safariViewController.show({ * url: 'http://ionic.io', * hidden: false, * animated: false, @@ -32,8 +35,7 @@ export interface SafariViewControllerOptions { * enterReaderModeIfAvailable: true, * tintColor: '#ff0000' * }) - * .then( - * (result: any) => { + * .then((result: any) => { * if(result.event === 'opened') console.log('Opened'); * else if(result.event === 'loaded') console.log('Loaded'); * else if(result.event === 'closed') console.log('Closed'); @@ -57,6 +59,7 @@ export interface SafariViewControllerOptions { platforms: ['iOS', 'Android'], repo: 'https://github.com/EddyVerbruggen/cordova-plugin-safariviewcontroller' }) +@Injectable() export class SafariViewController { /** @@ -64,7 +67,7 @@ export class SafariViewController { * @returns {Promise} */ @Cordova() - static isAvailable(): Promise { return; } + isAvailable(): Promise { return; } /** * Shows Safari View Controller @@ -75,27 +78,27 @@ export class SafariViewController { successIndex: 1, errorIndex: 2 }) - static show(options?: SafariViewControllerOptions): Promise { return; } + show(options?: SafariViewControllerOptions): Promise { return; } /** * Hides Safari View Controller */ @Cordova() - static hide(): Promise { return; } + hide(): Promise { return; } /** * Tries to connect to the Chrome's custom tabs service. you must call this method before calling any of the other methods listed below. * @returns {Promise} */ @Cordova() - static connectToService(): Promise { return; } + connectToService(): Promise { return; } /** * Call this method whenever there's a chance the user will open an external url. * @returns {Promise} */ @Cordova() - static warmUp(): Promise { return; } + warmUp(): Promise { return; } /** * For even better performance optimization, call this methods if there's more than a 50% chance the user will open a certain URL. @@ -103,6 +106,6 @@ export class SafariViewController { * @returns {Promise} */ @Cordova() - static mayLaunchUrl(url: string): Promise { return; } + mayLaunchUrl(url: string): Promise { return; } } diff --git a/src/plugins/screen-orientation.ts b/src/@ionic-native/plugins/screen-orientation/index.ts similarity index 62% rename from src/plugins/screen-orientation.ts rename to src/@ionic-native/plugins/screen-orientation/index.ts index 28e27888f..1d43052a0 100644 --- a/src/plugins/screen-orientation.ts +++ b/src/@ionic-native/plugins/screen-orientation/index.ts @@ -1,4 +1,6 @@ -import { Cordova, CordovaProperty, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, CordovaProperty, Plugin } from '@ionic-native/core'; +import { Observable } from 'rxjs/Observable'; declare var window; @@ -12,14 +14,21 @@ declare var window; * * @usage * ```typescript - * import { ScreenOrientation } from 'ionic-native'; + * import { ScreenOrientation } from '@ionic-native/screen-orientation'; + * + * constructor(private screenOrientation: ScreenOrientation) { } + * + * ... * * - * // set to either landscape - * ScreenOrientation.lockOrientation('landscape'); + * // get current + * console.log(this.screenOrientation.type); // logs the current orientation, example: 'landscape' + * + * // set to landscape + * this.screenOrientation.lock(this.screenOrientation.ORIENTATIONS.LANDSCAPE); * * // allow user rotate - * ScreenOrientation.unlockOrientation(); + * this.screenOrientation.unlock(); * ``` * * @advanced @@ -39,29 +48,55 @@ declare var window; @Plugin({ pluginName: 'ScreenOrientation', plugin: 'cordova-plugin-screen-orientation', - pluginRef: 'window.screen', + pluginRef: 'screen.orientation', repo: 'https://github.com/apache/cordova-plugin-screen-orientation', platforms: ['Android', 'iOS', 'Windows Phone 8'] }) +@Injectable() export class ScreenOrientation { + /** + * Convenience enum for possible orientations + */ + ORIENTATIONS = { + PORTRAIT_PRIMARY: 'portrait-primary', + PORTRAIT_SECONDARY: 'portrait-secondary', + LANDSCAPE_PRIMARY: 'landscape-primary', + LANDSCAPE_SECONDARY: 'landscape-secondary', + PORTRAIT: 'portrait', + LANDSCAPE: 'landscape', + ANY: 'any' + }; + + /** + * Listen to orientation change event + * @return {Observable} + */ + @Cordova({ + eventObservable: true, + event: 'orientationchange' + }) + onChange(): Observable { return; } + /** * Lock the orientation to the passed value. * See below for accepted values * @param orientation {string} The orientation which should be locked. Accepted values see table above. + * @return {Promise} */ - @Cordova({ sync: true }) - static lockOrientation(orientation: string): void { } + @Cordova({ otherPromise: true }) + lock(orientation: string): Promise { return; } /** * Unlock and allow all orientations. */ @Cordova({ sync: true }) - static unlockOrientation(): void { } + unlock(): void { } /** * Get the current orientation of the device. */ @CordovaProperty - static orientation: string; + type: string; + } diff --git a/src/plugins/screenshot.ts b/src/@ionic-native/plugins/screenshot/index.ts similarity index 78% rename from src/plugins/screenshot.ts rename to src/@ionic-native/plugins/screenshot/index.ts index e7982b61e..cb735cba4 100644 --- a/src/plugins/screenshot.ts +++ b/src/@ionic-native/plugins/screenshot/index.ts @@ -1,4 +1,5 @@ -import { Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin } from '@ionic-native/core'; declare var navigator: any; @@ -7,13 +8,17 @@ declare var navigator: any; * @description Captures a screen shot * @usage * ```typescript - * import {Screenshot} from 'ionic-native'; + * import { Screenshot } from '@ionic-native/screenshot'; + * + * constructor(private screenshot: Screenshot) { } + * + * ... * * // Take a screenshot and save to file - * Screenshot.save('jpg', 80, 'myscreenshot.jpg').then(onSuccess, onError); + * this.screenshot.save('jpg', 80, 'myscreenshot.jpg').then(onSuccess, onError); * * // Take a screenshot and get temporary file URI - * Screenshot.URI(80).then(onSuccess, onError); + * this.screenshot.URI(80).then(onSuccess, onError); * ``` */ @Plugin({ @@ -22,6 +27,7 @@ declare var navigator: any; pluginRef: 'navigator.screenshot', repo: 'https://github.com/gitawego/cordova-screenshot.git' }) +@Injectable() export class Screenshot { /** @@ -34,7 +40,7 @@ export class Screenshot { * @param {string} filename. Name of the file as stored on the storage * @returns {Promise} */ - static save(format?: string, quality?: number, filename?: string): Promise { + save(format?: string, quality?: number, filename?: string): Promise { return new Promise( (resolve, reject) => { navigator.screenshot.save( @@ -60,7 +66,7 @@ export class Screenshot { * Default quality is set to 100. * @returns {Promise} */ - static URI(quality?: number): Promise { + URI(quality?: number): Promise { return new Promise( (resolve, reject) => { navigator.screenshot.URI( diff --git a/src/plugins/securestorage.ts b/src/@ionic-native/plugins/secure-storage/index.ts similarity index 52% rename from src/plugins/securestorage.ts rename to src/@ionic-native/plugins/secure-storage/index.ts index 8b88c60fa..a60e5d634 100644 --- a/src/plugins/securestorage.ts +++ b/src/@ionic-native/plugins/secure-storage/index.ts @@ -1,74 +1,21 @@ -import { CordovaInstance, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { CordovaInstance, Plugin, CordovaCheck } from '@ionic-native/core'; declare var cordova: any; + /** - * @name Secure Storage - * @description - * This plugin gets, sets and removes key,value pairs from a device's secure storage. - * - * Requires Cordova plugin: `cordova-plugin-secure-storage`. For more info, please see the [Cordova Secure Storage docs](https://github.com/Crypho/cordova-plugin-secure-storage). - * - * @usage - * - * ```typescript - * import { SecureStorage } from 'ionic-native'; - * - * let secureStorage: SecureStorage = new SecureStorage(); - * secureStorage.create('my_store_name') - * .then( - * () => console.log('Storage is ready!'), - * error => console.log(error) - * ); - * - * secureStorage.get('myitem') - * .then( - * data => console.log(data), - * error => console.log(error) - * ); - * - * secureStorage.set('myitem', 'myvalue') - * .then( - * data => console.log(data), - * error => console.log(error) - * ); - * - * secureStorage.remove('myitem') - * .then( - * data => console.log(data), - * error => console.log(error) - * ); - * ``` + * @hidden */ -@Plugin({ - pluginName: 'SecureStorage', - plugin: 'cordova-plugin-secure-storage', - pluginRef: 'plugins.securestorage', - repo: 'https://github.com/Crypho/cordova-plugin-secure-storage', - platforms: ['Android', 'iOS', 'Windows Phone', 'Browser'] -}) -export class SecureStorage { +export class SecureStorageObject { - private _objectInstance: any; - - constructor() {} - - /** - * Creates a namespaced storage. - * @param store {string} - * @returns {Promise} - */ - create(store: string): Promise { - return new Promise((res, rej) => { - this._objectInstance = new cordova.plugins.SecureStorage(res, rej, store); - }); - } + constructor(private _objectInstance: any) {} /** * Gets a stored item * @param reference {string} * @returns {Promise} */ - @CordovaInstance({ + @CordovaInstance({ callbackOrder: 'reverse' }) get(reference: string): Promise { return; } @@ -79,7 +26,7 @@ export class SecureStorage { * @param value {string} * @returns {Promise} */ - @CordovaInstance({ + @CordovaInstance({ callbackOrder: 'reverse' }) set(reference: string, value: string): Promise { return; } @@ -89,8 +36,77 @@ export class SecureStorage { * @param reference {string} * @returns {Promise} */ - @CordovaInstance({ + @CordovaInstance({ callbackOrder: 'reverse' }) remove(reference: string): Promise { return; } + +} + +/** + * @name Secure Storage + * @description + * This plugin gets, sets and removes key,value pairs from a device's secure storage. + * + * Requires Cordova plugin: `cordova-plugin-secure-storage`. For more info, please see the [Cordova Secure Storage docs](https://github.com/Crypho/cordova-plugin-secure-storage). + * + * @usage + * + * ```typescript + * import { SecureStorage, SecureStorageOBject } from '@ionic-native/secure-storage'; + * + * constructor(private secureStorage: SecureStorage) { } + * + * ... + * + * this.secureStorage.create('my_store_name') + * .then((storage: SecureStorageObject) => { + * + * storage.get('myitem') + * .then( + * data => console.log(data), + * error => console.log(error) + * ); + * + * storage.set('myitem', 'myvalue') + * .then( + * data => console.log(data), + * error => console.log(error) + * ); + * + * storage.remove('myitem') + * .then( + * data => console.log(data), + * error => console.log(error) + * ); + * + * }); + * + * + * ``` + * @classes + * SecureStorageObject + */ +@Plugin({ + pluginName: 'SecureStorage', + plugin: 'cordova-plugin-secure-storage', + pluginRef: 'plugins.securestorage', + repo: 'https://github.com/Crypho/cordova-plugin-secure-storage', + platforms: ['Android', 'iOS', 'Windows Phone', 'Browser'] +}) +@Injectable() +export class SecureStorage { + + /** + * Creates a namespaced storage. + * @param store {string} + * @returns {Promise} + */ + @CordovaCheck() + create(store: string): Promise { + return new Promise((res, rej) => { + const instance = new cordova.plugins.SecureStorage(() => res(new SecureStorageObject(instance)), rej, store); + }); + } + } diff --git a/src/plugins/serial.ts b/src/@ionic-native/plugins/serial/index.ts similarity index 78% rename from src/plugins/serial.ts rename to src/@ionic-native/plugins/serial/index.ts index e248ab99d..ab574424a 100644 --- a/src/plugins/serial.ts +++ b/src/@ionic-native/plugins/serial/index.ts @@ -1,4 +1,5 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; declare var serial: any; @@ -21,10 +22,14 @@ export interface SerialOpenOptions { * @usage * * ``` - * import { Serial } from 'ionic-native'; + * import { Serial } from '@ionic-native/serial'; * - * Serial.requestPermission().then(() => { - * Serial.open({ + * constructor(private serial: Serial) { } + * + * ... + * + * this.serial.requestPermission().then(() => { + * this.serial.open({ * baudRate: 9800 * }).then(() => { * console.log('Serial connection opened'); @@ -40,6 +45,7 @@ export interface SerialOpenOptions { repo: 'https://github.com/xseignard/cordovarduino', platforms: ['Android'] }) +@Injectable() export class Serial { /** @@ -52,7 +58,7 @@ export class Serial { successIndex: 1, errorIndex: 2 }) - static requestPermission(options?: SerialPermissionOptions): Promise { return; } + requestPermission(options?: SerialPermissionOptions): Promise { return; } /** * Open connection to a serial device @@ -61,7 +67,7 @@ export class Serial { * @return {Promise} Returns a promise that resolves when the serial connection is opened */ @Cordova() - static open(options: SerialOpenOptions): Promise { return; } + open(options: SerialOpenOptions): Promise { return; } /** * Write to a serial connection @@ -70,7 +76,7 @@ export class Serial { * @return {Promise} Returns a promise that resolves when the write is complete */ @Cordova() - static write(data: any): Promise { return; } + write(data: any): Promise { return; } /** * Write hex to a serial connection @@ -79,7 +85,7 @@ export class Serial { * @return {Promise} Returns a promise that resolves when the write is complete */ @Cordova() - static writeHex(data: any): Promise { return; } + writeHex(data: any): Promise { return; } /** * Read from a serial connection @@ -87,7 +93,7 @@ export class Serial { * @return {Promise} Returns a promise that resolves with data read from the serial connection */ @Cordova() - static read(): Promise { return; } + read(): Promise { return; } /** * Watch the incoming data from the serial connection. Clear the watch by unsubscribing from the observable @@ -97,7 +103,7 @@ export class Serial { @Cordova({ observable: true }) - static registerReadCallback(): Observable { return; } + registerReadCallback(): Observable { return; } /** * Close the serial connection @@ -105,6 +111,6 @@ export class Serial { * @return {Promise} Returns a promise that resolves when the serial connection is closed */ @Cordova() - static close(): Promise { return; } + close(): Promise { return; } } diff --git a/src/plugins/shake.ts b/src/@ionic-native/plugins/shake/index.ts similarity index 65% rename from src/plugins/shake.ts rename to src/@ionic-native/plugins/shake/index.ts index ba1d6940d..a169c8796 100644 --- a/src/plugins/shake.ts +++ b/src/@ionic-native/plugins/shake/index.ts @@ -1,13 +1,18 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; /** * @name Shake * @description Handles shake gesture * @usage * ```typescript - * import {Shake} from 'ionic-native'; + * import { Shake } from '@ionic-native/shake'; * - * let watch = Shake.startWatch(60).subscribe(() => { + * constructor(private shake: Shake) { } + * + * ... + * + * const watch = this.shake.startWatch(60).subscribe(() => { * // do something * }); * @@ -20,6 +25,7 @@ import { Observable } from 'rxjs/Observable'; pluginRef: 'shake', repo: 'https://github.com/leecrossley/cordova-plugin-shake' }) +@Injectable() export class Shake { /** * Watch for shake gesture @@ -32,6 +38,6 @@ export class Shake { successIndex: 0, errorIndex: 2 }) - static startWatch(sensitivity?: number): Observable {return; } + startWatch(sensitivity?: number): Observable {return; } } diff --git a/src/plugins/sim.ts b/src/@ionic-native/plugins/sim/index.ts similarity index 71% rename from src/plugins/sim.ts rename to src/@ionic-native/plugins/sim/index.ts index b3abe574e..dc3c5b985 100644 --- a/src/plugins/sim.ts +++ b/src/@ionic-native/plugins/sim/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; /** @@ -10,19 +11,23 @@ import { Cordova, Plugin } from './plugin'; * * @usage * ```typescript - * import { Sim } from 'ionic-native'; + * import { Sim } from '@ionic-native/sim'; * * - * Sim.getSimInfo().then( + * constructor(private sim: Sim) { } + * + * ... + * + * this.sim.getSimInfo().then( * (info) => console.log('Sim info: ', info), * (err) => console.log('Unable to get sim info: ', err) * ); * - * Sim.hasReadPermission().then( + * this.sim.hasReadPermission().then( * (info) => console.log('Has permission: ', info) * ); * - * Sim.requestReadPermission().then( + * this.sim.requestReadPermission().then( * () => console.log('Permission granted'), * () => console.log('Permission denied') * ); @@ -35,13 +40,14 @@ import { Cordova, Plugin } from './plugin'; repo: 'https://github.com/pbakondy/cordova-plugin-sim', platforms: ['Android', 'iOS', 'Windows Phone'] }) +@Injectable() export class Sim { /** * Returns info from the SIM card. * @returns {Promise} */ @Cordova() - static getSimInfo(): Promise { return; } + getSimInfo(): Promise { return; } /** * Check permission @@ -50,7 +56,7 @@ export class Sim { @Cordova({ platforms: ['Android'] }) - static hasReadPermission(): Promise { return; } + hasReadPermission(): Promise { return; } /** * Request permission @@ -59,5 +65,5 @@ export class Sim { @Cordova({ platforms: ['Android'] }) - static requestReadPermission(): Promise { return; } + requestReadPermission(): Promise { return; } } diff --git a/src/plugins/sms.ts b/src/@ionic-native/plugins/sms/index.ts similarity index 83% rename from src/plugins/sms.ts rename to src/@ionic-native/plugins/sms/index.ts index f8cae37b3..a0e804c30 100644 --- a/src/plugins/sms.ts +++ b/src/@ionic-native/plugins/sms/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; /** @@ -32,11 +33,16 @@ export interface SmsOptionsAndroid { * * @usage * ```typescript - * import { SMS } from 'ionic-native'; + * import { SMS } from '@ionic-native/sms'; + * + * constructor(private sms: SMS) { } + * + * + * ... * * * // Send a text message using default options - * SMS.send('416123456', 'Hello world!'); + * this.sms.send('416123456', 'Hello world!'); * ``` * @interfaces * SmsOptions @@ -49,6 +55,7 @@ export interface SmsOptionsAndroid { repo: 'https://github.com/cordova-sms/cordova-sms-plugin', platforms: ['Android', 'iOS', 'Windows Phone 8'] }) +@Injectable() export class SMS { /** @@ -62,7 +69,7 @@ export class SMS { successIndex: 3, errorIndex: 4 }) - static send( + send( phoneNumber: string | string[], message: string, options?: SmsOptions @@ -75,6 +82,6 @@ export class SMS { @Cordova({ platforms: ['Android'] }) - static hasPermission(): Promise { return; } + hasPermission(): Promise { return; } } diff --git a/src/plugins/socialsharing.ts b/src/@ionic-native/plugins/social-sharing/index.ts similarity index 72% rename from src/plugins/socialsharing.ts rename to src/@ionic-native/plugins/social-sharing/index.ts index f598426e1..87bb696fd 100644 --- a/src/plugins/socialsharing.ts +++ b/src/@ionic-native/plugins/social-sharing/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; /** @@ -7,17 +8,21 @@ import { Cordova, Plugin } from './plugin'; * Share text, files, images, and links via social networks, sms, and email. * @usage * ```typescript - * import { SocialSharing } from 'ionic-native'; + * import { SocialSharing } from '@ionic-native/social-sharing'; + * + * constructor(private socialSharing: SocialSharing) { } + * + * ... * * // Check if sharing via email is supported - * SocialSharing.canShareViaEmail().then(() => { + * this.socialSharing.canShareViaEmail().then(() => { * // Sharing via email is possible * }).catch(() => { * // Sharing via email is not possible * }); * * // Share via email - * SocialSharing.shareViaEmail('Body', 'Subject', 'recipient@example.org').then(() => { + * this.socialSharing.shareViaEmail('Body', 'Subject', 'recipient@example.org').then(() => { * // Success! * }).catch(() => { * // Error! @@ -31,6 +36,7 @@ import { Cordova, Plugin } from './plugin'; repo: 'https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin', platforms: ['iOS', 'Android', 'Windows Phone'] }) +@Injectable() export class SocialSharing { /** * Shares using the share sheet @@ -41,7 +47,7 @@ export class SocialSharing { * @returns {Promise} */ @Cordova() - static share(message?: string, subject?: string, file?: string|string[], url?: string): Promise { return; } + share(message?: string, subject?: string, file?: string|string[], url?: string): Promise { return; } /** * Shares using the share sheet with additional options and returns a result object or an error message (requires plugin version 5.1.0+) @@ -51,7 +57,7 @@ export class SocialSharing { @Cordova({ platforms: ['iOS', 'Android'] }) - static shareWithOptions(options: { message?: string, subject?: string, files?: string|string[], url?: string, chooserTitle?: string }): Promise { return; } + shareWithOptions(options: { message?: string, subject?: string, files?: string|string[], url?: string, chooserTitle?: string }): Promise { return; } /** * Checks if you can share via a specific app. @@ -67,7 +73,7 @@ export class SocialSharing { errorIndex: 6, platforms: ['iOS', 'Android'] }) - static canShareVia(appName: string, message?: string, subject?: string, image?: string, url?: string): Promise { return; } + canShareVia(appName: string, message?: string, subject?: string, image?: string, url?: string): Promise { return; } /** * Shares directly to Twitter @@ -81,7 +87,7 @@ export class SocialSharing { errorIndex: 4, platforms: ['iOS', 'Android'] }) - static shareViaTwitter(message: string, image?: string, url?: string): Promise { return; } + shareViaTwitter(message: string, image?: string, url?: string): Promise { return; } /** * Shares directly to Facebook @@ -95,7 +101,7 @@ export class SocialSharing { errorIndex: 4, platforms: ['iOS', 'Android'] }) - static shareViaFacebook(message: string, image?: string, url?: string): Promise { return; } + shareViaFacebook(message: string, image?: string, url?: string): Promise { return; } /** @@ -111,7 +117,7 @@ export class SocialSharing { errorIndex: 5, platforms: ['iOS', 'Android'] }) - static shareViaFacebookWithPasteMessageHint(message: string, image?: string, url?: string, pasteMessageHint?: string): Promise { return; } + shareViaFacebookWithPasteMessageHint(message: string, image?: string, url?: string, pasteMessageHint?: string): Promise { return; } /** * Shares directly to Instagram @@ -122,7 +128,7 @@ export class SocialSharing { @Cordova({ platforms: ['iOS', 'Android'] }) - static shareViaInstagram(message: string, image: string): Promise { return; } + shareViaInstagram(message: string, image: string): Promise { return; } /** * Shares directly to WhatsApp @@ -136,7 +142,7 @@ export class SocialSharing { errorIndex: 4, platforms: ['iOS', 'Android'] }) - static shareViaWhatsApp(message: string, image?: string, url?: string): Promise { return; } + shareViaWhatsApp(message: string, image?: string, url?: string): Promise { return; } /** * Shares directly to a WhatsApp Contact @@ -151,7 +157,7 @@ export class SocialSharing { errorIndex: 5, platforms: ['iOS', 'Android'] }) - static shareViaWhatsAppToReceiver(receiver: string, message: string, image?: string, url?: string): Promise { return; } + shareViaWhatsAppToReceiver(receiver: string, message: string, image?: string, url?: string): Promise { return; } /** * Share via SMS @@ -162,7 +168,7 @@ export class SocialSharing { @Cordova({ platforms: ['iOS', 'Android'] }) - static shareViaSMS(messge: string, phoneNumber: string): Promise { return; } + shareViaSMS(messge: string, phoneNumber: string): Promise { return; } /** * Checks if you can share via email @@ -171,7 +177,7 @@ export class SocialSharing { @Cordova({ platforms: ['iOS', 'Android'] }) - static canShareViaEmail(): Promise { return; } + canShareViaEmail(): Promise { return; } /** * Share via Email @@ -188,7 +194,7 @@ export class SocialSharing { successIndex: 6, errorIndex: 7 }) - static shareViaEmail(message: string, subject: string, to: string[], cc?: string[], bcc?: string[], files?: string|string[]): Promise { return; } + shareViaEmail(message: string, subject: string, to: string[], cc?: string[], bcc?: string[], files?: string|string[]): Promise { return; } /** * Share via AppName @@ -204,5 +210,5 @@ export class SocialSharing { errorIndex: 6, platforms: ['iOS', 'Android'] }) - static shareVia(appName: string, message: string, subject?: string, image?: string, url?: string): Promise { return; } + shareVia(appName: string, message: string, subject?: string, image?: string, url?: string): Promise { return; } } diff --git a/src/plugins/speech-recognition.ts b/src/@ionic-native/plugins/speech-recognition/index.ts similarity index 76% rename from src/plugins/speech-recognition.ts rename to src/@ionic-native/plugins/speech-recognition/index.ts index e904f0971..f65e7a1c4 100644 --- a/src/plugins/speech-recognition.ts +++ b/src/@ionic-native/plugins/speech-recognition/index.ts @@ -1,4 +1,5 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; export type SpeechRecognitionListeningOptions = SpeechRecognitionListeningOptionsIOS | SpeechRecognitionListeningOptionsAndroid; @@ -50,35 +51,41 @@ export interface SpeechRecognitionListeningOptionsAndroid { * * @usage * ``` - * import { SpeechRecognition } from 'ionic-native'; + * import { SpeechRecognition } from '@ionic-native/speech-recognition'; + * + * constructor(private speechRecognition: SpeechRecognition) { } + * + * ... + * + * * * // Check feature available - * SpeechRecognition.isRecognitionAvailable() + * this.speechRecognition.isRecognitionAvailable() * .then((available: boolean) => console.log(available)) * * // Start the recognition process - * SpeechRecognition.startListening(options) + * this.speechRecognition.startListening(options) * .subscribe( * (matches: Array) => console.log(matches), * (onerror) => console.log('error:', onerror) * ) * * // Stop the recognition process (iOS only) - * SpeechRecognition.stopListening() + * this.speechRecognition.stopListening() * * // Get the list of supported languages - * SpeechRecognition.getSupportedLanguages() + * this.speechRecognition.getSupportedLanguages() * .then( * (languages: Array) => console.log(languages), * (error) => console.log(error) * ) * * // Check permission - * SpeechRecognition.hasPermission() + * this.speechRecognition.hasPermission() * .then((hasPermission: boolean) => console.log(hasPermission)) * * // Request permissions - * SpeechRecognition.requestPermission() + * this.speechRecognition.requestPermission() * .then( * () => console.log('Granted'), * () => console.log('Denied') @@ -93,6 +100,7 @@ export interface SpeechRecognitionListeningOptionsAndroid { repo: 'https://github.com/pbakondy/cordova-plugin-speechrecognition', platforms: ['Android', 'iOS'] }) +@Injectable() export class SpeechRecognition { /** @@ -100,7 +108,7 @@ export class SpeechRecognition { * @return {Promise} */ @Cordova() - static isRecognitionAvailable(): Promise { + isRecognitionAvailable(): Promise { return; } @@ -113,7 +121,7 @@ export class SpeechRecognition { observable: true, }) - static startListening(options?: SpeechRecognitionListeningOptions): Observable> { + startListening(options?: SpeechRecognitionListeningOptions): Observable> { return; } @@ -123,7 +131,7 @@ export class SpeechRecognition { @Cordova({ platforms: ['iOS'] }) - static stopListening(): Promise { + stopListening(): Promise { return; } @@ -132,7 +140,7 @@ export class SpeechRecognition { * @return {Promise< Array >} list of languages */ @Cordova() - static getSupportedLanguages(): Promise> { + getSupportedLanguages(): Promise> { return; } @@ -141,7 +149,7 @@ export class SpeechRecognition { * @return {Promise} has permission */ @Cordova() - static hasPermission(): Promise { + hasPermission(): Promise { return; } @@ -150,7 +158,7 @@ export class SpeechRecognition { * @return {Promise} */ @Cordova() - static requestPermission(): Promise { + requestPermission(): Promise { return; } diff --git a/src/plugins/spinnerdialog.ts b/src/@ionic-native/plugins/spinner-dialog/index.ts similarity index 70% rename from src/plugins/spinnerdialog.ts rename to src/@ionic-native/plugins/spinner-dialog/index.ts index ea5e7ebd4..c6847e5a1 100644 --- a/src/plugins/spinnerdialog.ts +++ b/src/@ionic-native/plugins/spinner-dialog/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; export interface SpinnerDialogIOSOptions { overlayOpacity?: number; @@ -12,12 +13,15 @@ export interface SpinnerDialogIOSOptions { * @description * @usage * ```typescript - * import { SpinnerDialog } from 'ionic-native'; + * import { SpinnerDialog } from '@ionic-native/spinner-dialog'; * + * constructor(private spinnerDialog: SpinnerDialog) { } * - * SpinnerDialog.show(); + * ... * - * SpinnerDialog.hide(); + * this.spinnerDialog.show(); + * + * this.spinnerDialog.hide(); * ``` * @interfaces * SpinnerDialogIOSOptions @@ -29,6 +33,7 @@ export interface SpinnerDialogIOSOptions { repo: 'https://github.com/Paldom/SpinnerDialog', platforms: ['Android', 'iOS', 'Windows Phone 8'] }) +@Injectable() export class SpinnerDialog { /** @@ -41,7 +46,7 @@ export class SpinnerDialog { @Cordova({ sync: true }) - static show(title?: string, message?: string, cancelCallback?: any, iOSOptions?: SpinnerDialogIOSOptions): void {} + show(title?: string, message?: string, cancelCallback?: any, iOSOptions?: SpinnerDialogIOSOptions): void {} /** * Hides the spinner dialog if visible @@ -49,6 +54,6 @@ export class SpinnerDialog { @Cordova({ sync: true }) - static hide(): void {} + hide(): void {} } diff --git a/src/plugins/splashscreen.ts b/src/@ionic-native/plugins/splash-screen/index.ts similarity index 56% rename from src/plugins/splashscreen.ts rename to src/@ionic-native/plugins/splash-screen/index.ts index ad55524f8..9722ad6c5 100644 --- a/src/plugins/splashscreen.ts +++ b/src/@ionic-native/plugins/splash-screen/index.ts @@ -1,26 +1,31 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; /** - * @name Splashscreen + * @name SplashScreen * @description This plugin displays and hides a splash screen during application launch. The methods below allows showing and hiding the splashscreen after the app has loaded. * @usage * ```typescript - * import { Splashscreen } from 'ionic-native'; + * import { SplashScreen } from '@ionic-native/splash-screen'; * + * constructor(private splashScreen: SplashScreen) { } * - * Splashscreen.show(); + * ... * - * Splashscreen.hide(); + * this.splashScreen.show(); + * + * this.splashScreen.hide(); * ``` */ @Plugin({ - pluginName: 'Splashscreen', + pluginName: 'SplashScreen', plugin: 'cordova-plugin-splashscreen', pluginRef: 'navigator.splashscreen', repo: 'https://github.com/apache/cordova-plugin-splashscreen' }) -export class Splashscreen { +@Injectable() +export class SplashScreen { /** * Shows the splashscreen @@ -28,7 +33,7 @@ export class Splashscreen { @Cordova({ sync: true }) - static show(): void {} + show(): void {} /** * Hides the splashscreen @@ -36,6 +41,6 @@ export class Splashscreen { @Cordova({ sync: true }) - static hide(): void {} + hide(): void {} } diff --git a/src/plugins/sqlite.ts b/src/@ionic-native/plugins/sqlite/index.ts similarity index 66% rename from src/plugins/sqlite.ts rename to src/@ionic-native/plugins/sqlite/index.ts index e4d984d5a..ec49da5b2 100644 --- a/src/plugins/sqlite.ts +++ b/src/@ionic-native/plugins/sqlite/index.ts @@ -1,94 +1,18 @@ -import {Cordova, CordovaInstance, Plugin, pluginWarn, InstanceProperty} from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, CordovaInstance, Plugin, CordovaCheck, InstanceProperty } from '@ionic-native/core'; declare var sqlitePlugin; /** - * @name SQLite - * - * @description - * Access SQLite databases on the device. - * - * @usage - * - * ```typescript - * import { SQLite } from 'ionic-native'; - * - * // OPTION A: Use static constructor - * SQLite.openDatabase({ - * name: 'data.db', - * location: 'default' - * }) - * .then((db: SQLite) => { - * - * db.executeSql('create table danceMoves(name VARCHAR(32))', []).then(() => {}).catch(() => {}); - * - * }) - * .catch(error => console.error('Error opening database', error)); - * - * - * // OPTION B: Create a new instance of SQLite - * let db = new SQLite(); - * db.openDatabase({ - * name: 'data.db', - * location: 'default' // the location field is required - * }).then(() => { - * db.executeSql('create table danceMoves(name VARCHAR(32))', []).then(() => { - * - * }, (err) => { - * console.error('Unable to execute sql: ', err); - * }); - * }, (err) => { - * console.error('Unable to open database: ', err); - * }); - * ``` - * + * @hidden */ -@Plugin({ - pluginName: 'SQLite', - pluginRef: 'sqlitePlugin', - plugin: 'cordova-sqlite-storage', - repo: 'https://github.com/litehelpers/Cordova-sqlite-storage' -}) -export class SQLite { +export class SQLiteObject { - private _objectInstance: any; + constructor(private _objectInstance: any) { } @InstanceProperty databaseFeatures: any; - constructor() { } - - static openDatabase(config: any): Promise { - return new SQLite().openDatabase(config); - } - - - /** - * Open or create a SQLite database file. - * - * See the plugin docs for an explanation of all options: https://github.com/litehelpers/Cordova-sqlite-storage#opening-a-database - * - * @param config the config for opening the database. - */ - openDatabase(config: any): Promise { - return new Promise((resolve, reject) => { - if (typeof sqlitePlugin !== 'undefined') { - sqlitePlugin.openDatabase(config, db => { - this._objectInstance = db; - resolve(db); - }, error => { - console.warn(error); - reject(error); - }); - } else { - pluginWarn({ - pluginName: 'SQLite', - plugin: 'cordova-sqlite-storage' - }); - } - }); - } - @CordovaInstance({ sync: true }) @@ -204,13 +128,74 @@ export class SQLite { * @returns {Promise} */ @Cordova() - static echoTest(): Promise { return; } + echoTest(): Promise { return; } /** * @param first * @returns {Promise} */ @Cordova() - static deleteDatabase(first): Promise { return; } + deleteDatabase(first): Promise { return; } + +} + +/** + * @name SQLite + * + * @description + * Access SQLite databases on the device. + * + * @usage + * + * ```typescript + * import { SQLite, SQLiteObject } from '@ionic-native/sqlite'; + * + * constructor(private sqlite: SQLite) { } + * + * ... + * + * this.sqlite.create({ + * name: 'data.db', + * location: 'default' + * }) + * .then((db: SQLiteObject) => { + * + * + * db.executeSql('create table danceMoves(name VARCHAR(32))', {}) + * .then(() => console.log('Executed SQL')) + * .catch(e => console.log(e)); + * + * + * }) + * .catch(e => console.log(e)); + * + * ``` + * + * @classes + * SQLiteObject + */ +@Plugin({ + pluginName: 'SQLite', + pluginRef: 'sqlitePlugin', + plugin: 'cordova-sqlite-storage', + repo: 'https://github.com/litehelpers/Cordova-sqlite-storage' +}) +@Injectable() +export class SQLite { + + /** + * Open or create a SQLite database file. + * + * See the plugin docs for an explanation of all options: https://github.com/litehelpers/Cordova-sqlite-storage#opening-a-database + * + * @param config the config for opening the database. + * @return Promise + */ + @CordovaCheck() + create(config: any): Promise { + return new Promise((resolve, reject) => { + sqlitePlugin.openDatabase(config, db => resolve(new SQLiteObject(db)), reject); + }); + } } diff --git a/src/plugins/statusbar.ts b/src/@ionic-native/plugins/status-bar/index.ts similarity index 75% rename from src/plugins/statusbar.ts rename to src/@ionic-native/plugins/status-bar/index.ts index 42c37abb1..b67a99e7e 100644 --- a/src/plugins/statusbar.ts +++ b/src/@ionic-native/plugins/status-bar/index.ts @@ -1,4 +1,5 @@ -import { Cordova, CordovaProperty, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, CordovaProperty, Plugin } from '@ionic-native/core'; declare var window; @@ -12,12 +13,16 @@ declare var window; * * @usage * ```typescript - * import { StatusBar } from 'ionic-native'; + * import { StatusBar } from '@ionic-native/status-bar'; + * + * constructor(private statusBar: StatusBar) { } + * + * ... * * - * StatusBar.overlaysWebView(true); // let status bar overlay webview + * this.statusBar.overlaysWebView(true); // let status bar overlay webview * - * StatusBar.backgroundColorByHexString('#ffffff'); // set status bar to white + * this.statusBar.backgroundColorByHexString('#ffffff'); // set status bar to white * ``` * */ @@ -28,6 +33,7 @@ declare var window; repo: 'https://github.com/apache/cordova-plugin-statusbar', platforms: ['iOS', 'Android', 'Windows Phone 8', 'Windows 8', 'Windows 10'] }) +@Injectable() export class StatusBar { /** * Set whether the status bar overlays the main app view. The default @@ -38,7 +44,7 @@ export class StatusBar { @Cordova({ sync: true }) - static overlaysWebView(doesOverlay: boolean) { }; + overlaysWebView(doesOverlay: boolean) { }; /** * Use the default statusbar (dark text, for light backgrounds). @@ -46,7 +52,7 @@ export class StatusBar { @Cordova({ sync: true }) - static styleDefault() { }; + styleDefault() { }; /** * Use the lightContent statusbar (light text, for dark backgrounds). @@ -54,7 +60,7 @@ export class StatusBar { @Cordova({ sync: true }) - static styleLightContent() { }; + styleLightContent() { }; /** * Use the blackTranslucent statusbar (light text, for dark backgrounds). @@ -62,7 +68,7 @@ export class StatusBar { @Cordova({ sync: true }) - static styleBlackTranslucent() { }; + styleBlackTranslucent() { }; /** * Use the blackOpaque statusbar (light text, for dark backgrounds). @@ -70,7 +76,7 @@ export class StatusBar { @Cordova({ sync: true }) - static styleBlackOpaque() { }; + styleBlackOpaque() { }; /** * Set the status bar to a specific named color. Valid options: @@ -83,7 +89,7 @@ export class StatusBar { @Cordova({ sync: true }) - static backgroundColorByName(colorName: string) { }; + backgroundColorByName(colorName: string) { }; /** * Set the status bar to a specific hex color (CSS shorthand supported!). @@ -95,7 +101,7 @@ export class StatusBar { @Cordova({ sync: true }) - static backgroundColorByHexString(hexString: string) { }; + backgroundColorByHexString(hexString: string) { }; /** * Hide the StatusBar @@ -103,7 +109,7 @@ export class StatusBar { @Cordova({ sync: true }) - static hide() { }; + hide() { }; /** * Show the StatusBar @@ -111,12 +117,12 @@ export class StatusBar { @Cordova({ sync: true }) - static show() { }; + show() { }; /** * Whether the StatusBar is currently visible or not. */ @CordovaProperty - static isVisible: boolean; + isVisible: boolean; } diff --git a/src/plugins/stepcounter.ts b/src/@ionic-native/plugins/stepcounter/index.ts similarity index 67% rename from src/plugins/stepcounter.ts rename to src/@ionic-native/plugins/stepcounter/index.ts index 6092f0f3a..d524fa8a6 100644 --- a/src/plugins/stepcounter.ts +++ b/src/@ionic-native/plugins/stepcounter/index.ts @@ -1,4 +1,5 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; /** * @name Stepcounter * @description @@ -10,12 +11,16 @@ import { Plugin, Cordova } from './plugin'; * * @usage * ``` - * import { Stepcounter } from 'ionic-native'; + * import { Stepcounter } from '@ionic-native/stepcounter'; + * + * constructor(private stepcounter: Stepcounter) { } + * + * ... * * let startingOffset = 0; - * Stepcounter.start(startingOffset).then(onSuccess => console.log('stepcounter-start success', onSuccess), onFailure => console.log('stepcounter-start error', onFailure)); + * this.stepcounter.start(startingOffset).then(onSuccess => console.log('stepcounter-start success', onSuccess), onFailure => console.log('stepcounter-start error', onFailure)); * - * Stepcounter.getHistory().then(historyObj => console.log('stepcounter-history success', historyObj), onFailure => console.log('stepcounter-history error', onFailure)); + * this.stepcounter.getHistory().then(historyObj => console.log('stepcounter-history success', historyObj), onFailure => console.log('stepcounter-history error', onFailure)); * * ``` */ @@ -26,6 +31,7 @@ import { Plugin, Cordova } from './plugin'; repo: 'https://github.com/Slidee/cordova-plugin-stepcounter', platforms: ['Android'] }) +@Injectable() export class Stepcounter { /** @@ -35,40 +41,40 @@ export class Stepcounter { * @returns {Promise} Returns a Promise that resolves on success or rejects on failure */ @Cordova() - static start(startingOffset: number): Promise { return; } + start(startingOffset: number): Promise { return; } /** * Stop the step counter * @returns {Promise} Returns a Promise that resolves on success with the amount of steps since the start command has been called, or rejects on failure */ @Cordova() - static stop(): Promise { return; } + stop(): Promise { return; } /** * Get the amount of steps for today (or -1 if it no data given) * @returns {Promise} Returns a Promise that resolves on success with the amount of steps today, or rejects on failure */ @Cordova() - static getTodayStepCount(): Promise { return; } + getTodayStepCount(): Promise { return; } /** * Get the amount of steps since the start command has been called * @returns {Promise} Returns a Promise that resolves on success with the amount of steps since the start command has been called, or rejects on failure */ @Cordova() - static getStepCount(): Promise { return; } + getStepCount(): Promise { return; } /** * Returns true/false if Android device is running >API level 19 && has the step counter API available * @returns {Promise} Returns a Promise that resolves on success, or rejects on failure */ @Cordova() - static deviceCanCountSteps(): Promise { return; } + deviceCanCountSteps(): Promise { return; } /** * Get the step history (JavaScript object) * @returns {Promise} Returns a Promise that resolves on success, or rejects on failure */ @Cordova() - static getHistory(): Promise { return; } + getHistory(): Promise { return; } } diff --git a/src/plugins/streaming-media.ts b/src/@ionic-native/plugins/streaming-media/index.ts similarity index 73% rename from src/plugins/streaming-media.ts rename to src/@ionic-native/plugins/streaming-media/index.ts index 0ad34858e..f48a20f42 100644 --- a/src/plugins/streaming-media.ts +++ b/src/@ionic-native/plugins/streaming-media/index.ts @@ -1,4 +1,5 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; export interface StreamingVideoOptions { successCallback?: Function; @@ -16,13 +17,15 @@ export interface StreamingAudioOptions { } /** - * @name StreamingMedia + * @name Streaming Media * @description * This plugin allows you to stream audio and video in a fullscreen, native player on iOS and Android. * * @usage * ``` - * import {StreamingMedia, StreamingVideoOptions} from 'ionic-native'; + * import { StreamingMedia, StreamingVideoOptions } from '@ionic-native/streaming-media'; + * + * constructor(private streamingMedia: StreamingMedia) { } * * let options: StreamingVideoOptions = { * successCallback: () => { console.log('Video played') }, @@ -30,7 +33,7 @@ export interface StreamingAudioOptions { * orientation: 'landscape' * }; * - * StreamingMedia.playVideo('https://path/to/video/stream', options); + * this.streamingMedia.playVideo('https://path/to/video/stream', options); * * ``` * @interfaces @@ -44,6 +47,7 @@ export interface StreamingAudioOptions { repo: 'https://github.com/nchutchind/cordova-plugin-streaming-media', platforms: ['Android', 'iOS'] }) +@Injectable() export class StreamingMedia { /** * Streams a video @@ -51,7 +55,7 @@ export class StreamingMedia { * @param options {StreamingVideoOptions} Options */ @Cordova({sync: true}) - static playVideo(videoUrl: string, options?: StreamingVideoOptions): void { } + playVideo(videoUrl: string, options?: StreamingVideoOptions): void { } /** * Streams an audio @@ -59,24 +63,24 @@ export class StreamingMedia { * @param options {StreamingAudioOptions} Options */ @Cordova({sync: true}) - static playAudio(audioUrl: string, options?: StreamingAudioOptions): void { } + playAudio(audioUrl: string, options?: StreamingAudioOptions): void { } /** * Stops streaming audio */ @Cordova({sync: true}) - static stopAudio(): void { } + stopAudio(): void { } /** * Pauses streaming audio */ @Cordova({sync: true, platforms: ['iOS']}) - static pauseAudio(): void { } + pauseAudio(): void { } /** * Resumes streaming audio */ @Cordova({sync: true, platforms: ['iOS']}) - static resumeAudio(): void { } + resumeAudio(): void { } } diff --git a/src/@ionic-native/plugins/stripe/index.ts b/src/@ionic-native/plugins/stripe/index.ts new file mode 100644 index 000000000..d90c3b41d --- /dev/null +++ b/src/@ionic-native/plugins/stripe/index.ts @@ -0,0 +1,179 @@ +import { Injectable } from '@angular/core'; +import {Plugin, Cordova} from '@ionic-native/core'; + +export interface StripeCardTokenParams { + /** + * Card number + */ + number: string; + /** + * Expiry month + */ + expMonth: number; + /** + * Expiry year + */ + expYear: number; + /** + * CVC / CVV + */ + cvc?: string; + /** + * Cardholder name + */ + name?: string; + /** + * Address line 1 + */ + address_line1?: string; + /** + * Address line 2 + */ + address_line2?: string; + /** + * City + */ + address_city?: string; + /** + * State / Province + */ + address_state?: string; + /** + * Country + */ + address_country?: string; + /** + * Postal code / ZIP Code + */ + postal_code?: string; + /** + * 3-letter ISO code for currency + */ + currency?: string; +} + +export interface StripeBankAccountParams { + /** + * Routing number. + */ + routing_number: string; + /** + * Account number. + */ + account_number: string; + /** + * Currency code. Example: `USD`. + */ + currency: string; + /** + * Country code. Example: `US`. + */ + country: string; + /** + * Account holder name. + */ + account_holder_name?: string; + /** + * Account holder type. This can be `individual` or `company`. + */ + account_holder_type?: string; +} + +/** + * @name Stripe + * @description + * A plugin that allows you to use Stripe's Native SDKs for Android and iOS. + * + * @usage + * ``` + * import { Stripe } from '@ionic-native/stripe'; + * + * constructor(private stripe: Stripe) { } + * + * ... + * + * this.stripe.setPublishableKey('my_publishable_key'); + * + * let card = { + * number: '4242424242424242', + * expMonth: 12, + * expYear: 2020, + * cvc: '220' + * }; + * + * this.stripe.createCardToken(card) + * .then(token => console.log(token)) + * .catch(error => console.error(error)); + * + * ``` + * + * @interfaces + * StripeCardTokenParams + */ +@Plugin({ + pluginName: 'Stripe', + plugin: 'cordova-plugin-stripe', + pluginRef: 'cordova.plugins.stripe', + repo: 'https://github.com/zyramedia/cordova-plugin-stripe' +}) +@Injectable() +export class Stripe { + + /** + * Set publishable key + * @param publishableKey {string} Publishable key + * @return {Promise} + */ + @Cordova() + setPublishableKey(publishableKey: string): Promise { return; } + + /** + * Create Credit Card Token + * @param params {StripeCardTokenParams} Credit card information + * @return {Promise} returns a promise that resolves with the token, or rejects with an error + */ + @Cordova() + createCardToken(params: StripeCardTokenParams): Promise { return; } + + /** + * Create a bank account token + * @param params {StripeBankAccountParams} Bank account information + * @return {Promise} returns a promise that resolves with the token, or rejects with an error + */ + @Cordova() + createBankAccountToken(params: StripeBankAccountParams): Promise { return; } + + /** + * Validates a credit card number + * @param cardNumber {string} Credit card number + * @return {Promise} returns a promise that resolves if the number is valid, and rejects if it's invalid + */ + @Cordova() + validateCardNumber(cardNumber: string): Promise { return; } + + /** + * Validates a CVC number + * @param cvc {string} CVC number + * @return {Promise} returns a promise that resolves if the number is valid, and rejects if it's invalid + */ + @Cordova() + validateCVC(cvc: string): Promise { return; } + + /** + * Validates an expiry date + * @param expMonth {string} expiry month + * @param expYear {string} expiry year + * @return {Promise} returns a promise that resolves if the date is valid, and rejects if it's invalid + */ + @Cordova() + validateExpiryDate(expMonth: string, expYear: string): Promise { return; } + + /** + * Get a card type from card number + * @param cardNumber {string} Card number + * @return {Promise} returns a promise that resolves with the credit card type + */ + @Cordova() + getCardType(cardNumber: string): Promise { return; } + +} diff --git a/src/plugins/text-to-speech.ts b/src/@ionic-native/plugins/text-to-speech/index.ts similarity index 64% rename from src/plugins/text-to-speech.ts rename to src/@ionic-native/plugins/text-to-speech/index.ts index 8ba02dc05..8038a0bf2 100644 --- a/src/plugins/text-to-speech.ts +++ b/src/@ionic-native/plugins/text-to-speech/index.ts @@ -1,4 +1,5 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; export interface TTSOptions { /** text to speak */ @@ -16,9 +17,13 @@ export interface TTSOptions { * * @usage * ``` - * import {TextToSpeech} from 'ionic-native'; + * import { TextToSpeech } from '@ionic-native/text-to-speech'; * - * TextToSpeech.speak('Hello World') + * constructor(private tts: TextToSpeech) { } + * + * ... + * + * this.tts.speak('Hello World') * .then(() => console.log('Success')) * .catch((reason: any) => console.log(reason)); * @@ -27,11 +32,12 @@ export interface TTSOptions { * TTSOptions */ @Plugin({ - pluginName: 'TextToSpeech', + pluginName: 'Text To Speech', plugin: 'cordova-plugin-tts', pluginRef: 'TTS', repo: 'https://github.com/vilic/cordova-plugin-tts' }) +@Injectable() export class TextToSpeech { /** @@ -43,11 +49,16 @@ export class TextToSpeech { successIndex: 1, errorIndex: 2 }) - static speak(options: string | TTSOptions): Promise { + speak(options: string | TTSOptions): Promise { return; } - static stop(): Promise { + /** + * Stop any current TTS playback + * @return {Promise} + */ + @Cordova() + stop(): Promise { return; } diff --git a/src/plugins/themeable-browser.ts b/src/@ionic-native/plugins/themeable-browser/index.ts similarity index 80% rename from src/plugins/themeable-browser.ts rename to src/@ionic-native/plugins/themeable-browser/index.ts index 7451b83e1..c4f651b22 100644 --- a/src/plugins/themeable-browser.ts +++ b/src/@ionic-native/plugins/themeable-browser/index.ts @@ -1,6 +1,6 @@ -import { Plugin, CordovaInstance } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, CordovaInstance, InstanceCheck } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; -import { InAppBrowserEvent } from './inappbrowser'; declare var cordova: any; @@ -68,19 +68,90 @@ export interface ThemeableBrowserOptions { } /** - * @name ThemeableBrowser + * @hidden + */ +export class ThemeableBrowserObject { + + private _objectInstance: any; + + constructor(url: string, target: string, styleOptions: ThemeableBrowserOptions) { + try { + this._objectInstance = cordova.ThemeableBrowser.open(url, target, styleOptions); + } catch (e) { + window.open(url); + console.warn('Native: ThemeableBrowser is not installed or you are running on a browser. Falling back to window.open.'); + } + } + + /** + * Displays an browser window that was opened hidden. Calling this has no effect + * if the browser was already visible. + */ + @CordovaInstance({sync: true}) + show(): void { } + + /** + * Closes the browser window. + */ + @CordovaInstance({sync: true}) + close(): void { } + + /** + * Reloads the current page + */ + @CordovaInstance({ sync: true }) + reload(): void { } + + /** + * Injects JavaScript code into the browser window. + * @param script Details of the script to run, specifying either a file or code key. + * @returns {Promise} + */ + @CordovaInstance() + executeScript(script: {file?: string, code?: string}): Promise {return; } + + /** + * Injects CSS into the browser window. + * @param css Details of the script to run, specifying either a file or code key. + * @returns {Promise} + */ + @CordovaInstance() + insertCss(css: {file?: string, code?: string}): Promise {return; } + + /** + * A method that allows you to listen to events happening in the browser. + * Available events are: `ThemeableBrowserError`, `ThemeableBrowserWarning`, `critical`, `loadfail`, `unexpected`, `undefined` + * @param event Event name + * @returns {Observable} Returns back an observable that will listen to the event on subscribe, and will stop listening to the event on unsubscribe. + */ + @InstanceCheck({ observable: true }) + on(event: string): Observable { + return new Observable((observer) => { + this._objectInstance.addEventListener(event, observer.next.bind(observer)); + return () => this._objectInstance.removeEventListener(event, observer.next.bind(observer)); + }); + } + +} + +/** + * @name Themeable Browser * @description * In-app browser that allows styling. * * @usage * ``` - * import { ThemeableBrowser } from 'ionic-native'; + * import { ThemeableBrowser, ThemeableBrowserOptions, ThemeableBrowserObject } from '@ionic-native/themeable-browser'; + * + * constructor(private themeableBrowser: ThemeableBrowser) { } + * + * ... * * // can add options from the original InAppBrowser in a JavaScript object form (not string) * // This options object also takes additional parameters introduced by the ThemeableBrowser plugin * // This example only shows the additional parameters for ThemeableBrowser * // Note that that `image` and `imagePressed` values refer to resources that are stored in your app - * let options = { + * const options: ThemeableBrowserOptions = { * statusbar: { * color: '#ffffffff' * }, @@ -138,10 +209,12 @@ export interface ThemeableBrowserOptions { * backButtonCanClose: true * }; * - * let browser = new ThemeableBrowser('https://ionic.io', '_blank', options); + * const browser: ThemeableBrowserObject = this.themeableBrowser.create('https://ionic.io', '_blank', options); * * ``` * We suggest that you refer to the plugin's repository for additional information on usage that may not be covered here. + * @classes + * ThemeableBrowserObject * @interfaces * ThemeableBrowserButton * ThemeableBrowserOptions @@ -152,65 +225,18 @@ export interface ThemeableBrowserOptions { pluginRef: 'cordova.ThemeableBrowser', repo: 'https://github.com/initialxy/cordova-plugin-themeablebrowser' }) +@Injectable() export class ThemeableBrowser { - private _objectInstance: any; - - constructor(url: string, target: string, styleOptions: ThemeableBrowserOptions) { - try { - this._objectInstance = cordova.ThemeableBrowser.open(url, target, styleOptions); - } catch (e) { - window.open(url); - console.warn('Native: ThemeableBrowser is not installed or you are running on a browser. Falling back to window.open, all instance methods will NOT work.'); - } - } /** - * Displays an browser window that was opened hidden. Calling this has no effect - * if the browser was already visible. + * Creates a browser instance + * @param url {string} URL to open + * @param target {string} Target + * @param styleOptions {ThemeableBrowserOptions} Themeable browser options + * @returns {ThemeableBrowserObject} */ - @CordovaInstance({sync: true}) - show(): void { } - - /** - * Closes the browser window. - */ - @CordovaInstance({sync: true}) - close(): void { } - - /** - * Reloads the current page - */ - @CordovaInstance({ sync: true }) - reload(): void { } - - /** - * Injects JavaScript code into the browser window. - * @param script Details of the script to run, specifying either a file or code key. - * @returns {Promise} - */ - @CordovaInstance() - executeScript(script: {file?: string, code?: string}): Promise {return; } - - /** - * Injects CSS into the browser window. - * @param css Details of the script to run, specifying either a file or code key. - * @returns {Promise} - */ - @CordovaInstance() - insertCss(css: {file?: string, code?: string}): Promise {return; } - - /** - * A method that allows you to listen to events happening in the browser. - * Available events are: `ThemeableBrowserError`, `ThemeableBrowserWarning`, `critical`, `loadfail`, `unexpected`, `undefined` - * @param event Event name - * @returns {Observable} Returns back an observable that will listen to the event on subscribe, and will stop listening to the event on unsubscribe. - */ - on(event: string): Observable { - return new Observable((observer) => { - this._objectInstance.addEventListener(event, observer.next.bind(observer)); - return () => this._objectInstance.removeEventListener(event, observer.next.bind(observer)); - }); + create(url: string, target: string, styleOptions: ThemeableBrowserOptions): ThemeableBrowserObject { + return new ThemeableBrowserObject(url, target, styleOptions); } } - diff --git a/src/plugins/3dtouch.ts b/src/@ionic-native/plugins/three-dee-touch/index.ts similarity index 83% rename from src/plugins/3dtouch.ts rename to src/@ionic-native/plugins/three-dee-touch/index.ts index 894753450..7268f07fa 100644 --- a/src/plugins/3dtouch.ts +++ b/src/@ionic-native/plugins/three-dee-touch/index.ts @@ -1,6 +1,8 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; + declare var window: any; export interface ThreeDeeTouchQuickAction { @@ -57,20 +59,20 @@ export interface ThreeDeeTouchForceTouch { } /** - * @name 3DTouch + * @name 3D Touch * @description * @usage * Please do refer to the original plugin's repo for detailed usage. The usage example here might not be sufficient. * ``` - * import { ThreeDeeTouch } from 'ionic-native'; + * import { ThreeDeeTouch, ThreeDeeTouchQuickAction, ThreeDeeTouchForceTouch } from '@ionic-native/three-dee-touch'; + * + * constructor(private threeDeeTouch: ThreeDeeTouch) { } * - * // import for type completion on variables - * import { ThreeDeeTouchQuickAction, ThreeDeeTouchForceTouch } from 'ionic-native'; * ... * - * ThreeDeeTouch.isAvailable().then(isAvailable => console.log("3D Touch available? " + isAvailable)); + * this.threeDeeTouch.isAvailable().then(isAvailable => console.log("3D Touch available? " + isAvailable)); * - * ThreeDeeTouch.watchForceTouches() + * this.threeDeeTouch.watchForceTouches() * .subscribe( * (data: ThreeDeeTouchForceTouch) => { * console.log("Force touch %" + data.force); @@ -104,9 +106,10 @@ export interface ThreeDeeTouchForceTouch { * iconTemplate: 'HeartTemplate' * } * ]; - * ThreeDeeTouch.configureQuickActions(actions); * - * ThreeDeeTouch.onHomeIconPressed().subscribe( + * this.threeDeeTouch.configureQuickActions(actions); + * + * this.threeDeeTouch.onHomeIconPressed().subscribe( * (payload) => { * // returns an object that is the button you presed * console.log('Pressed the ${payload.title} button') @@ -126,6 +129,7 @@ export interface ThreeDeeTouchForceTouch { repo: 'https://github.com/EddyVerbruggen/cordova-plugin-3dtouch', platforms: ['iOS'] }) +@Injectable() export class ThreeDeeTouch { /** @@ -133,7 +137,7 @@ export class ThreeDeeTouch { * @returns {Promise} returns a promise that resolves with a boolean that indicates whether the plugin is available or not */ @Cordova() - static isAvailable(): Promise { return; } + isAvailable(): Promise { return; } /** * You can get a notification when the user force touches the webview. The plugin defines a Force Touch when at least 75% of the maximum force is applied to the screen. Your app will receive the x and y coordinates, so you have to figure out which UI element was touched. @@ -142,7 +146,7 @@ export class ThreeDeeTouch { @Cordova({ observable: true }) - static watchForceTouches(): Observable { return; } + watchForceTouches(): Observable { return; } /** * setup the 3D-touch actions, takes an array of objects with the following @@ -155,13 +159,13 @@ export class ThreeDeeTouch { @Cordova({ sync: true }) - static configureQuickActions(quickActions: Array): void { } + configureQuickActions(quickActions: Array): void { } /** * When a home icon is pressed, your app launches and this JS callback is invoked. * @returns {Observable} returns an observable that notifies you when he user presses on the home screen icon */ - static onHomeIconPressed(): Observable { + onHomeIconPressed(): Observable { return new Observable(observer => { if (window.ThreeDeeTouch) { window.ThreeDeeTouch.onHomeIconPressed = observer.next.bind(observer); @@ -179,7 +183,7 @@ export class ThreeDeeTouch { @Cordova({ sync: true }) - static enableLinkPreview(): void { } + enableLinkPreview(): void { } /** * Disabled the link preview feature, if enabled. @@ -187,6 +191,6 @@ export class ThreeDeeTouch { @Cordova({ sync: true }) - static disableLinkPreview(): void { } + disableLinkPreview(): void { } } diff --git a/src/plugins/toast.ts b/src/@ionic-native/plugins/toast/index.ts similarity index 84% rename from src/plugins/toast.ts rename to src/@ionic-native/plugins/toast/index.ts index 808da1a45..359016976 100644 --- a/src/plugins/toast.ts +++ b/src/@ionic-native/plugins/toast/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; import { Observable } from 'rxjs/Observable'; export interface ToastOptions { @@ -44,10 +45,13 @@ export interface ToastOptions { * * @usage * ```typescript - * import { Toast } from 'ionic-native'; + * import { Toast } from '@ionic-native/toast'; * + * constructor(private toast: Toast) { } * - * Toast.show("I'm a toast", '5000', 'center').subscribe( + * ... + * + * thisoast.show("I'm a toast", '5000', 'center').subscribe( * toast => { * console.log(toast); * } @@ -63,6 +67,7 @@ export interface ToastOptions { repo: 'https://github.com/EddyVerbruggen/Toast-PhoneGap-Plugin', platforms: ['Android', 'iOS', 'Windows Phone 8'] }) +@Injectable() export class Toast { /** @@ -77,18 +82,14 @@ export class Toast { observable: true, clearFunction: 'hide' }) - static show( - message: string, - duration: string, - position: string - ): Observable { return; } + show(message: string, duration: string, position: string): Observable { return; } /** * Manually hide any currently visible toast. * @returns {Promise} Returns a Promise that resolves on success. */ @Cordova() - static hide(): Promise { return; } + hide(): Promise { return; } /** * Show a native toast with the given options. @@ -105,7 +106,7 @@ export class Toast { observable: true, clearFunction: 'hide' }) - static showWithOptions(options: ToastOptions): Observable { return; } + showWithOptions(options: ToastOptions): Observable { return; } /** * Shorthand for `show(message, 'short', 'top')`. @@ -116,7 +117,7 @@ export class Toast { observable: true, clearFunction: 'hide' }) - static showShortTop(message: string): Observable { return; } + showShortTop(message: string): Observable { return; } /** * Shorthand for `show(message, 'short', 'center')`. @@ -127,7 +128,7 @@ export class Toast { observable: true, clearFunction: 'hide' }) - static showShortCenter(message: string): Observable { return; } + showShortCenter(message: string): Observable { return; } /** @@ -139,7 +140,7 @@ export class Toast { observable: true, clearFunction: 'hide' }) - static showShortBottom(message: string): Observable { return; } + showShortBottom(message: string): Observable { return; } /** @@ -151,7 +152,7 @@ export class Toast { observable: true, clearFunction: 'hide' }) - static showLongTop(message: string): Observable { return; } + showLongTop(message: string): Observable { return; } /** @@ -163,7 +164,7 @@ export class Toast { observable: true, clearFunction: 'hide' }) - static showLongCenter(message: string): Observable { return; } + showLongCenter(message: string): Observable { return; } /** @@ -175,6 +176,6 @@ export class Toast { observable: true, clearFunction: 'hide' }) - static showLongBottom(message: string): Observable { return; } + showLongBottom(message: string): Observable { return; } } diff --git a/src/plugins/touchid.ts b/src/@ionic-native/plugins/touch-id/index.ts similarity index 78% rename from src/plugins/touchid.ts rename to src/@ionic-native/plugins/touch-id/index.ts index c2e067a99..24ebc3f52 100644 --- a/src/plugins/touchid.ts +++ b/src/@ionic-native/plugins/touch-id/index.ts @@ -1,30 +1,29 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; /** - * @name TouchID + * @name Touch ID * @description * Scan the fingerprint of a user with the TouchID sensor. * * Requires Cordova plugin: `cordova-plugin-touch-id`. For more info, please see the [TouchID plugin docs](https://github.com/EddyVerbruggen/cordova-plugin-touch-id). * * @usage - * ### Import Touch ID Plugin into Project * ```typescript - * import { TouchID } from 'ionic-native'; - * ``` - * ### Check for Touch ID Availability - * ```typescript - * TouchID.isAvailable() + * import { TouchID } from '@ionic-native/touch-id'; + * + * constructor(private touchId: TouchID) { } + * + * ... + * + * this.touchId.isAvailable() * .then( * res => console.log('TouchID is available!'), * err => console.error('TouchID is not available', err) * ); - * ``` - * ### Invoke Touch ID w/ Custom Message * - * ```typescript - * TouchID.verifyFingerprint('Scan your fingerprint please') + * this.touchId.verifyFingerprint('Scan your fingerprint please') * .then( * res => console.log('Ok', res), * err => console.error('Error', err) @@ -51,6 +50,7 @@ import { Cordova, Plugin } from './plugin'; repo: 'https://github.com/EddyVerbruggen/cordova-plugin-touch-id', platforms: ['iOS'] }) +@Injectable() export class TouchID { /** @@ -59,7 +59,7 @@ export class TouchID { * @returns {Promise} Returns a Promise that resolves if yes, rejects if no. */ @Cordova() - static isAvailable(): Promise { return; } + isAvailable(): Promise { return; } /** * Show TouchID dialog and wait for a fingerprint scan. If user taps 'Enter Password' button, brings up standard system passcode screen. @@ -68,7 +68,7 @@ export class TouchID { * @returns {Promise} Returns a Promise the resolves if the fingerprint scan was successful, rejects with an error code (see above). */ @Cordova() - static verifyFingerprint(message: string): Promise { return; } + verifyFingerprint(message: string): Promise { return; } /** * Show TouchID dialog and wait for a fingerprint scan. If user taps 'Enter Password' button, rejects with code '-3' (see above). @@ -77,7 +77,7 @@ export class TouchID { * @returns {Promise} Returns a Promise the resolves if the fingerprint scan was successful, rejects with an error code (see above). */ @Cordova() - static verifyFingerprintWithCustomPasswordFallback(message: string): Promise { return; } + verifyFingerprintWithCustomPasswordFallback(message: string): Promise { return; } /** * Show TouchID dialog with custom 'Enter Password' message and wait for a fingerprint scan. If user taps 'Enter Password' button, rejects with code '-3' (see above). @@ -87,6 +87,6 @@ export class TouchID { * @returns {Promise} Returns a Promise the resolves if the fingerprint scan was successful, rejects with an error code (see above). */ @Cordova() - static verifyFingerprintWithCustomPasswordFallbackAndEnterPasswordLabel(message: string, enterPasswordLabel: string): Promise { return; } + verifyFingerprintWithCustomPasswordFallbackAndEnterPasswordLabel(message: string, enterPasswordLabel: string): Promise { return; } } diff --git a/src/plugins/filetransfer.ts b/src/@ionic-native/plugins/transfer/index.ts similarity index 81% rename from src/plugins/filetransfer.ts rename to src/@ionic-native/plugins/transfer/index.ts index 1ecae1f35..b5dba36d7 100644 --- a/src/plugins/filetransfer.ts +++ b/src/@ionic-native/plugins/transfer/index.ts @@ -1,4 +1,5 @@ -import { CordovaInstance, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { CordovaInstance, Plugin, InstanceCheck, checkAvailability } from '@ionic-native/core'; declare var FileTransfer; @@ -115,11 +116,14 @@ export interface FileTransferError { * * @usage * ```typescript - * import { Transfer } from 'ionic-native'; + * import { Transfer, FileUploadOptions, TransferObject } from '@ionic-native/transfer'; + * import { File } from '@ionic-native/file'; * + * constructor(private transfer: Transfer, private file: File) { } * - * // Create instance: - * const fileTransfer = new Transfer(); + * ... + * + * const fileTransfer: TransferObject = this.transfer.create(); * * // Upload a file: * fileTransfer.upload(..).then(..).catch(..); @@ -130,33 +134,26 @@ export interface FileTransferError { * // Abort active transfer: * fileTransfer.abort(); * - * E.g - * - * upload(){ - * const fileTransfer = new Transfer(); - * var options: any; - * - * options = { + * // full example + * upload() { + * let options: FileUploadOptions = { * fileKey: 'file', * fileName: 'name.jpg', * headers: {} * ..... * } - * fileTransfer.upload("", "", options) + * + * fileTransfer.upload('', '', options) * .then((data) => { * // success * }, (err) => { * // error * }) * } - * - * // Cordova - * declare var cordova: any; - * + ** * download() { - * const fileTransfer = new Transfer(); - * let url = 'http://www.example.com/file.pdf'; - * fileTransfer.download(url, cordova.file.dataDirectory + 'file.pdf').then((entry) => { + * const url = 'http://www.example.com/file.pdf'; + * fileTransfer.download(url, this.file.dataDirectory + 'file.pdf').then((entry) => { * console.log('download complete: ' + entry.toURL()); * }, (error) => { * // handle error @@ -165,15 +162,6 @@ export interface FileTransferError { * * ``` * - * Note: You will not see your documents using a file explorer on your device. Use adb: - * - * ``` - * adb shell - * run-as com.your.app - * cd files - * ls - * ``` - * * To store files in a different/publicly accessible directory, please refer to the following link * https://github.com/apache/cordova-plugin-file#where-to-store-files * @@ -181,6 +169,8 @@ export interface FileTransferError { * FileUploadOptions * FileUploadResult * FileTransferError + * @classes + * TransferObject */ @Plugin({ pluginName: 'FileTransfer', @@ -188,6 +178,7 @@ export interface FileTransferError { pluginRef: 'FileTransfer', repo: 'https://github.com/apache/cordova-plugin-file-transfer' }) +@Injectable() export class Transfer { /** @@ -197,10 +188,10 @@ export class Transfer { * INVALID_URL_ERR: 2, Return when url was invalid * CONNECTION_ERR: 3, Return on connection error * ABORT_ERR: 4, Return on aborting - * NOT_MODIFIED_ERR: 5 Return on "304 Not Modified" HTTP response + * NOT_MODIFIED_ERR: 5 Return on '304 Not Modified' HTTP response * @enum {number} */ - public static FileTransferErrorCode = { + FileTransferErrorCode = { FILE_NOT_FOUND_ERR: 1, INVALID_URL_ERR: 2, CONNECTION_ERR: 3, @@ -208,10 +199,30 @@ export class Transfer { NOT_MODIFIED_ERR: 5 }; + /** + * Creates a new FileTransfer object + * @return {TransferObject} + */ + create(): TransferObject { + return new TransferObject(); + } + +} + +/** + * @hidden + */ +@Plugin({ + plugin: 'cordova-plugin-file-transfer', + pluginName: 'FileTransfer' +}) +export class TransferObject { private _objectInstance: any; constructor() { - this._objectInstance = new FileTransfer(); + if (checkAvailability('FileTransfer', null, 'FileTransfer') === true) { + this._objectInstance = new FileTransfer(); + } } /** @@ -250,9 +261,9 @@ export class Transfer { /** * Registers a listener that gets called whenever a new chunk of data is transferred. - * @param {function} Listener that takes a progress event. + * @param listener {function} Listener that takes a progress event. */ - + @InstanceCheck({ sync: true }) onProgress(listener: (event: ProgressEvent) => any): void { this._objectInstance.onprogress = listener; } @@ -265,5 +276,4 @@ export class Transfer { sync: true }) abort(): void { } - } diff --git a/src/plugins/twitter-connect.ts b/src/@ionic-native/plugins/twitter-connect/index.ts similarity index 73% rename from src/plugins/twitter-connect.ts rename to src/@ionic-native/plugins/twitter-connect/index.ts index 7dca4e4c6..653e8e662 100644 --- a/src/plugins/twitter-connect.ts +++ b/src/@ionic-native/plugins/twitter-connect/index.ts @@ -1,4 +1,5 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; export interface TwitterConnectResponse { /** @@ -25,7 +26,11 @@ export interface TwitterConnectResponse { * Plugin to use Twitter Single Sign On * Uses Twitter's Fabric SDK * ```typescript - * import {TwitterConnect} from 'ionic-native'; + * import { TwitterConnect } from '@ionic-native/twitter-connect'; + * + * constructor(private twitter: TwitterConnect) { } + * + * ... * * function onSuccess(response) { * console.log(response); @@ -39,9 +44,9 @@ export interface TwitterConnectResponse { * // } * } * - * TwitterConnect.login().then(onSuccess, onError); + * this.twitter.login().then(onSuccess, onError); * - * TwitterConnect.logout().then(onLogoutSuccess, onLogoutError); + * this.twitter.logout().then(onLogoutSuccess, onLogoutError); * ``` * @interfaces * TwitterConnectResponse @@ -51,27 +56,28 @@ export interface TwitterConnectResponse { plugin: 'twitter-connect-plugin', pluginRef: 'TwitterConnect', repo: 'https://github.com/ManifestWebDesign/twitter-connect-plugin', - install: 'ionic plugin add twitter-connect-plugin --variable FABRIC_KEY=fabric_API_key' + install: 'ionic plugin add twitter-connect-plugin --variable FABRIC_KEY=fabric_API_key', + installVariables: ['FABRIC_KEY'] }) +@Injectable() export class TwitterConnect { /** * Logs in * @returns {Promise} returns a promise that resolves if logged in and rejects if failed to login */ @Cordova() - static login(): Promise {return; } + login(): Promise {return; } /** * Logs out * @returns {Promise} returns a promise that resolves if logged out and rejects if failed to logout */ @Cordova() - static logout(): Promise {return; } + logout(): Promise {return; } /** * Returns user's profile information * @returns {Promise} returns a promise that resolves if user profile is successfully retrieved and rejects if request fails */ @Cordova() - static showUser(): Promise {return; } + showUser(): Promise {return; } } - diff --git a/src/plugins/unique-device-id.ts b/src/@ionic-native/plugins/unique-device-id/index.ts similarity index 64% rename from src/plugins/unique-device-id.ts rename to src/@ionic-native/plugins/unique-device-id/index.ts index aea049aec..1674c9689 100644 --- a/src/plugins/unique-device-id.ts +++ b/src/@ionic-native/plugins/unique-device-id/index.ts @@ -1,15 +1,20 @@ -import { Plugin, Cordova } from './plugin'; +import { Plugin, Cordova } from '@ionic-native/core'; +import { Injectable } from '@angular/core'; /** - * @name UniqueDeviceID + * @name Unique Device ID * @description * This plugin produces a unique, cross-install, app-specific device id. * * @usage * ``` - * import { UniqueDeviceID } from 'ionic-native'; + * import { UniqueDeviceID } from '@ionic-native/unique-device-id'; * - * UniqueDeviceID.get() + * constructor(private uniqueDeviceID: UniqueDeviceID) { } + * + * ... + * + * this.uniqueDeviceID.get() * .then((uuid: any) => console.log(uuid)) * .catch((error: any) => console.log(error)); * @@ -21,6 +26,7 @@ import { Plugin, Cordova } from './plugin'; pluginRef: 'window.plugins.uniqueDeviceID', repo: 'https://github.com/Paldom/UniqueDeviceID' }) +@Injectable() export class UniqueDeviceID { /** @@ -28,6 +34,6 @@ export class UniqueDeviceID { * @return {Promise} Returns a promise that resolves when something happens */ @Cordova() - static get(): Promise { return; } + get(): Promise { return; } } diff --git a/src/plugins/vibration.ts b/src/@ionic-native/plugins/vibration/index.ts similarity index 71% rename from src/plugins/vibration.ts rename to src/@ionic-native/plugins/vibration/index.ts index 0833cd045..354910869 100644 --- a/src/plugins/vibration.ts +++ b/src/@ionic-native/plugins/vibration/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; /** @@ -6,22 +7,25 @@ import { Cordova, Plugin } from './plugin'; * @description Vibrates the device * @usage * ```typescript - * import { Vibration } from 'ionic-native'; + * import { Vibration } from '@ionic-native/vibration'; * + * constructor(private vibration: Vibration) { } + * + * ... * * // Vibrate the device for a second * // Duration is ignored on iOS. - * Vibration.vibrate(1000); + * this.vibration.vibrate(1000); * * // Vibrate 2 seconds * // Pause for 1 second * // Vibrate for 2 seconds * // Patterns work on Android and Windows only - * Vibration.vibrate([2000,1000,2000]); + * this.vibration.vibrate([2000,1000,2000]); * * // Stop any current vibrations immediately * // Works on Android and Windows only - * Vibration.vibrate(0); + * this.vibration.vibrate(0); * ``` */ @Plugin({ @@ -31,6 +35,7 @@ import { Cordova, Plugin } from './plugin'; repo: 'https://github.com/apache/cordova-plugin-vibration', platforms: ['Android', 'iOS', 'Windows 8.1 Phone', 'Windows 8.1', 'Windows 10'] }) +@Injectable() export class Vibration { /** @@ -40,6 +45,6 @@ export class Vibration { @Cordova({ sync: true }) - static vibrate(time: number | Array) { } + vibrate(time: number | Array) { } } diff --git a/src/plugins/video-editor.ts b/src/@ionic-native/plugins/video-editor/index.ts similarity index 88% rename from src/plugins/video-editor.ts rename to src/@ionic-native/plugins/video-editor/index.ts index bb42494b9..37293c02f 100644 --- a/src/plugins/video-editor.ts +++ b/src/@ionic-native/plugins/video-editor/index.ts @@ -1,4 +1,5 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; export interface TranscodeOptions { @@ -119,14 +120,18 @@ export interface VideoInfo { } /** - * @name VideoEditor + * @name Video Editor * @description Edit videos using native device APIs * * @usage * ``` - * import {VideoEditor} from 'ionic-native'; + * import { VideoEditor } from '@ionic-native/video-editor'; * - * VideoEditor.transcodeVideo({ + * constructor(private videoEditor: VideoEditor) { } + * + * ... + * + * this.videoEditor.transcodeVideo({ * fileUri: '/path/to/input.mov', * outputFileName: 'output.mp4', * outputFileType: VideoEditor.OutputFileType.MPEG4 @@ -149,14 +154,15 @@ export interface VideoInfo { repo: 'https://github.com/jbavari/cordova-plugin-video-editor', platforms: ['Android', 'iOS', 'Windows Phone 8'] }) +@Injectable() export class VideoEditor { - static OptimizeForNetworkUse = { + OptimizeForNetworkUse = { NO: 0, YES: 1 }; - static OutputFileType = { + OutputFileType = { M4V: 0, MPEG4: 1, M4A: 2, @@ -171,7 +177,7 @@ export class VideoEditor { @Cordova({ callbackOrder: 'reverse' }) - static transcodeVideo(options: TranscodeOptions): Promise { return; } + transcodeVideo(options: TranscodeOptions): Promise { return; } /** * Trim a video @@ -182,7 +188,7 @@ export class VideoEditor { callbackOrder: 'reverse', platforms: ['iOS'] }) - static trim(options: TrimOptions): Promise { return; } + trim(options: TrimOptions): Promise { return; } /** * Create a JPEG thumbnail from a video @@ -192,7 +198,7 @@ export class VideoEditor { @Cordova({ callbackOrder: 'reverse' }) - static createThumbnail(options: CreateThumbnailOptions): Promise { return; } + createThumbnail(options: CreateThumbnailOptions): Promise { return; } /** * Get info on a video (width, height, orientation, duration, size, & bitrate) @@ -202,6 +208,6 @@ export class VideoEditor { @Cordova({ callbackOrder: 'reverse' }) - static getVideoInfo(options: GetVideoInfoOptions): Promise { return; } + getVideoInfo(options: GetVideoInfoOptions): Promise { return; } } diff --git a/src/plugins/video-player.ts b/src/@ionic-native/plugins/video-player/index.ts similarity index 80% rename from src/plugins/video-player.ts rename to src/@ionic-native/plugins/video-player/index.ts index 20b02ce5c..74c3a31a8 100644 --- a/src/plugins/video-player.ts +++ b/src/@ionic-native/plugins/video-player/index.ts @@ -1,4 +1,5 @@ -import { Cordova, Plugin } from './plugin'; +import { Injectable } from '@angular/core'; +import { Cordova, Plugin } from '@ionic-native/core'; /** * Options for the video playback using the `play` function. @@ -25,11 +26,14 @@ export interface VideoOptions { * * @usage * ```typescript - * import { VideoPlayer } from 'ionic-native'; + * import { VideoPlayer } from '@ionic-native/video-player; * + * constructor(private videoPlayer: VideoPlayer) { } + * + * ... * * // Playing a video. - * VideoPlayer.play("file:///android_asset/www/movie.mp4").then(() => { + * this.videoPlayer.play("file:///android_asset/www/movie.mp4").then(() => { * console.log('video completed'); * }).catch(err => { * console.log(err); @@ -46,6 +50,7 @@ export interface VideoOptions { repo: 'https://github.com/moust/cordova-plugin-videoplayer', platforms: ['Android'] }) +@Injectable() export class VideoPlayer { /** @@ -55,11 +60,11 @@ export class VideoPlayer { * @returns {Promise} Resolves promise when the video was played successfully. */ @Cordova() - static play(fileUrl: string, options?: VideoOptions): Promise { return; } + play(fileUrl: string, options?: VideoOptions): Promise { return; } /** * Stops the video playback immediatly. */ @Cordova({ sync: true }) - static close(): void { } + close(): void { } } diff --git a/src/@ionic-native/plugins/web-intent/index.ts b/src/@ionic-native/plugins/web-intent/index.ts new file mode 100644 index 000000000..0a0bb3ebf --- /dev/null +++ b/src/@ionic-native/plugins/web-intent/index.ts @@ -0,0 +1,144 @@ +import { Injectable } from '@angular/core'; +import { Cordova, CordovaProperty, Plugin } from '@ionic-native/core'; +import { Observable } from 'rxjs/Observable'; + +declare var window; + +/** + * @name Web Intent + * @description + * @usage + * For usage information please refer to the plugin's Github repo. + * + * ```typescript + * import { WebIntent } from '@ionic-native/web-intent'; + * + * constructor(private webIntent: WebIntent) { } + * + * ... + * + * const options = { + * action: this.webIntent.ACTION_VIEW, + * url: 'path/to/file', + * type: 'application/vnd.android.package-archive' + * }; + * + * this.webIntent.startActivity(options).then(onSuccess, onError); + * + * ``` + */ +@Plugin({ + pluginName: 'WebIntent', + plugin: 'https://github.com/Initsogar/cordova-webintent.git', + pluginRef: 'window.plugins.webintent', + repo: 'https://github.com/Initsogar/cordova-webintent.git', + platforms: ['Android'] +}) +@Injectable() +export class WebIntent { + + /** + * Convenience constant for actions + * @type {string} + */ + @CordovaProperty + ACTION_SEND: string; + + /** + * Convenience constant for actions + * @type {string} + */ + @CordovaProperty + ACTION_VIEW: string; + + /** + * Convenience constant for extras + * @type {string} + */ + @CordovaProperty + EXTRA_TEXT: string; + + /** + * Convenience constant for extras + * @type {string} + */ + @CordovaProperty + EXTRA_SUBJECT: string; + + /** + * Convenience constant for extras + * @type {string} + */ + @CordovaProperty + EXTRA_STREAM: string; + + /** + * Convenience constant for extras + * @type {string} + */ + @CordovaProperty + EXTRA_EMAIL: string; + + /** + * Convenience constant for actions + * @type {string} + */ + @CordovaProperty + ACTION_CALL: string; + + /** + * Convenience constant for actions + * @type {string} + */ + @CordovaProperty + ACTION_SENDTO: string; + + + /** + * Launches an Android intent + * @param options {Object} { action: any, url: string, type?: string } + * @returns {Promise} + */ + @Cordova() + startActivity(options: { action: any, url: string, type?: string }): Promise { return; } + + /** + * Checks if this app was invoked with specified extra + * @param extra {string} + * @returns {Promise} + */ + @Cordova() + hasExtra(extra: string): Promise { return; } + + /** + * Gets the extra that this app was invoked with + * @param extra {string} + * @returns {Promise} + */ + @Cordova() + getExtra(extra: string): Promise { return; } + + /** + * Gets the Uri the app was invoked with + * @returns {Promise} + */ + @Cordova() + getUri(): Promise { return; }; + + /** + * @returns {Observable} + */ + @Cordova({ + observable: true + }) + onNewIntent(): Observable { return; }; + + /** + * Sends a custom intent passing optional extras + * @param options {Object} { action: string, extras?: { option: boolean } } + * @returns {Promise} + */ + @Cordova() + sendBroadcast(options: { action: string, extras?: { option: boolean } }): Promise { return; } + +} diff --git a/src/plugins/youtube-video-player.ts b/src/@ionic-native/plugins/youtube-video-player/index.ts similarity index 57% rename from src/plugins/youtube-video-player.ts rename to src/@ionic-native/plugins/youtube-video-player/index.ts index 9e9fc2217..b4e453291 100644 --- a/src/plugins/youtube-video-player.ts +++ b/src/@ionic-native/plugins/youtube-video-player/index.ts @@ -1,14 +1,20 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; /** - * @name YoutubeVideoPlayer + * @name Youtube Video Player * @description * Plays YouTube videos in Native YouTube App * * @usage * ``` - * import {YoutubeVideoPlayer} from 'ionic-native'; + * import { YoutubeVideoPlayer } from '@ionic-native/youtube-video-player'; * - * YoutubeVideoPlayer.openVideo('myvideoid'); + * constructor(private youtube: YoutubeVideoPlayer) { } + * + * ... + * + * + * this.youtube.openVideo('myvideoid'); * * ``` */ @@ -19,11 +25,12 @@ import { Plugin, Cordova } from './plugin'; repo: 'https://github.com/Glitchbone/CordovaYoutubeVideoPlayer', platforms: ['Android', 'iOS'] }) +@Injectable() export class YoutubeVideoPlayer { /** * Plays a YouTube video * @param videoId {string} Video ID */ @Cordova({sync: true}) - static openVideo(videoId: string): void { } + openVideo(videoId: string): void { } } diff --git a/src/plugins/z-bar.ts b/src/@ionic-native/plugins/zbar/index.ts similarity index 83% rename from src/plugins/z-bar.ts rename to src/@ionic-native/plugins/zbar/index.ts index e8c54bcfb..5ac42e8fd 100644 --- a/src/plugins/z-bar.ts +++ b/src/@ionic-native/plugins/zbar/index.ts @@ -1,4 +1,5 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; export interface ZBarOptions { /** @@ -43,14 +44,18 @@ export interface ZBarOptions { * * @usage * ``` - * import { ZBar } from 'ionic-native'; + * import { ZBar, ZBarOptions } from '@ionic-native/z-bar'; * - * let zBarOptions = { + * constructor(private zbar: ZBar) { } + * + * ... + * + * let ZBarOptions = { * flash: "off", * drawSight: false * }; * - * ZBar.scan(zBarOptions) + * this.zbar.scan(zBarOptions) * .then(result => { * console.log(result); // Scanned code * }) @@ -70,6 +75,7 @@ export interface ZBarOptions { repo: 'https://github.com/tjwoon/csZBar', platforms: ['Android', 'iOS'] }) +@Injectable() export class ZBar { /** @@ -78,6 +84,6 @@ export class ZBar { * @returns {Promise} Returns a Promise that resolves with the scanned string, or rejects with an error. */ @Cordova() - static scan(options: ZBarOptions): Promise { return; } + scan(options: ZBarOptions): Promise { return; } } diff --git a/src/plugins/zip.ts b/src/@ionic-native/plugins/zip/index.ts similarity index 63% rename from src/plugins/zip.ts rename to src/@ionic-native/plugins/zip/index.ts index 8dabc12ba..50489ce2a 100644 --- a/src/plugins/zip.ts +++ b/src/@ionic-native/plugins/zip/index.ts @@ -1,4 +1,5 @@ -import { Plugin, Cordova } from './plugin'; +import { Injectable } from '@angular/core'; +import { Plugin, Cordova } from '@ionic-native/core'; /** * @name Zip @@ -7,9 +8,13 @@ import { Plugin, Cordova } from './plugin'; * * @usage * ``` - * import {Zip} from 'ionic-native'; + * import { Zip } from '@ionic-native/zip'; * - * Zip.unzip('path/to/source.zip', 'path/to/dest', (progress) => console.log('Unzipping, ' + Math.round((progress.loaded / progress.total) * 100) + '%')) + * constructor(private zip: Zip) { } + * + * ... + * + * this.zip.unzip('path/to/source.zip', 'path/to/dest', (progress) => console.log('Unzipping, ' + Math.round((progress.loaded / progress.total) * 100) + '%')) * .then((result) => { * if(result === 0) console.log('SUCCESS'); * if(result === -1) console.log('FAILED'); @@ -23,7 +28,9 @@ import { Plugin, Cordova } from './plugin'; pluginRef: 'zip', repo: 'https://github.com/MobileChromeApps/cordova-plugin-zip', }) +@Injectable() export class Zip { + /** * Extracts files from a ZIP archive * @param sourceZip {string} Source ZIP file @@ -35,6 +42,6 @@ export class Zip { successIndex: 2, errorIndex: 4 }) - static unzip(sourceZip: string, destUrl: string, onProgress?: Function): Promise {return; } + unzip(sourceZip: string, destUrl: string, onProgress?: Function): Promise {return; } } diff --git a/src/index.ts b/src/index.ts deleted file mode 100644 index d65bffc64..000000000 --- a/src/index.ts +++ /dev/null @@ -1,429 +0,0 @@ -import { initAngular1 } from './ng1'; - -const DEVICE_READY_TIMEOUT = 5000; - -declare var window; -import { ActionSheet } from './plugins/actionsheet'; -import { AdMob } from './plugins/admob'; -import { Alipay } from './plugins/alipay'; -import { AndroidFingerprintAuth } from './plugins/android-fingerprint-auth'; -import { AppAvailability } from './plugins/appavailability'; -import { Appodeal } from './plugins/appodeal'; -import { AppRate } from './plugins/apprate'; -import { AppPreferences } from './plugins/apppreferences'; -import { AppUpdate } from './plugins/app-update'; -import { AppVersion } from './plugins/appversion'; -import { Badge } from './plugins/badge'; -import { BackgroundFetch } from './plugins/background-fetch'; -import { BackgroundGeolocation } from './plugins/background-geolocation'; -import { BackgroundMode } from './plugins/backgroundmode'; -import { Backlight } from './plugins/backlight'; -import { BarcodeScanner } from './plugins/barcodescanner'; -import { Base64ToGallery } from './plugins/base64togallery'; -import { BatteryStatus } from './plugins/batterystatus'; -import { Brightness } from './plugins/brightness'; -import { BrowserTab } from './plugins/browser-tab'; -import { BLE } from './plugins/ble'; -import { BluetoothSerial } from './plugins/bluetoothserial'; -import { Broadcaster } from './plugins/broadcaster'; -import { Calendar } from './plugins/calendar'; -import { CallNumber } from './plugins/call-number'; -import { Camera } from './plugins/camera'; -import { CameraPreview } from './plugins/camera-preview'; -import { CardIO } from './plugins/card-io'; -import { Clipboard } from './plugins/clipboard'; -import { CodePush } from './plugins/code-push'; -import { Contacts } from './plugins/contacts'; -import { CouchbaseLite } from './plugins/couchbase-lite'; -import { Crop } from './plugins/crop'; -import { DatePicker } from './plugins/datepicker'; -import { DBMeter } from './plugins/dbmeter'; -import { Deeplinks } from './plugins/deeplinks'; -import { Device } from './plugins/device'; -import { DeviceFeedback } from './plugins/device-feedback'; -import { DeviceAccounts } from './plugins/deviceaccounts'; -import { DeviceMotion } from './plugins/devicemotion'; -import { DeviceOrientation } from './plugins/deviceorientation'; -import { Diagnostic } from './plugins/diagnostic'; -import { Dialogs } from './plugins/dialogs'; -import { EmailComposer } from './plugins/emailcomposer'; -import { EstimoteBeacons } from './plugins/estimote-beacons'; -import { Facebook } from './plugins/facebook'; -import { File } from './plugins/file'; -import { FileChooser } from './plugins/file-chooser'; -import { FileOpener } from './plugins/file-opener'; -import { FilePath } from './plugins/filepath'; -import { Transfer } from './plugins/filetransfer'; -import { FingerprintAIO } from './plugins/fingerprint-aio'; -import { Firebase } from './plugins/firebase'; -import { Flashlight } from './plugins/flashlight'; -import { Geofence } from './plugins/geofence'; -import { Geolocation } from './plugins/geolocation'; -import { Globalization } from './plugins/globalization'; -import { GooglePlus } from './plugins/google-plus'; -import { GoogleMap } from './plugins/googlemap'; -import { GoogleAnalytics } from './plugins/googleanalytics'; -import { Gyroscope } from './plugins/gyroscope'; -import { HeaderColor } from './plugins/headercolor'; -import { Health } from './plugins/health'; -import { Hotspot } from './plugins/hotspot'; -import { HTTP } from './plugins/http'; -import { Httpd } from './plugins/httpd'; -import { IBeacon } from './plugins/ibeacon'; -import { ImagePicker } from './plugins/imagepicker'; -import { ImageResizer } from './plugins/imageresizer'; -import { InAppBrowser } from './plugins/inappbrowser'; -import { InAppPurchase } from './plugins/inapppurchase'; -import { Insomnia } from './plugins/insomnia'; -import { Instagram } from './plugins/instagram'; -import { IsDebug } from './plugins/is-debug'; -import { Keyboard } from './plugins/keyboard'; -import { LaunchNavigator } from './plugins/launchnavigator'; -import { LaunchReview } from './plugins/launch-review'; -import { LocalNotifications } from './plugins/localnotifications'; -import { LocationAccuracy } from './plugins/location-accuracy'; -import { MediaCapture } from './plugins/media-capture'; -import { NativeAudio } from './plugins/native-audio'; -import { NativeGeocoder } from './plugins/native-geocoder'; -import { NativePageTransitions } from './plugins/native-page-transitions'; -import { NativeStorage } from './plugins/nativestorage'; -import { NavigationBar } from './plugins/navigationbar'; -import { Market } from './plugins/market'; -import { MediaPlugin } from './plugins/media'; -import { Mixpanel } from './plugins/mixpanel'; -import { MusicControls } from './plugins/music-controls'; -import { Network } from './plugins/network'; -import { NFC } from './plugins/nfc'; -import { OneSignal } from './plugins/onesignal'; -import { PhotoViewer } from './plugins/photo-viewer'; -import { ScreenOrientation } from './plugins/screen-orientation'; -import { PayPal } from './plugins/pay-pal'; -import { Pedometer } from './plugins/pedometer'; -import { PhotoLibrary } from './plugins/photo-library'; -import { PinDialog } from './plugins/pin-dialog'; -import { Pinterest } from './plugins/pinterest'; -import { PowerManagement } from './plugins/power-management'; -import { Printer } from './plugins/printer'; -import { Push } from './plugins/push'; -import { Rollbar } from './plugins/rollbar'; -import { SafariViewController } from './plugins/safari-view-controller'; -import { Screenshot } from './plugins/screenshot'; -import { SecureStorage } from './plugins/securestorage'; -import { Serial } from './plugins/serial'; -import { Shake } from './plugins/shake'; -import { Sim } from './plugins/sim'; -import { SMS } from './plugins/sms'; -import { SocialSharing } from './plugins/socialsharing'; -import { SpeechRecognition } from './plugins/speech-recognition'; -import { SpinnerDialog } from './plugins/spinnerdialog'; -import { Splashscreen } from './plugins/splashscreen'; -import { SQLite } from './plugins/sqlite'; -import { StatusBar } from './plugins/statusbar'; -import { Stepcounter } from './plugins/stepcounter'; -import { StreamingMedia } from './plugins/streaming-media'; -import { Stripe } from './plugins/stripe'; -import { ThreeDeeTouch } from './plugins/3dtouch'; -import { Toast } from './plugins/toast'; -import { TouchID } from './plugins/touchid'; -import { TextToSpeech } from './plugins/text-to-speech'; -import { ThemeableBrowser } from './plugins/themeable-browser'; -import { TwitterConnect } from './plugins/twitter-connect'; -import { UniqueDeviceID } from './plugins/unique-device-id'; -import { Vibration } from './plugins/vibration'; -import { VideoEditor } from './plugins/video-editor'; -import { VideoPlayer } from './plugins/video-player'; -import { WebIntent } from './plugins/webintent'; -import { YoutubeVideoPlayer } from './plugins/youtube-video-player'; -import { ZBar } from './plugins/z-bar'; -import { Zip } from './plugins/zip'; -export * from './plugins/3dtouch'; -export * from './plugins/actionsheet'; -export * from './plugins/admob'; -export * from './plugins/alipay'; -export * from './plugins/android-fingerprint-auth'; -export * from './plugins/appavailability'; -export * from './plugins/apppreferences'; -export * from './plugins/appodeal'; -export * from './plugins/apprate'; -export * from './plugins/app-update'; -export * from './plugins/appversion'; -export * from './plugins/background-fetch'; -export * from './plugins/background-geolocation'; -export * from './plugins/backgroundmode'; -export * from './plugins/backlight'; -export * from './plugins/badge'; -export * from './plugins/barcodescanner'; -export * from './plugins/base64togallery'; -export * from './plugins/batterystatus'; -export * from './plugins/ble'; -export * from './plugins/bluetoothserial'; -export * from './plugins/brightness'; -export * from './plugins/browser-tab'; -export * from './plugins/broadcaster'; -export * from './plugins/calendar'; -export * from './plugins/call-number'; -export * from './plugins/camera'; -export * from './plugins/camera-preview'; -export * from './plugins/card-io'; -export * from './plugins/clipboard'; -export * from './plugins/code-push'; -export * from './plugins/contacts'; -export * from './plugins/couchbase-lite'; -export * from './plugins/crop'; -export * from './plugins/datepicker'; -export * from './plugins/dbmeter'; -export * from './plugins/deeplinks'; -export * from './plugins/device'; -export * from './plugins/device-feedback'; -export * from './plugins/deviceaccounts'; -export * from './plugins/devicemotion'; -export * from './plugins/deviceorientation'; -export * from './plugins/diagnostic'; -export * from './plugins/dialogs'; -export * from './plugins/emailcomposer'; -export * from './plugins/estimote-beacons'; -export * from './plugins/facebook'; -export * from './plugins/file'; -export * from './plugins/file-chooser'; -export * from './plugins/file-opener'; -export * from './plugins/filetransfer'; -export * from './plugins/firebase'; -export * from './plugins/filepath'; -export * from './plugins/fingerprint-aio'; -export * from './plugins/flashlight'; -export * from './plugins/geofence'; -export * from './plugins/geolocation'; -export * from './plugins/globalization'; -export * from './plugins/google-plus'; -export * from './plugins/googleanalytics'; -export * from './plugins/googlemap'; -export * from './plugins/gyroscope'; -export * from './plugins/headercolor'; -export * from './plugins/health'; -export * from './plugins/hotspot'; -export * from './plugins/http'; -export * from './plugins/httpd'; -export * from './plugins/ibeacon'; -export * from './plugins/imagepicker'; -export * from './plugins/imageresizer'; -export * from './plugins/inappbrowser'; -export * from './plugins/inapppurchase'; -export * from './plugins/insomnia'; -export * from './plugins/instagram'; -export * from './plugins/is-debug'; -export * from './plugins/keyboard'; -export * from './plugins/launchnavigator'; -export * from './plugins/launch-review'; -export * from './plugins/localnotifications'; -export * from './plugins/location-accuracy'; -export * from './plugins/market'; -export * from './plugins/media'; -export * from './plugins/media-capture'; -export * from './plugins/mixpanel'; -export * from './plugins/music-controls'; -export * from './plugins/native-audio'; -export * from './plugins/native-geocoder'; -export * from './plugins/native-page-transitions'; -export * from './plugins/nativestorage'; -export * from './plugins/navigationbar'; -export * from './plugins/network'; -export * from './plugins/nfc'; -export * from './plugins/onesignal'; -export * from './plugins/pay-pal'; -export * from './plugins/pedometer'; -export * from './plugins/photo-library'; -export * from './plugins/photo-viewer'; -export * from './plugins/pin-dialog'; -export * from './plugins/pinterest'; -export * from './plugins/plugin'; -export * from './plugins/power-management'; -export * from './plugins/printer'; -export * from './plugins/push'; -export * from './plugins/rollbar'; -export * from './plugins/safari-view-controller'; -export * from './plugins/screen-orientation'; -export * from './plugins/screenshot'; -export * from './plugins/securestorage'; -export * from './plugins/serial'; -export * from './plugins/shake'; -export * from './plugins/sim'; -export * from './plugins/sms'; -export * from './plugins/socialsharing'; -export * from './plugins/speech-recognition'; -export * from './plugins/spinnerdialog'; -export * from './plugins/splashscreen'; -export * from './plugins/sqlite'; -export * from './plugins/statusbar'; -export * from './plugins/stepcounter'; -export * from './plugins/streaming-media'; -export * from './plugins/stripe'; -export * from './plugins/text-to-speech'; -export * from './plugins/themeable-browser'; -export * from './plugins/toast'; -export * from './plugins/touchid'; -export * from './plugins/twitter-connect'; -export * from './plugins/unique-device-id'; -export * from './plugins/vibration'; -export * from './plugins/video-editor'; -export * from './plugins/video-player'; -export * from './plugins/webintent'; -export * from './plugins/youtube-video-player'; -export * from './plugins/z-bar'; -export * from './plugins/zip'; - -// Window export to use outside of a module loading system -window['IonicNative'] = { - ActionSheet, - AdMob, - Alipay, - AndroidFingerprintAuth, - AppAvailability, - AppPreferences, - Appodeal, - AppRate, - AppUpdate, - AppVersion, - Badge, - BackgroundGeolocation, - BackgroundFetch, - BackgroundMode, - Backlight, - BarcodeScanner, - Base64ToGallery, - BatteryStatus, - Brightness, - BrowserTab, - BLE, - BluetoothSerial, - Broadcaster, - Calendar, - CallNumber, - Camera, - CameraPreview, - CardIO, - Clipboard, - CodePush, - Contacts, - CouchbaseLite, - Crop, - DatePicker, - DBMeter, - Deeplinks, - Device, - DeviceFeedback, - DeviceAccounts, - DeviceMotion, - DeviceOrientation, - Dialogs, - Diagnostic, - EmailComposer, - EstimoteBeacons, - Facebook, - File, - FileChooser, - FileOpener, - FilePath, - FingerprintAIO, - Flashlight, - Firebase, - Geofence, - Geolocation, - Globalization, - GooglePlus, - GoogleMap, - GoogleAnalytics, - Gyroscope, - HeaderColor, - Health, - Hotspot, - HTTP, - Httpd, - IBeacon, - ImagePicker, - ImageResizer, - InAppBrowser, - InAppPurchase, - Insomnia, - Instagram, - IsDebug, - Keyboard, - LaunchNavigator, - LaunchReview, - LocalNotifications, - LocationAccuracy, - Market, - MediaCapture, - MediaPlugin, - Mixpanel, - MusicControls, - NativeAudio, - NativeGeocoder, - NativePageTransitions, - NativeStorage, - NavigationBar, - Network, - PayPal, - Pedometer, - PhotoLibrary, - NFC, - Printer, - Push, - OneSignal, - PhotoViewer, - ScreenOrientation, - PinDialog, - Pinterest, - PowerManagement, - Rollbar, - SafariViewController, - Screenshot, - SecureStorage, - Serial, - Shake, - Sim, - SMS, - SocialSharing, - SpinnerDialog, - Splashscreen, - SQLite, - StatusBar, - SpeechRecognition, - Stepcounter, - StreamingMedia, - Stripe, - ThreeDeeTouch, - Toast, - TouchID, - Transfer, - TextToSpeech, - ThemeableBrowser, - TwitterConnect, - UniqueDeviceID, - VideoEditor, - VideoPlayer, - Vibration, - WebIntent, - YoutubeVideoPlayer, - ZBar, - Zip -}; - -initAngular1(window['IonicNative']); - -// To help developers using cordova, we listen for the device ready event and -// log an error if it didn't fire in a reasonable amount of time. Generally, -// when this happens, developers should remove and reinstall plugins, since -// an inconsistent plugin is often the culprit. -const before = Date.now(); - -let didFireReady = false; -document.addEventListener('deviceready', () => { - console.log('DEVICE READY FIRED AFTER', (Date.now() - before), 'ms'); - didFireReady = true; -}); - -setTimeout(() => { - if (!didFireReady && window.cordova) { - console.warn(`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); diff --git a/src/ng1.ts b/src/ng1.ts deleted file mode 100644 index 615b3f6ae..000000000 --- a/src/ng1.ts +++ /dev/null @@ -1,26 +0,0 @@ -declare var window; - -/** - * Initialize the ionic.native Angular module if we're running in ng1. - * This iterates through the list of registered plugins and dynamically - * creates Angular 1 services of the form $cordovaSERVICE, ex: $cordovaStatusBar. - */ -export function initAngular1(plugins) { - if (window.angular) { - - const ngModule = window.angular.module('ionic.native', []); - - for (var name in plugins) { - let serviceName = '$cordova' + name; - let cls = plugins[name]; - - (function(serviceName, cls, name) { - ngModule.service(serviceName, [function() { - var funcs = window.angular.copy(cls); - funcs.prototype['name'] = name; - return funcs; - }]); - })(serviceName, cls, name); - } - } -} diff --git a/src/plugins/appodeal.ts b/src/plugins/appodeal.ts deleted file mode 100644 index 2d3933f53..000000000 --- a/src/plugins/appodeal.ts +++ /dev/null @@ -1,443 +0,0 @@ -import { Plugin, Cordova } from './plugin'; -import { Observable } from 'rxjs'; - -/** - * @name Appodeal - * @description - * Plugin to serve ads through native Appodeal SDKs - * - * @usage - * ``` - * import { Appodeal } from 'ionic-native'; - * - * let appKey = ''; - * Appodeal.initialize(appKey, Appodeal.AD_TYPES.REWARDED_VIDEO); - * Appodeal.show(Appodeal.AD_TYPES.REWARDED_VIDEO); - * - * ``` - */ -@Plugin({ - pluginName: 'Appodeal', - plugin: 'https://github.com/appodeal/appodeal-cordova-plugin', - pluginRef: 'Appodeal', - repo: 'https://github.com/appodeal/appodeal-cordova-plugin.git', - platforms: [ 'ios', 'android' ] -}) -export class Appodeal { - // available types of advertisements - static readonly AD_TYPES = { - INTERSTITIAL: 1, - SKIPPABLE_VIDEO: 2, - BANNER: 4, - BANNER_BOTTOM: 8, - BANNER_TOP: 16, - REWARDED_VIDEO: 128, - NON_SKIPPABLE_VIDEO: 256 - }; - - /** - * initialize Appodeal SDK - * @param {string} appKey - * @param {number} adType - */ - @Cordova() - static initialize(appKey: string, adType: number): void {}; - - /** - * check if SDK has been initialized - * @returns {Promise} - */ - @Cordova() - static isInitialized(): Promise { return; }; - - /** - * show ad of specified type - * @param {number} adType - * @returns {Promise} - */ - @Cordova() - static show(adType: number): Promise { return; }; - - /** - * show ad of specified type with placement options - * @param {number} adType - * @param {any} placement - * @returns {Promise} - */ - @Cordova() - static showWithPlacement( - adType: number, - placement: any - ): Promise { return; }; - - /** - * hide ad of specified type - * @param {number} adType - */ - @Cordova() - static hide(adType: number): void {}; - - /** - * confirm use of ads of specified type - * @param {number} adType - */ - @Cordova() - static confirm(adType: number): void {}; - - /** - * check if ad of specified type has been loaded - * @param {number} adType - * @returns {Promise} - */ - @Cordova() - static isLoaded(adType: number): Promise { return; }; - - /** - * check if ad of specified - * @param {number} adType - * @returns {Promise} - */ - @Cordova() - static isPrecache(adType: number): Promise { return; }; - - /** - * - * @param {number} adType - * @param autoCache - */ - @Cordova() - static setAutoCache(adType: number, autoCache: any): void {}; - - /** - * forcefully cache an ad by type - * @param {number} adType - */ - @Cordova() - static cache(adType: number): void {}; - - /** - * - * @param {boolean} set - */ - @Cordova() - static setOnLoadedTriggerBoth(set: boolean): void {}; - - /** - * enable or disable Smart Banners - * @param {boolean} enabled - */ - @Cordova() - static setSmartBanners(enabled: boolean): void {}; - - /** - * enable or disable banner backgrounds - * @param {boolean} enabled - */ - @Cordova() - static setBannerBackground(enabled: boolean): void {}; - - /** - * enable or disable banner animations - * @param {boolean} enabled - */ - @Cordova() - static setBannerAnimation(enabled: boolean): void {}; - - /** - * - * @param value - */ - @Cordova() - static set728x90Banners(value: any): void {}; - - /** - * enable or disable logging - * @param {boolean} logging - */ - @Cordova() - static setLogging(logging: boolean): void {}; - - /** - * enable or disable testing mode - * @param {boolean} testing - */ - @Cordova() - static setTesting(testing: boolean): void {}; - - /** - * reset device ID - */ - @Cordova() - static resetUUID(): void {}; - - /** - * get version of Appdeal SDK - */ - @Cordova() - static getVersion(): Promise { return; }; - - /** - * - * @param {string} network - * @param {number} adType - */ - @Cordova() - static disableNetwork(network?: string, adType?: number): void {}; - - /** - * - * @param {string} network - * @param {number} adType - */ - @Cordova() - static disableNetworkType(network?: string, adType?: number): void {}; - - /** - * disable Location permissions for Appodeal SDK - */ - @Cordova() - static disableLocationPermissionCheck(): void {}; - - /** - * disable Storage permissions for Appodeal SDK - */ - @Cordova() - static disableWriteExternalStoragePermissionCheck(): void {}; - - /** - * enable event listeners - * @param {boolean} enabled - */ - @Cordova() - static enableInterstitialCallbacks(enabled: boolean): void {}; - - /** - * enable event listeners - * @param {boolean} enabled - */ - @Cordova() - static enableSkippableVideoCallbacks(enabled: boolean): void {}; - - /** - * enable event listeners - * @param {boolean} enabled - */ - @Cordova() - static enableNonSkippableVideoCallbacks(enabled: boolean): void {}; - - /** - * enable event listeners - * @param {boolean} enabled - */ - @Cordova() - static enableBannerCallbacks(enabled: boolean): void {}; - - /** - * enable event listeners - * @param {boolean} enabled - */ - @Cordova() - static enableRewardedVideoCallbacks(enabled: boolean): void {}; - - /** - * - * @param {string} name - name of rule - * @param {boolean} value - */ - @Cordova() - static setCustomBooleanRule(name: string, value: boolean): void {}; - - /** - * - * @param {string} name - name of rule - * @param {number} value - */ - @Cordova() - static setCustomIntegerRule(name: string, value: number): void {}; - - /** - * set rule with float value - * @param {string} name - * @param {number} value - */ - @Cordova() - static setCustomDoubleRule(name: string, value: number): void {}; - - /** - * set rule with string value - * @param {string} name - name of rule - * @param {string} value - */ - @Cordova() - static setCustomStringRule(name: string, value: string): void {}; - - /** - * set ID preference in Appodeal for current user - * @param id - */ - @Cordova() - static setUserId(id: any): void {}; - - /** - * set Email preference in Appodeal for current user - * @param email - */ - @Cordova() - static setEmail(email: any): void {}; - - /** - * set Birthday preference in Appodeal for current user - * @param birthday - */ - @Cordova() - static setBirthday(birthday: any): void {}; - - /** - * et Age preference in Appodeal for current user - * @param age - */ - @Cordova() - static setAge(age: any): void {}; - - /** - * set Gender preference in Appodeal for current user - * @param gender - */ - @Cordova() - static setGender(gender: any): void {}; - - /** - * set Occupation preference in Appodeal for current user - * @param occupation - */ - @Cordova() - static setOccupation(occupation: any): void {}; - - /** - * set Relation preference in Appodeal for current user - * @param relation - */ - @Cordova() - static setRelation(relation: any): void {}; - - /** - * set Smoking preference in Appodeal for current user - * @param smoking - */ - @Cordova() - static setSmoking(smoking: any): void {}; - - /** - * set Alcohol preference in Appodeal for current user - * @param alcohol - */ - @Cordova() - static setAlcohol(alcohol: any): void {}; - - /** - * set Interests preference in Appodeal for current user - * @param interests - */ - @Cordova() - static setInterests(interests: any): void {}; - - /********************* - * event Observables * - *********************/ - - static onInterstitialLoaded(): Observable { - return Observable.fromEvent(document, 'onInterstitialLoaded'); - } - - static onInterstitialFailedToLoad(): Observable { - return Observable.fromEvent(document, 'onInterstitialFailedToLoad'); - } - - static onInterstitialShown(): Observable { - return Observable.fromEvent(document, 'onInterstitialShown'); - } - - static onInterstitialClicked(): Observable { - return Observable.fromEvent(document, 'onInterstitialClicked'); - } - - static onInterstitialClosed(): Observable { - return Observable.fromEvent(document, 'onInterstitialClosed'); - } - - static onSkippableVideoLoaded(): Observable { - return Observable.fromEvent(document, 'onSkippableVideoLoaded'); - } - - static onSkippableVideoFailedToLoad(): Observable { - return Observable.fromEvent(document, 'onSkippableVideoFailedToLoad'); - } - - static onSkippableVideoShown(): Observable { - return Observable.fromEvent(document, 'onSkippableVideoShown'); - } - - static onSkippableVideoFinished(): Observable { - return Observable.fromEvent(document, 'onSkippableVideoFinished'); - } - - static onSkippableVideoClosed(): Observable { - return Observable.fromEvent(document, 'onSkippableVideoClosed'); - } - - static onRewardedVideoLoaded(): Observable { - return Observable.fromEvent(document, 'onRewardedVideoLoaded'); - } - - static onRewardedVideoFailedToLoad(): Observable { - return Observable.fromEvent(document, 'onRewardedVideoFailedToLoad'); - } - - static onRewardedVideoShown(): Observable { - return Observable.fromEvent(document, 'onRewardedVideoShown'); - } - - static onRewardedVideoFinished(): Observable { - return Observable.fromEvent(document, 'onRewardedVideoFinished'); - } - - static onRewardedVideoClosed(): Observable { - return Observable.fromEvent(document, 'onRewardedVideoClosed'); - } - - static onNonSkippableVideoLoaded(): Observable { - return Observable.fromEvent(document, 'onNonSkippableVideoLoaded'); - } - - static onNonSkippableVideoFailedToLoad(): Observable { - return Observable.fromEvent(document, 'onNonSkippableVideoFailedToLoad'); - } - - static onNonSkippableVideoShown(): Observable { - return Observable.fromEvent(document, 'onNonSkippableVideoShown'); - } - - static onNonSkippableVideoFinished(): Observable { - return Observable.fromEvent(document, 'onNonSkippableVideoFinished'); - } - - static onNonSkippableVideoClosed(): Observable { - return Observable.fromEvent(document, 'onNonSkippableVideoClosed'); - } - - static onBannerClicked(): Observable { - return Observable.fromEvent(document, 'onBannerClicked'); - } - - static onBannerFailedToLoad(): Observable { - return Observable.fromEvent(document, 'onBannerFailedToLoad'); - } - - static onBannerLoaded(): Observable { - return Observable.fromEvent(document, 'onBannerLoaded'); - } - - static onBannerShown(): Observable { - return Observable.fromEvent(document, 'onBannerShown'); - } -} diff --git a/src/plugins/gyroscope.ts b/src/plugins/gyroscope.ts deleted file mode 100644 index 1203a18fc..000000000 --- a/src/plugins/gyroscope.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { Plugin, Cordova} from './plugin'; -import { Observable } from 'rxjs/Observable'; - -declare var navigator: any; - -/** - * Interface that represent output data - */ -export interface GyroscopeOrientation { - /** - * Represent x-axis - */ - x: number; - - /** - * Represent y-axis - */ - y: number; - - /** - * Represent z-axis - */ - z: number; - - /** - * Represent timestamp of sensor read. Default is 10000ms - */ - timestamp: number; -} - -/** - * Interface that represent option data - */ -export interface GyroscopeOptions { - /** - * Represent how often (in milliseconds) sensor should be read. Default is 10000 ms - */ - frequency: number; -} - -/** - * @name Gyroscope - * @description Read Gyroscope sensor data - * @usage - * ``` - * import { Gyroscope, GyroscopeOrientation, GyroscopeOptions } from 'ionic-native'; - * - * - * let options: GyroscopeOptions = { - * frequency: 1000 - * }; - * - * Gyroscope.getCurrent(options) - * .then((orientation: GyroscopeOrientation) => { - * console.log(orientation.x, orientation.y, orientation.z, orientation.timestamp); - * }) - * .catch() - * - * - * Gyroscope.watch() - * .subscribe((orientation: GyroscopeOrientation) => { - * console.log(orientation.x, orientation.y, orientation.z, orientation.timestamp); - * }); - * - * ``` - */ - @Plugin({ - pluginName: 'Gyroscope', - plugin: 'cordova-plugin-gyroscope', - pluginRef: 'navigator.gyroscope', - repo: 'https://github.com/NeoLSN/cordova-plugin-gyroscope', - platforms: ['Android', 'iOS'] - }) - - export class Gyroscope { - - /** - * Watching for gyroscope sensor changes - * @param options {GyroscopeOptions} (optional) - * @return {Observable} Returns an Observable that resolves GyroscopeOrientation - */ - static watch(options?: GyroscopeOptions): Observable { - return new Observable ( - (observer: any) => { - let watchId = navigator.gyroscope.watch(observer.next.bind(observer), observer.next.bind(observer), options); - return () => navigator.gyroscope.clearWatch(watchId); - } - ); - } - - /** - * Get current data from gyroscope sensor - * @param options {GyroscopeOptions} (optional) - * @return {Promise} Returns a promise that resolves GyroscopeOrientation - */ - @Cordova({ - callbackOrder: 'reverse' - }) - static getCurrent(options?: GyroscopeOptions): Promise { return; } - } diff --git a/src/plugins/location-accuracy.ts b/src/plugins/location-accuracy.ts deleted file mode 100644 index c56a74c96..000000000 --- a/src/plugins/location-accuracy.ts +++ /dev/null @@ -1,68 +0,0 @@ -import {Plugin, Cordova} from './plugin'; -/** - * @name LocationAccuracy - * @description - * This Cordova/Phonegap plugin for Android and iOS to request enabling/changing of Location Services by triggering a native dialog from within the app, avoiding the need for the user to leave your app to change location settings manually. - * - * @usage - * ``` - * import { LocationAccuracy } from 'ionic-native'; - * - * LocationAccuracy.canRequest().then((canRequest: boolean) => { - * - * if(canRequest) { - * // the accuracy option will be ignored by iOS - * LocationAccuracy.request(LocationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).then( - * () => console.log('Request successful'), - * error => console.log('Error requesting location permissions', error) - * ); - * } - * - * }); - * - * ``` - */ -@Plugin({ - pluginName: 'LocationAccuracy', - plugin: 'cordova-plugin-request-location-accuracy', - pluginRef: 'cordova.plugins.locationAccuracy', - repo: 'https://github.com/dpa99c/cordova-plugin-request-location-accuracy' -}) -export class LocationAccuracy { - /** - * Indicates if you can request accurate location - * @returns {Promise} Returns a promise that resovles with a boolean that indicates if you can request accurate location - */ - @Cordova() - static canRequest(): Promise { return; } - - /** - * Indicates if a request is currently in progress - * @returns {Promise} Returns a promise that resolves with a boolean that indicates if a request is currently in progress - */ - @Cordova() - static isRequesting(): Promise { return; } - - /** - * Requests accurate location - * @param accuracy {number} Accuracy, from 0 to 4. You can use the static properties of this class that start with REQUEST_PRIORITY_ - * @returns {Promise} Returns a promise that resolves on success and rejects if an error occurred - */ - @Cordova({ callbackOrder: 'reverse' }) - static request(accuracy: number): Promise { return; } - - static REQUEST_PRIORITY_NO_POWER = 0; - static REQUEST_PRIORITY_LOW_POWER = 1; - static REQUEST_PRIORITY_BALANCED_POWER_ACCURACY = 2; - static REQUEST_PRIORITY_HIGH_ACCURACY = 3; - static SUCCESS_SETTINGS_SATISFIED = 0; - static SUCCESS_USER_AGREED = 1; - static ERROR_ALREADY_REQUESTING = -1; - static ERROR_INVALID_ACTION = 0; - static ERROR_INVALID_ACCURACY = 1; - static ERROR_EXCEPTION = 1; - static ERROR_CANNOT_CHANGE_ACCURACY = 3; - static ERROR_USER_DISAGREED = 4; - static ERROR_GOOGLE_API_CONNECTION_FAILED = 4; - -} diff --git a/src/plugins/plugin.ts b/src/plugins/plugin.ts deleted file mode 100644 index 65f168508..000000000 --- a/src/plugins/plugin.ts +++ /dev/null @@ -1,603 +0,0 @@ -import { get } from '../util'; -import { Observable } from 'rxjs/Observable'; -import 'rxjs/add/observable/fromEvent'; - -declare var window; -declare var Promise; - -/** - * @private - */ -export interface PluginConfig { - /** - * Plugin name, this should match the class name - */ - pluginName: string; - /** - * Plugin NPM package name - */ - plugin: string; - /** - * Plugin object reference - */ - pluginRef: string; - /** - * Github repository URL - */ - repo: string; - /** - * Custom install command - */ - install?: string; - /** - * Supported platforms - */ - platforms?: string[]; -} - -/** - * @private - */ -export interface CordovaOptions { - /** - * Set to true if the wrapped method is a sync function - */ - sync?: boolean; - /** - * Callback order. Set to reverse if the success/error callbacks are the first 2 arguments that the wrapped method takes. - */ - callbackOrder?: 'reverse'; - /** - * Callback style - */ - callbackStyle?: 'node' | 'object'; - /** - * Set a custom index for the success callback function. This doesn't work if callbackOrder or callbackStyle are set. - */ - successIndex?: number; - /** - * Set a custom index for the error callback function. This doesn't work if callbackOrder or callbackStyle are set. - */ - errorIndex?: number; - /** - * Success function property name. This must be set if callbackStyle is set to object. - */ - successName?: string; - /** - * Error function property name. This must be set if callbackStyle is set to object. - */ - errorName?: string; - /** - * Set to true to return an observable - */ - observable?: boolean; - /** - * If observable is set to true, this can be set to a different function name that will cancel the observable. - */ - clearFunction?: string; - /** - * This can be used if clearFunction is set. Set this to true to call the clearFunction with the same arguments used in the initial function. - */ - clearWithArgs?: boolean; - /** - * Creates an observable that wraps a global event. Replaces document.addEventListener - */ - eventObservable?: boolean; - /** - * Event name, this must be set if eventObservable is set to true - */ - event?: string; - /** - * Element to attach the event listener to, this is optional, defaults to `window` - */ - element?: any; - /** - * Set to true if the wrapped method returns a promise - */ - otherPromise?: boolean; - /** - * Supported platforms - */ - platforms?: string[]; -} - -/** - * @private - * @param pluginRef - * @returns {null|*} - */ -export const getPlugin = function(pluginRef: string): any { - return get(window, pluginRef); -}; - -/** - * @private - * @param pluginObj - * @param method - */ -export const pluginWarn = function(pluginObj: any, method?: string) { - let pluginName = pluginObj.pluginName, plugin = pluginObj.plugin; - if (method) { - 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('Install the ' + pluginName + ' plugin: \'ionic plugin add ' + plugin + '\''); -}; - -/** - * @private - * @param pluginName - * @param method - */ -export const cordovaWarn = function(pluginName: string, method: string) { - 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'); - } 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'); - } -}; -function setIndex(args: any[], opts: any = {}, resolve?: Function, reject?: Function): any { - // ignore resolve and reject in case sync - if (opts.sync) { - return args; - } - - // If the plugin method expects myMethod(success, err, options) - if (opts.callbackOrder === 'reverse') { - // Get those arguments in the order [resolve, reject, ...restOfArgs] - args.unshift(reject); - args.unshift(resolve); - } else if (opts.callbackStyle === 'node') { - args.push((err, result) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - } 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') { - const setSuccessIndex = () => { - // If we've specified a success/error index - if (opts.successIndex > args.length) { - args[opts.successIndex] = resolve; - } else { - args.splice(opts.successIndex, 0, resolve); - } - }; - - const setErrorIndex = () => { - // We don't want that the reject cb gets spliced into the position of an optional argument that has not been defined and thus causing non expected behaviour. - if (opts.errorIndex > args.length) { - args[opts.errorIndex] = reject; // insert the reject fn at the correct specific index - } else { - args.splice(opts.errorIndex, 0, reject); // otherwise just splice it into the array - } - }; - - if (opts.successIndex > opts.errorIndex) { - setErrorIndex(); - setSuccessIndex(); - } else { - setSuccessIndex(); - setErrorIndex(); - } - - - } else { - // Otherwise, let's tack them on to the end of the argument list - // which is 90% of cases - args.push(resolve); - args.push(reject); - } - return args; -} - -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); - - let pluginInstance = getPlugin(pluginObj.pluginRef); - - if (!pluginInstance || pluginInstance[methodName] === 'undefined') { - // Do this check in here in the case that the Web API for this plugin is available (for example, Geolocation). - if (!window.cordova) { - cordovaWarn(pluginObj.pluginName, methodName); - return { - error: 'cordova_not_available' - }; - } - - pluginWarn(pluginObj, methodName); - return { - error: 'plugin_not_installed' - }; - } - - return pluginInstance[methodName].apply(pluginInstance, args); -} - -/** - * @private - */ -export function getPromise(cb) { - - const tryNativePromise = () => { - if (window.Promise) { - return new Promise((resolve, reject) => { - cb(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 1/2 or on a recent browser.'); - } - }; - - if (window.angular) { - let injector = window.angular.element(document.querySelector('[ng-app]') || document.body).injector(); - if (injector) { - let $q = injector.get('$q'); - return $q((resolve, reject) => { - cb(resolve, reject); - }); - } else { - console.warn('Angular 1 was detected but $q couldn\'t be retrieved. This is usually when the app is not bootstrapped on the html or body tag. Falling back to native promises which won\'t trigger an automatic digest when promises resolve.'); - return tryNativePromise(); - } - } else { - return tryNativePromise(); - } -} - -function wrapPromise(pluginObj: any, methodName: string, args: any[], opts: any = {}) { - let pluginResult, rej; - const p = getPromise((resolve, reject) => { - pluginResult = callCordovaPlugin(pluginObj, methodName, args, opts, resolve, reject); - rej = reject; - }); - // Angular throws an error on unhandled rejection, but in this case we have already printed - // a warning that Cordova is undefined or the plugin is uninstalled, so there is no reason - // to error - if (pluginResult && pluginResult.error) { - p.catch(() => { }); - rej(pluginResult.error); - } - return p; -} - -function wrapOtherPromise(pluginObj: any, methodName: string, args: any[], opts: any= {}) { - return getPromise((resolve, reject) => { - let pluginResult = callCordovaPlugin(pluginObj, methodName, args, opts); - if (pluginResult && pluginResult.error) { - reject(pluginResult.error); - } - pluginResult.then(resolve).catch(reject); - }); -} - -function wrapObservable(pluginObj: any, methodName: string, args: any[], opts: any = {}) { - return new Observable(observer => { - let pluginResult = callCordovaPlugin(pluginObj, methodName, args, opts, observer.next.bind(observer), observer.error.bind(observer)); - if (pluginResult && pluginResult.error) { - observer.error(pluginResult.error); - } - return () => { - try { - if (opts.clearFunction) { - if (opts.clearWithArgs) { - return callCordovaPlugin(pluginObj, opts.clearFunction, args, opts, observer.next.bind(observer), observer.error.bind(observer)); - } - return get(window, pluginObj.pluginRef)[opts.clearFunction].call(pluginObj, pluginResult); - } - } catch (e) { - console.warn('Unable to clear the previous observable watch for', pluginObj.pluginName, methodName); - console.error(e); - } - }; - }); -} - -function callInstance(pluginObj: any, methodName: string, args: any[], opts: any = {}, resolve?: Function, reject?: Function) { - args = setIndex(args, opts, resolve, reject); - return pluginObj._objectInstance[methodName].apply(pluginObj._objectInstance, args); -} - -function wrapInstance(pluginObj: any, methodName: string, opts: any = {}) { - return (...args) => { - if (opts.sync) { - // Sync doesn't wrap the plugin with a promise or observable, it returns the result as-is - return callInstance(pluginObj, methodName, args, opts); - } else if (opts.observable) { - return new Observable(observer => { - let pluginResult = callInstance(pluginObj, methodName, args, opts, observer.next.bind(observer), observer.error.bind(observer)); - return () => { - try { - if (opts.clearWithArgs) { - return pluginObj._objectInstance[opts.clearFunction].apply(pluginObj._objectInstance, args); - } - return pluginObj._objectInstance[opts.clearFunction].call(pluginObj, pluginResult); - } catch (e) { - console.warn('Unable to clear the previous observable watch for', pluginObj.pluginName, methodName); - console.error(e); - } - }; - }); - } else if (opts.otherPromise) { - return getPromise((resolve, reject) => { - let result = callInstance(pluginObj, methodName, args, opts, resolve, reject); - result.then(resolve, reject); - }); - } else { - return getPromise((resolve, reject) => { - callInstance(pluginObj, methodName, args, opts, resolve, reject); - }); - } - }; -} - -/** - * Wrap the event with an observable - * @param event even name - * @param element The element to attach the event listener to - * @returns {Observable} - */ -function wrapEventObservable(event: string, element: any = window): Observable { - return Observable.fromEvent(element, event); -} - -/** - * Certain plugins expect the user to override methods in the plugin. For example, - * window.cordova.plugins.backgroundMode.onactivate = function() { ... }. - * - * Unfortunately, this is brittle and would be better wrapped as an Observable. overrideFunction - * does just this. - */ -function overrideFunction(pluginObj: any, methodName: string, args: any[], opts: any = {}): Observable { - return new Observable(observer => { - - let pluginInstance = getPlugin(pluginObj.pluginRef); - - if (!pluginInstance) { - // Do this check in here in the case that the Web API for this plugin is available (for example, Geolocation). - if (!window.cordova) { - cordovaWarn(pluginObj.pluginName, methodName); - observer.error({ - error: 'cordova_not_available' - }); - } - - pluginWarn(pluginObj, methodName); - observer.error({ - error: 'plugin_not_installed' - }); - return; - } - - pluginInstance[methodName] = observer.next.bind(observer); - }); -} - - -/** - * @private - * @param pluginObj - * @param methodName - * @param opts - * @returns {function(...[any]): (undefined|*|Observable|*|*)} - */ -export const wrap = function(pluginObj: any, methodName: string, opts: CordovaOptions = {}) { - return (...args) => { - if (opts.sync) { - // Sync doesn't wrap the plugin with a promise or observable, it returns the result as-is - return callCordovaPlugin(pluginObj, methodName, args, opts); - } else if (opts.observable) { - return wrapObservable(pluginObj, methodName, args, opts); - } else if (opts.eventObservable && opts.event) { - return wrapEventObservable(opts.event, opts.element); - } else if (opts.otherPromise) { - return wrapOtherPromise(pluginObj, methodName, args, opts); - } else { - return wrapPromise(pluginObj, methodName, args, opts); - } - }; -}; - - -/** - * @private - * - * Class decorator specifying Plugin metadata. Required for all plugins. - * - * @usage - * ```typescript - * @Plugin({ - * pluginName: 'MyPlugin', - * plugin: 'cordova-plugin-myplugin', - * pluginRef: 'window.myplugin' - * }) - * export class MyPlugin { - * - * // Plugin wrappers, properties, and functions go here ... - * - * } - * ``` - */ -export function Plugin(config: PluginConfig) { - return function(cls) { - - // Add these fields to the class - for (let k in config) { - cls[k] = config[k]; - } - - cls['installed'] = function(printWarning?: boolean) { - return !!getPlugin(config.pluginRef); - }; - - cls['getPlugin'] = function() { - return getPlugin(config.pluginRef); - }; - - cls['checkInstall'] = function() { - let pluginInstance = getPlugin(config.pluginRef); - - if (!pluginInstance) { - pluginWarn(cls); - return false; - } - return true; - }; - - return cls; - }; -} - -/** - * @private - * - * Wrap a stub function in a call to a Cordova plugin, checking if both Cordova - * and the required plugin are installed. - */ -export function Cordova(opts: CordovaOptions = {}) { - return (target: Object, methodName: string, descriptor: TypedPropertyDescriptor) => { - return { - value: function(...args: any[]) { - return wrap(this, methodName, opts).apply(this, args); - } - }; - }; -} - -/** - * @private - * - * Wrap an instance method - */ -export function CordovaInstance(opts: any = {}) { - return (target: Object, methodName: string) => { - return { - value: function(...args: any[]) { - return wrapInstance(this, methodName, opts).apply(this, args); - } - }; - }; -} - -/** - * @private - * - * - * Before calling the original method, ensure Cordova and the plugin are installed. - */ -export function CordovaProperty(target: any, key: string) { - const exists = () => { - let pluginInstance = getPlugin(target.pluginRef); - if (!pluginInstance || typeof pluginInstance[key] === 'undefined') { - pluginWarn(target, key); - return false; - } - return true; - }; - - Object.defineProperty(target, key, { - get: () => { - if (exists()) { - return getPlugin(target.pluginRef)[key]; - } else { - return null; - } - }, - set: (value) => { - if (exists()) { - getPlugin(target.pluginRef)[key] = value; - } - } - }); -} - -/** - * @private - * @param target - * @param key - * @constructor - */ -export function InstanceProperty(target: any, key: string) { - Object.defineProperty(target, key, { - get: function(){ - return this._objectInstance[key]; - }, - set: function(value){ - this._objectInstance[key] = value; - } - }); -} - -/** - * @private - * - * Wrap a stub function in a call to a Cordova plugin, checking if both Cordova - * and the required plugin are installed. - */ -export function CordovaFunctionOverride(opts: any = {}) { - return (target: Object, methodName: string, descriptor: TypedPropertyDescriptor) => { - return { - value: function(...args: any[]) { - return overrideFunction(this, methodName, opts); - } - }; - }; -} - -/** - * @private - */ -export interface CordovaFiniteObservableOptions extends CordovaOptions { - /** - * Function that gets a result returned from plugin's success callback, and decides whether it is last value and observable should complete. - */ - resultFinalPredicate?: (result: any) => boolean; - /** - * Function that gets called after resultFinalPredicate, and removes service data that indicates end of stream from the result. - */ - resultTransform?: (result: any) => any; -} - -/** - * @private - * - * Wraps method that returns an observable that can be completed. Provided opts.resultFinalPredicate dictates when the observable completes. - * - */ -export function CordovaFiniteObservable(opts: CordovaFiniteObservableOptions = {}) { - if (opts.observable === false) { - throw new Error('CordovaFiniteObservable decorator can only be used on methods that returns observable. Please provide correct option.'); - } - opts.observable = true; - return (target: Object, methodName: string, descriptor: TypedPropertyDescriptor) => { - return { - value: function(...args: any[]) { - let wrappedObservable: Observable = wrap(this, methodName, opts).apply(this, args); - return new Observable((observer) => { - let wrappedSubscription = wrappedObservable.subscribe({ - next: (x) => { - observer.next(opts.resultTransform ? opts.resultTransform(x) : x); - if (opts.resultFinalPredicate && opts.resultFinalPredicate(x)) { - observer.complete(); - } - }, - error: (err) => { observer.error(err); }, - complete: () => { observer.complete(); } - }); - return () => { - wrappedSubscription.unsubscribe(); - }; - }); - } - }; - }; -} diff --git a/src/plugins/stripe.ts b/src/plugins/stripe.ts deleted file mode 100644 index 4878b4674..000000000 --- a/src/plugins/stripe.ts +++ /dev/null @@ -1,105 +0,0 @@ -import {Plugin, Cordova} from './plugin'; - -export interface StripeCardTokenParams { - /** - * Card number - */ - number: string; - /** - * Expiry month - */ - expMonth: number; - /** - * Expiry year - */ - expYear: number; - /** - * CVC / CVV - */ - cvc?: string; - /** - * Cardholder name - */ - name?: string; - /** - * Address line 1 - */ - address_line1?: string; - /** - * Address line 2 - */ - address_line2?: string; - /** - * City - */ - address_city?: string; - /** - * State / Province - */ - address_state?: string; - /** - * Country - */ - address_country?: string; - /** - * Postal code / ZIP Code - */ - postal_code?: string; - /** - * 3-letter ISO code for currency - */ - currency?: string; -} - -/** - * @name Stripe - * @description - * A plugin that allows you to use Stripe's Native SDKs for Android and iOS. - * - * @usage - * ``` - * import { Stripe } from 'ionic-native'; - * - * Stripe.setPublishableKey('my_publishable_key'); - * - * let card = { - * number: '4242424242424242', - * expMonth: 12, - * expYear: 2020, - * cvc: '220' - * }; - * - * Stripe.createCardToken(card) - * .then(token => console.log(token)) - * .catch(error => console.error(error)); - * - * ``` - * - * @interfaces - * StripeCardTokenParams - */ -@Plugin({ - pluginName: 'Stripe', - plugin: 'cordova-plugin-stripe', - pluginRef: 'cordova.plugins.stripe', - repo: 'https://github.com/zyramedia/cordova-plugin-stripe' -}) -export class Stripe { - - /** - * Set publishable key - * @param publishableKey {string} Publishable key - * @return {Promise} - */ - @Cordova() - static setPublishableKey(publishableKey: string): Promise { return; } - - /** - * Create Credit Card Token - * @param params {StripeCardTokenParams} Credit card information - * @return {Promise} returns a promise that resolves with the token, or reject with an error - */ - @Cordova() - static createCardToken(params: StripeCardTokenParams): Promise { return; } - -} diff --git a/src/plugins/webintent.ts b/src/plugins/webintent.ts deleted file mode 100644 index 3ffd4fe99..000000000 --- a/src/plugins/webintent.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { Cordova, CordovaProperty, Plugin } from './plugin'; - - -declare var window; - -/** - * @name WebIntent - * @description - * @usage - * For usage information please refer to the plugin's Github repo. - * - * ```typescript - * import {WebIntent} from 'ionic-native'; - * - * WebIntent.startActivity(options).then(onSuccess, onError); - * - * ``` - */ -@Plugin({ - pluginName: 'WebIntent', - plugin: 'https://github.com/Initsogar/cordova-webintent.git', - pluginRef: 'window.plugins.webintent', - repo: 'https://github.com/Initsogar/cordova-webintent.git', - platforms: ['Android'] -}) -export class WebIntent { - - @CordovaProperty - static ACTION_VIEW; - - @CordovaProperty - static EXTRA_TEXT; - - /** - * @param options {Object} { action: any, url: string, type?: string } - * @returns {Promise} - */ - @Cordova() - static startActivity(options: { action: any, url: string, type?: string }): Promise { return; } - - /** - * @param extra {any} - * @returns {Promise} - */ - @Cordova() - static hasExtra(extra: any): Promise { return; } - - /** - * @param extra {any} - * @returns {Promise} - */ - @Cordova() - static getExtra(extra: any): Promise { return; } - - /** - * @returns {Promise} - */ - @Cordova() - static getUri(): Promise { return; }; - - /** - * @returns {Promise} - */ - @Cordova() - static onNewIntent(): Promise { return; }; - - /** - * @param options {Object} { action: string, extras?: { option: boolean } } - * @returns {Promise} - */ - @Cordova() - static sendBroadcast(options: { action: string, extras?: { option: boolean } }): Promise { return; } - -} diff --git a/src/util.ts b/src/util.ts deleted file mode 100644 index 397bce0e2..000000000 --- a/src/util.ts +++ /dev/null @@ -1,7 +0,0 @@ -export function get(obj, path) { - for (var i = 0, path = path.split('.'), len = path.length; i < len; i++) { - if (!obj) { return null; } - obj = obj[path[i]]; - } - return obj; -}; diff --git a/test/plugin.spec.ts b/test/plugin.spec.ts deleted file mode 100644 index ae572df28..000000000 --- a/test/plugin.spec.ts +++ /dev/null @@ -1,174 +0,0 @@ -/// - -import 'es6-shim'; -import {Plugin, Cordova} from './../src/plugins/plugin'; - -declare let window: any; -window.plugins = { - test: {} -}; - -const testPluginMeta = { - pluginName: 'Test', - plugin: 'cordova-plugin-test', - pluginRef: 'plugins.test', - repo: 'https://github.com/apache/cordova-plugin-test', - platforms: ['Android', 'iOS'] -}; - -describe('plugin', () => { - - it('sync method', () => { - - window.plugins.test.syncMethod = () => { - return 'syncResult'; - }; - - @Plugin(testPluginMeta) - class Test { - - @Cordova({ - sync: true - }) - static syncMethod(arg: any): boolean { return; }; - - } - - const spy = spyOn(window.plugins.test, 'syncMethod').and.callThrough(); - const result = Test.syncMethod('foo'); - expect(result).toEqual('syncResult'); - expect(spy).toHaveBeenCalledWith('foo'); - - }); - - it('normal order callback', done => { - - window.plugins.test.normalOrderCallback = (args, success, error) => { - success('normalOrderCallback'); - }; - - @Plugin(testPluginMeta) - class Test { - @Cordova() - static normalOrderCallback(args: any): Promise { return; } - } - - const spy = spyOn(window.plugins.test, 'normalOrderCallback').and.callThrough(); - Test.normalOrderCallback('foo').then(result => { - expect(result).toEqual('normalOrderCallback'); - done(); - }); - expect(spy.calls.mostRecent().args[0]).toEqual('foo'); - - }); - - it('reverse order callback', done => { - - window.plugins.test.reverseOrderCallback = (success, error, args) => { - success('reverseOrderCallback'); - }; - - @Plugin(testPluginMeta) - class Test { - - @Cordova({ - callbackOrder: 'reverse' - }) - static reverseOrderCallback(args: any): Promise { return; } - - } - - const spy = spyOn(window.plugins.test, 'reverseOrderCallback').and.callThrough(); - Test.reverseOrderCallback('foo').then(result => { - expect(result).toEqual('reverseOrderCallback'); - done(); - }); - expect(spy.calls.mostRecent().args[2]).toEqual('foo'); - - }); - - it('node style callback', done => { - - window.plugins.test.nodeStyleCallback = (args, done) => { - done(null, 'nodeStyleCallback'); - }; - - @Plugin(testPluginMeta) - class Test { - - @Cordova({ - callbackStyle: 'node' - }) - static nodeStyleCallback(args: any): Promise { return; } - - } - - const spy = spyOn(window.plugins.test, 'nodeStyleCallback').and.callThrough(); - Test.nodeStyleCallback('foo').then(result => { - expect(result).toEqual('nodeStyleCallback'); - done(); - }); - expect(spy.calls.mostRecent().args[0]).toEqual('foo'); - - }); - - it('object style callback', done => { - - window.plugins.test.objectStyleCallback = (args, {success}) => { - success('objectStyleCallback'); - }; - - @Plugin(testPluginMeta) - class Test { - - @Cordova({ - callbackStyle: 'object', - successName: 'success', - errorName: 'error' - }) - static objectStyleCallback(args: any): Promise { return; } - - } - - const spy = spyOn(window.plugins.test, 'objectStyleCallback').and.callThrough(); - Test.objectStyleCallback('foo').then(result => { - expect(result).toEqual('objectStyleCallback'); - done(); - }); - expect(spy.calls.mostRecent().args[0]).toEqual('foo'); - - }); - - it('reverse callback at the end of the function', done => { - - window.plugins.test.reverseEndCallback = (args, error, success) => { - success('Success'); - }; - - @Plugin(testPluginMeta) - class Test { - - @Cordova({ - successIndex: 2, - errorIndex: 1 - }) - static reverseEndCallback(args: any): Promise { return; } - - } - - const spy = spyOn(window.plugins.test, 'reverseEndCallback').and.callThrough(); - const cb = (result) => { - expect(result).toEqual('Success'); - done(); - }; - - Test.reverseEndCallback('foo').then(cb, cb); - - expect(spy.calls.mostRecent().args[0]).toEqual('foo'); - expect(spy.calls.mostRecent().args[1]).toBeDefined(); - expect(spy.calls.mostRecent().args[2]).toBeDefined(); - expect(spy.calls.mostRecent().args[3]).toBeUndefined(); - - }); - -}); diff --git a/test/plugins/googlemap.spec.ts b/test/plugins/googlemap.spec.ts deleted file mode 100644 index 1718743eb..000000000 --- a/test/plugins/googlemap.spec.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { GoogleMapsLatLngBounds, GoogleMapsLatLng } from '../../src/plugins/googlemap'; - -declare var window: any; - -class LatLngBounds { - public southwest: GoogleMapsLatLng; - public northeast: GoogleMapsLatLng; - - constructor(latLngArray: GoogleMapsLatLng[]) { - this.southwest = latLngArray[0]; - this.northeast = latLngArray[1]; - } -} - -window.plugin = { - google: { - maps: { - LatLngBounds - } - } -}; - -describe('GoogleMapsLatLngBounds', () => { - - const southwest = new GoogleMapsLatLng(1,1); - const northeast = new GoogleMapsLatLng(4,4); - let object; - - it('should create an object', () => { - object = new GoogleMapsLatLngBounds([southwest, northeast]); - expect(object).toBeDefined(); - }); - - it('northwest property should be defined', () => expect(object.northeast).toBeDefined()); - - it('southwest property should be defined', () => expect(object.southwest).toBeDefined()); - - - -}); diff --git a/test/plugins/inappbrowser.spec.ts b/test/plugins/inappbrowser.spec.ts deleted file mode 100644 index 9c7c3eee6..000000000 --- a/test/plugins/inappbrowser.spec.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { InAppBrowser, InAppBrowserEvent, InAppBrowserOptions } from '../../src/plugins/inappbrowser'; - -declare var window: any; - -window.cordova = { - InAppBrowser: { - open: window.open - } -}; - -describe('InAppBrowser', () => { - - const options: InAppBrowserOptions = { hidden: 'yes', hardwareback: 'no' }; - let object; - - it('should create an object using strings and InAppBrowserOptions signature', () => { - object = new InAppBrowser('http://google.com', '_self', options); - expect(object).toBeDefined(); - }); - - it('should create an object using string only signature', () => { - object = new InAppBrowser('http://google.com', '_self', 'location=no'); - expect(object).toBeDefined(); - }); - - it('should create an object with the least amount of parameters', () => { - object = new InAppBrowser('http://google.com'); - expect(object).toBeDefined(); - }); -}); diff --git a/test/plugins/mixpanel.spec.ts b/test/plugins/mixpanel.spec.ts deleted file mode 100644 index 7eb43d0b4..000000000 --- a/test/plugins/mixpanel.spec.ts +++ /dev/null @@ -1,28 +0,0 @@ -import {Mixpanel} from '../../src/plugins/mixpanel'; -declare const window: any; - -window.mixpanel = { - people: { - identify: (args, success, error) => success('Success') - } -}; - -describe('Mixpanel', () => { - - it('should return MixpanelPeople', () => { - expect(Mixpanel.people).toBeDefined(); - expect(Mixpanel.people.identify).toBeDefined(); - }); - - it('should call a method of MixpanelPeople', (done) => { - const spy = spyOn(window.mixpanel.people, 'identify').and.callThrough(); - Mixpanel.people.identify('veryDistinctSuchIdVeryWow') - .then(result => { - expect(result).toEqual('Success'); - done(); - }); - expect(spy.calls.mostRecent().args[0]).toEqual('veryDistinctSuchIdVeryWow'); - expect(window.mixpanel.people.identify).toHaveBeenCalled(); - }); - -}); diff --git a/tsconfig-es5.json b/tsconfig-es5.json deleted file mode 100644 index a4f31bdca..000000000 --- a/tsconfig-es5.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "target": "ES5", - "sourceMap": true, - "declaration": true, - "experimentalDecorators": true, - "outDir": "dist/es5", - "moduleResolution": "node" - }, - "files": [ - "typings/es6-shim/es6-shim.d.ts", - "src/index.ts" - ] -} diff --git a/tsconfig-esm.json b/tsconfig-esm.json deleted file mode 100644 index 7fb860b6c..000000000 --- a/tsconfig-esm.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "compilerOptions": { - "module": "es2015", - "target": "ES5", - "sourceMap": true, - "declaration": true, - "experimentalDecorators": true, - "outDir": "dist/esm", - "moduleResolution": "node" - }, - "files": [ - "typings/es6-shim/es6-shim.d.ts", - "src/index.ts" - ] -} diff --git a/tsconfig.json b/tsconfig.json index be48d5b1b..d5607c05a 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,15 +1,18 @@ { "compilerOptions": { - "module": "commonjs", - "target": "ES5", - "sourceMap": true, + "baseUrl": ".", "declaration": true, + "stripInternal": true, "experimentalDecorators": true, - "outDir": "dist", - "moduleResolution": "node" - }, - "files": [ - "typings/es6-shim/es6-shim.d.ts", - "src/index.ts" - ] + "emitDecoratorMetadata": true, + "module": "es2015", + "moduleResolution": "node", + "paths": { + "@ionic-native/core": ["./dist/packages-dist/@ionic-native/core"] + }, + "rootDir": ".", + "target": "es5", + "skipLibCheck": true, + "lib": ["es2015", "dom"] + } } diff --git a/typings.json b/typings.json deleted file mode 100644 index dbbc9d62f..000000000 --- a/typings.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "globalDevDependencies": { - "jasmine": "registry:dt/jasmine#2.2.0+20160621224255" - } -} diff --git a/typings/es6-shim/es6-shim.d.ts b/typings/es6-shim/es6-shim.d.ts deleted file mode 100644 index 30621b372..000000000 --- a/typings/es6-shim/es6-shim.d.ts +++ /dev/null @@ -1,668 +0,0 @@ -// Type definitions for es6-shim v0.31.2 -// Project: https://github.com/paulmillr/es6-shim -// Definitions by: Ron Buckton -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare type PropertyKey = string | number | symbol; - -interface IteratorResult { - done: boolean; - value?: T; -} - -interface IterableShim { - /** - * Shim for an ES6 iterable. Not intended for direct use by user code. - */ - "_es6-shim iterator_"(): Iterator; -} - -interface Iterator { - next(value?: any): IteratorResult; - return?(value?: any): IteratorResult; - throw?(e?: any): IteratorResult; -} - -interface IterableIteratorShim extends IterableShim, Iterator { - /** - * Shim for an ES6 iterable iterator. Not intended for direct use by user code. - */ - "_es6-shim iterator_"(): IterableIteratorShim; -} - -interface StringConstructor { - /** - * Return the String value whose elements are, in order, the elements in the List elements. - * If length is 0, the empty string is returned. - */ - fromCodePoint(...codePoints: number[]): string; - - /** - * String.raw is intended for use as a tag function of a Tagged Template String. When called - * as such the first argument will be a well formed template call site object and the rest - * parameter will contain the substitution values. - * @param template A well-formed template string call site representation. - * @param substitutions A set of substitution values. - */ - raw(template: TemplateStringsArray, ...substitutions: any[]): string; -} - -interface String { - /** - * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point - * value of the UTF-16 encoded code point starting at the string element at position pos in - * the String resulting from converting this object to a String. - * If there is no element at that position, the result is undefined. - * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. - */ - codePointAt(pos: number): number; - - /** - * Returns true if searchString appears as a substring of the result of converting this - * object to a String, at one or more positions that are - * greater than or equal to position; otherwise, returns false. - * @param searchString search string - * @param position If position is undefined, 0 is assumed, so as to search all of the String. - */ - includes(searchString: string, position?: number): boolean; - - /** - * Returns true if the sequence of elements of searchString converted to a String is the - * same as the corresponding elements of this object (converted to a String) starting at - * endPosition – length(this). Otherwise returns false. - */ - endsWith(searchString: string, endPosition?: number): boolean; - - /** - * Returns a String value that is made from count copies appended together. If count is 0, - * T is the empty String is returned. - * @param count number of copies to append - */ - repeat(count: number): string; - - /** - * Returns true if the sequence of elements of searchString converted to a String is the - * same as the corresponding elements of this object (converted to a String) starting at - * position. Otherwise returns false. - */ - startsWith(searchString: string, position?: number): boolean; - - /** - * Returns an HTML anchor element and sets the name attribute to the text value - * @param name - */ - anchor(name: string): string; - - /** Returns a HTML element */ - big(): string; - - /** Returns a HTML element */ - blink(): string; - - /** Returns a HTML element */ - bold(): string; - - /** Returns a HTML element */ - fixed(): string - - /** Returns a HTML element and sets the color attribute value */ - fontcolor(color: string): string - - /** Returns a HTML element and sets the size attribute value */ - fontsize(size: number): string; - - /** Returns a HTML element and sets the size attribute value */ - fontsize(size: string): string; - - /** Returns an HTML element */ - italics(): string; - - /** Returns an HTML element and sets the href attribute value */ - link(url: string): string; - - /** Returns a HTML element */ - small(): string; - - /** Returns a HTML element */ - strike(): string; - - /** Returns a HTML element */ - sub(): string; - - /** Returns a HTML element */ - sup(): string; - - /** - * Shim for an ES6 iterable. Not intended for direct use by user code. - */ - "_es6-shim iterator_"(): IterableIteratorShim; -} - -interface ArrayConstructor { - /** - * Creates an array from an array-like object. - * @param arrayLike An array-like object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): Array; - - /** - * Creates an array from an iterable object. - * @param iterable An iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from(iterable: IterableShim, mapfn: (v: T, k: number) => U, thisArg?: any): Array; - - /** - * Creates an array from an array-like object. - * @param arrayLike An array-like object to convert to an array. - */ - from(arrayLike: ArrayLike): Array; - - /** - * Creates an array from an iterable object. - * @param iterable An iterable object to convert to an array. - */ - from(iterable: IterableShim): Array; - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: T[]): Array; -} - -interface Array { - /** - * Returns the value of the first element in the array where predicate is true, and undefined - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, find - * immediately returns that element value. Otherwise, find returns undefined. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - find(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): T; - - /** - * Returns the index of the first element in the array where predicate is true, and undefined - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, find - * immediately returns that element value. Otherwise, find returns undefined. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - findIndex(predicate: (value: T) => boolean, thisArg?: any): number; - - /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: T, start?: number, end?: number): T[]; - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): T[]; - - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIteratorShim<[number, T]>; - - /** - * Returns an list of keys in the array - */ - keys(): IterableIteratorShim; - - /** - * Returns an list of values in the array - */ - values(): IterableIteratorShim; - - /** - * Shim for an ES6 iterable. Not intended for direct use by user code. - */ - "_es6-shim iterator_"(): IterableIteratorShim; -} - -interface NumberConstructor { - /** - * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 - * that is representable as a Number value, which is approximately: - * 2.2204460492503130808472633361816 x 10‍−‍16. - */ - EPSILON: number; - - /** - * Returns true if passed value is finite. - * Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a - * number. Only finite values of the type number, result in true. - * @param number A numeric value. - */ - isFinite(number: number): boolean; - - /** - * Returns true if the value passed is an integer, false otherwise. - * @param number A numeric value. - */ - isInteger(number: number): boolean; - - /** - * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a - * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter - * to a number. Only values of the type number, that are also NaN, result in true. - * @param number A numeric value. - */ - isNaN(number: number): boolean; - - /** - * Returns true if the value passed is a safe integer. - * @param number A numeric value. - */ - isSafeInteger(number: number): boolean; - - /** - * The value of the largest integer n such that n and n + 1 are both exactly representable as - * a Number value. - * The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 − 1. - */ - MAX_SAFE_INTEGER: number; - - /** - * The value of the smallest integer n such that n and n − 1 are both exactly representable as - * a Number value. - * The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)). - */ - MIN_SAFE_INTEGER: number; - - /** - * Converts a string to a floating-point number. - * @param string A string that contains a floating-point number. - */ - parseFloat(string: string): number; - - /** - * Converts A string to an integer. - * @param s A string to convert into a number. - * @param radix A value between 2 and 36 that specifies the base of the number in numString. - * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. - * All other strings are considered decimal. - */ - parseInt(string: string, radix?: number): number; -} - -interface ObjectConstructor { - /** - * Copy the values of all of the enumerable own properties from one or more source objects to a - * target object. Returns the target object. - * @param target The target object to copy to. - * @param sources One or more source objects to copy properties from. - */ - assign(target: any, ...sources: any[]): any; - - /** - * Returns true if the values are the same value, false otherwise. - * @param value1 The first value. - * @param value2 The second value. - */ - is(value1: any, value2: any): boolean; - - /** - * Sets the prototype of a specified object o to object proto or null. Returns the object o. - * @param o The object to change its prototype. - * @param proto The value of the new prototype or null. - * @remarks Requires `__proto__` support. - */ - setPrototypeOf(o: any, proto: any): any; -} - -interface RegExp { - /** - * Returns a string indicating the flags of the regular expression in question. This field is read-only. - * The characters in this string are sequenced and concatenated in the following order: - * - * - "g" for global - * - "i" for ignoreCase - * - "m" for multiline - * - "u" for unicode - * - "y" for sticky - * - * If no flags are set, the value is the empty string. - */ - flags: string; -} - -interface Math { - /** - * Returns the number of leading zero bits in the 32-bit binary representation of a number. - * @param x A numeric expression. - */ - clz32(x: number): number; - - /** - * Returns the result of 32-bit multiplication of two numbers. - * @param x First number - * @param y Second number - */ - imul(x: number, y: number): number; - - /** - * Returns the sign of the x, indicating whether x is positive, negative or zero. - * @param x The numeric expression to test - */ - sign(x: number): number; - - /** - * Returns the base 10 logarithm of a number. - * @param x A numeric expression. - */ - log10(x: number): number; - - /** - * Returns the base 2 logarithm of a number. - * @param x A numeric expression. - */ - log2(x: number): number; - - /** - * Returns the natural logarithm of 1 + x. - * @param x A numeric expression. - */ - log1p(x: number): number; - - /** - * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of - * the natural logarithms). - * @param x A numeric expression. - */ - expm1(x: number): number; - - /** - * Returns the hyperbolic cosine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - cosh(x: number): number; - - /** - * Returns the hyperbolic sine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - sinh(x: number): number; - - /** - * Returns the hyperbolic tangent of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - tanh(x: number): number; - - /** - * Returns the inverse hyperbolic cosine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - acosh(x: number): number; - - /** - * Returns the inverse hyperbolic sine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - asinh(x: number): number; - - /** - * Returns the inverse hyperbolic tangent of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - atanh(x: number): number; - - /** - * Returns the square root of the sum of squares of its arguments. - * @param values Values to compute the square root for. - * If no arguments are passed, the result is +0. - * If there is only one argument, the result is the absolute value. - * If any argument is +Infinity or -Infinity, the result is +Infinity. - * If any argument is NaN, the result is NaN. - * If all arguments are either +0 or −0, the result is +0. - */ - hypot(...values: number[]): number; - - /** - * Returns the integral part of the a numeric expression, x, removing any fractional digits. - * If x is already an integer, the result is x. - * @param x A numeric expression. - */ - trunc(x: number): number; - - /** - * Returns the nearest single precision float representation of a number. - * @param x A numeric expression. - */ - fround(x: number): number; - - /** - * Returns an implementation-dependent approximation to the cube root of number. - * @param x A numeric expression. - */ - cbrt(x: number): number; -} - -interface PromiseLike { - /** - * Attaches callbacks for the resolution and/or rejection of the Promise. - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of which ever callback is executed. - */ - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): PromiseLike; - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): PromiseLike; -} - -/** - * Represents the completion of an asynchronous operation - */ -interface Promise { - /** - * Attaches callbacks for the resolution and/or rejection of the Promise. - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of which ever callback is executed. - */ - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; - - /** - * Attaches a callback for only the rejection of the Promise. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of the callback. - */ - catch(onrejected?: (reason: any) => T | PromiseLike): Promise; - catch(onrejected?: (reason: any) => void): Promise; -} - -interface PromiseConstructor { - /** - * A reference to the prototype. - */ - prototype: Promise; - - /** - * Creates a new Promise. - * @param executor A callback used to initialize the promise. This callback is passed two arguments: - * a resolve callback used resolve the promise with a value or the result of another promise, - * and a reject callback used to reject the promise with a provided reason or error. - */ - new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises - * resolve, or rejected when any Promise is rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - all(values: IterableShim>): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved - * or rejected. - * @param values An array of Promises. - * @returns A new Promise. - */ - race(values: IterableShim>): Promise; - - /** - * Creates a new rejected promise for the provided reason. - * @param reason The reason the promise was rejected. - * @returns A new rejected Promise. - */ - reject(reason: any): Promise; - - /** - * Creates a new rejected promise for the provided reason. - * @param reason The reason the promise was rejected. - * @returns A new rejected Promise. - */ - reject(reason: any): Promise; - - /** - * Creates a new resolved promise for the provided value. - * @param value A promise. - * @returns A promise whose internal state matches the provided promise. - */ - resolve(value: T | PromiseLike): Promise; - - /** - * Creates a new resolved promise . - * @returns A resolved promise. - */ - resolve(): Promise; -} - -declare var Promise: PromiseConstructor; - -interface Map { - clear(): void; - delete(key: K): boolean; - forEach(callbackfn: (value: V, index: K, map: Map) => void, thisArg?: any): void; - get(key: K): V; - has(key: K): boolean; - set(key: K, value?: V): Map; - size: number; - entries(): IterableIteratorShim<[K, V]>; - keys(): IterableIteratorShim; - values(): IterableIteratorShim; -} - -interface MapConstructor { - new (): Map; - new (iterable: IterableShim<[K, V]>): Map; - prototype: Map; -} - -declare var Map: MapConstructor; - -interface Set { - add(value: T): Set; - clear(): void; - delete(value: T): boolean; - forEach(callbackfn: (value: T, index: T, set: Set) => void, thisArg?: any): void; - has(value: T): boolean; - size: number; - entries(): IterableIteratorShim<[T, T]>; - keys(): IterableIteratorShim; - values(): IterableIteratorShim; -} - -interface SetConstructor { - new (): Set; - new (iterable: IterableShim): Set; - prototype: Set; -} - -declare var Set: SetConstructor; - -interface WeakMap { - delete(key: K): boolean; - get(key: K): V; - has(key: K): boolean; - set(key: K, value?: V): WeakMap; -} - -interface WeakMapConstructor { - new (): WeakMap; - new (iterable: IterableShim<[K, V]>): WeakMap; - prototype: WeakMap; -} - -declare var WeakMap: WeakMapConstructor; - -interface WeakSet { - add(value: T): WeakSet; - delete(value: T): boolean; - has(value: T): boolean; -} - -interface WeakSetConstructor { - new (): WeakSet; - new (iterable: IterableShim): WeakSet; - prototype: WeakSet; -} - -declare var WeakSet: WeakSetConstructor; - -declare module Reflect { - function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; - function construct(target: Function, argumentsList: ArrayLike): any; - function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; - function deleteProperty(target: any, propertyKey: PropertyKey): boolean; - function enumerate(target: any): IterableIteratorShim; - function get(target: any, propertyKey: PropertyKey, receiver?: any): any; - function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor; - function getPrototypeOf(target: any): any; - function has(target: any, propertyKey: PropertyKey): boolean; - function isExtensible(target: any): boolean; - function ownKeys(target: any): Array; - function preventExtensions(target: any): boolean; - function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; - function setPrototypeOf(target: any, proto: any): boolean; -} - -declare module "es6-shim" { - var String: StringConstructor; - var Array: ArrayConstructor; - var Number: NumberConstructor; - var Math: Math; - var Object: ObjectConstructor; - var Map: MapConstructor; - var Set: SetConstructor; - var WeakMap: WeakMapConstructor; - var WeakSet: WeakSetConstructor; - var Promise: PromiseConstructor; - module Reflect { - function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; - function construct(target: Function, argumentsList: ArrayLike): any; - function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; - function deleteProperty(target: any, propertyKey: PropertyKey): boolean; - function enumerate(target: any): Iterator; - function get(target: any, propertyKey: PropertyKey, receiver?: any): any; - function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor; - function getPrototypeOf(target: any): any; - function has(target: any, propertyKey: PropertyKey): boolean; - function isExtensible(target: any): boolean; - function ownKeys(target: any): Array; - function preventExtensions(target: any): boolean; - function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; - function setPrototypeOf(target: any, proto: any): boolean; - } -} diff --git a/typings/globals/jasmine/index.d.ts b/typings/globals/jasmine/index.d.ts deleted file mode 100644 index e81f5ace5..000000000 --- a/typings/globals/jasmine/index.d.ts +++ /dev/null @@ -1,502 +0,0 @@ -// Generated by typings -// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/c49913aa9ea419ea46c1c684e488cf2a10303b1a/jasmine/jasmine.d.ts -declare function describe(description: string, specDefinitions: () => void): void; -declare function fdescribe(description: string, specDefinitions: () => void): void; -declare function xdescribe(description: string, specDefinitions: () => void): void; - -declare function it(expectation: string, assertion?: () => void, timeout?: number): void; -declare function it(expectation: string, assertion?: (done: DoneFn) => void, timeout?: number): void; -declare function fit(expectation: string, assertion?: () => void, timeout?: number): void; -declare function fit(expectation: string, assertion?: (done: DoneFn) => void, timeout?: number): void; -declare function xit(expectation: string, assertion?: () => void, timeout?: number): void; -declare function xit(expectation: string, assertion?: (done: DoneFn) => void, timeout?: number): void; - -/** If you call the function pending anywhere in the spec body, no matter the expectations, the spec will be marked pending. */ -declare function pending(reason?: string): void; - -declare function beforeEach(action: () => void, timeout?: number): void; -declare function beforeEach(action: (done: DoneFn) => void, timeout?: number): void; -declare function afterEach(action: () => void, timeout?: number): void; -declare function afterEach(action: (done: DoneFn) => void, timeout?: number): void; - -declare function beforeAll(action: () => void, timeout?: number): void; -declare function beforeAll(action: (done: DoneFn) => void, timeout?: number): void; -declare function afterAll(action: () => void, timeout?: number): void; -declare function afterAll(action: (done: DoneFn) => void, timeout?: number): void; - -declare function expect(spy: Function): jasmine.Matchers; -declare function expect(actual: any): jasmine.Matchers; - -declare function fail(e?: any): void; -/** Action method that should be called when the async work is complete */ -interface DoneFn extends Function { - (): void; - - /** fails the spec and indicates that it has completed. If the message is an Error, Error.message is used */ - fail: (message?: Error|string) => void; -} - -declare function spyOn(object: any, method: string): jasmine.Spy; - -declare function runs(asyncMethod: Function): void; -declare function waitsFor(latchMethod: () => boolean, failureMessage?: string, timeout?: number): void; -declare function waits(timeout?: number): void; - -declare namespace jasmine { - - var clock: () => Clock; - - function any(aclass: any): Any; - function anything(): Any; - function arrayContaining(sample: any[]): ArrayContaining; - function objectContaining(sample: any): ObjectContaining; - function createSpy(name: string, originalFn?: Function): Spy; - function createSpyObj(baseName: string, methodNames: any[]): any; - function createSpyObj(baseName: string, methodNames: any[]): T; - function pp(value: any): string; - function getEnv(): Env; - function addCustomEqualityTester(equalityTester: CustomEqualityTester): void; - function addMatchers(matchers: CustomMatcherFactories): void; - function stringMatching(str: string): Any; - function stringMatching(str: RegExp): Any; - - interface Any { - - new (expectedClass: any): any; - - jasmineMatches(other: any): boolean; - jasmineToString(): string; - } - - // taken from TypeScript lib.core.es6.d.ts, applicable to CustomMatchers.contains() - interface ArrayLike { - length: number; - [n: number]: T; - } - - interface ArrayContaining { - new (sample: any[]): any; - - asymmetricMatch(other: any): boolean; - jasmineToString(): string; - } - - interface ObjectContaining { - new (sample: any): any; - - jasmineMatches(other: any, mismatchKeys: any[], mismatchValues: any[]): boolean; - jasmineToString(): string; - } - - interface Block { - - new (env: Env, func: SpecFunction, spec: Spec): any; - - execute(onComplete: () => void): void; - } - - interface WaitsBlock extends Block { - new (env: Env, timeout: number, spec: Spec): any; - } - - interface WaitsForBlock extends Block { - new (env: Env, timeout: number, latchFunction: SpecFunction, message: string, spec: Spec): any; - } - - interface Clock { - install(): void; - uninstall(): void; - /** Calls to any registered callback are triggered when the clock is ticked forward via the jasmine.clock().tick function, which takes a number of milliseconds. */ - tick(ms: number): void; - mockDate(date?: Date): void; - } - - interface CustomEqualityTester { - (first: any, second: any): boolean; - } - - interface CustomMatcher { - compare(actual: T, expected: T): CustomMatcherResult; - compare(actual: any, expected: any): CustomMatcherResult; - } - - interface CustomMatcherFactory { - (util: MatchersUtil, customEqualityTesters: Array): CustomMatcher; - } - - interface CustomMatcherFactories { - [index: string]: CustomMatcherFactory; - } - - interface CustomMatcherResult { - pass: boolean; - message?: string; - } - - interface MatchersUtil { - equals(a: any, b: any, customTesters?: Array): boolean; - contains(haystack: ArrayLike | string, needle: any, customTesters?: Array): boolean; - buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: Array): string; - } - - interface Env { - setTimeout: any; - clearTimeout: void; - setInterval: any; - clearInterval: void; - updateInterval: number; - - currentSpec: Spec; - - matchersClass: Matchers; - - version(): any; - versionString(): string; - nextSpecId(): number; - addReporter(reporter: Reporter): void; - execute(): void; - describe(description: string, specDefinitions: () => void): Suite; - // ddescribe(description: string, specDefinitions: () => void): Suite; Not a part of jasmine. Angular team adds these - beforeEach(beforeEachFunction: () => void): void; - beforeAll(beforeAllFunction: () => void): void; - currentRunner(): Runner; - afterEach(afterEachFunction: () => void): void; - afterAll(afterAllFunction: () => void): void; - xdescribe(desc: string, specDefinitions: () => void): XSuite; - it(description: string, func: () => void): Spec; - // iit(description: string, func: () => void): Spec; Not a part of jasmine. Angular team adds these - xit(desc: string, func: () => void): XSpec; - compareRegExps_(a: RegExp, b: RegExp, mismatchKeys: string[], mismatchValues: string[]): boolean; - compareObjects_(a: any, b: any, mismatchKeys: string[], mismatchValues: string[]): boolean; - equals_(a: any, b: any, mismatchKeys: string[], mismatchValues: string[]): boolean; - contains_(haystack: any, needle: any): boolean; - addCustomEqualityTester(equalityTester: CustomEqualityTester): void; - addMatchers(matchers: CustomMatcherFactories): void; - specFilter(spec: Spec): boolean; - throwOnExpectationFailure(value: boolean): void; - } - - interface FakeTimer { - - new (): any; - - reset(): void; - tick(millis: number): void; - runFunctionsWithinRange(oldMillis: number, nowMillis: number): void; - scheduleFunction(timeoutKey: any, funcToCall: () => void, millis: number, recurring: boolean): void; - } - - interface HtmlReporter { - new (): any; - } - - interface HtmlSpecFilter { - new (): any; - } - - interface Result { - type: string; - } - - interface NestedResults extends Result { - description: string; - - totalCount: number; - passedCount: number; - failedCount: number; - - skipped: boolean; - - rollupCounts(result: NestedResults): void; - log(values: any): void; - getItems(): Result[]; - addResult(result: Result): void; - passed(): boolean; - } - - interface MessageResult extends Result { - values: any; - trace: Trace; - } - - interface ExpectationResult extends Result { - matcherName: string; - passed(): boolean; - expected: any; - actual: any; - message: string; - trace: Trace; - } - - interface Trace { - name: string; - message: string; - stack: any; - } - - interface PrettyPrinter { - - new (): any; - - format(value: any): void; - iterateObject(obj: any, fn: (property: string, isGetter: boolean) => void): void; - emitScalar(value: any): void; - emitString(value: string): void; - emitArray(array: any[]): void; - emitObject(obj: any): void; - append(value: any): void; - } - - interface StringPrettyPrinter extends PrettyPrinter { - } - - interface Queue { - - new (env: any): any; - - env: Env; - ensured: boolean[]; - blocks: Block[]; - running: boolean; - index: number; - offset: number; - abort: boolean; - - addBefore(block: Block, ensure?: boolean): void; - add(block: any, ensure?: boolean): void; - insertNext(block: any, ensure?: boolean): void; - start(onComplete?: () => void): void; - isRunning(): boolean; - next_(): void; - results(): NestedResults; - } - - interface Matchers { - - new (env: Env, actual: any, spec: Env, isNot?: boolean): any; - - env: Env; - actual: any; - spec: Env; - isNot?: boolean; - message(): any; - - toBe(expected: any, expectationFailOutput?: any): boolean; - toEqual(expected: any, expectationFailOutput?: any): boolean; - toMatch(expected: string | RegExp, expectationFailOutput?: any): boolean; - toBeDefined(expectationFailOutput?: any): boolean; - toBeUndefined(expectationFailOutput?: any): boolean; - toBeNull(expectationFailOutput?: any): boolean; - toBeNaN(): boolean; - toBeTruthy(expectationFailOutput?: any): boolean; - toBeFalsy(expectationFailOutput?: any): boolean; - toHaveBeenCalled(): boolean; - toHaveBeenCalledWith(...params: any[]): boolean; - toHaveBeenCalledTimes(expected: number): boolean; - toContain(expected: any, expectationFailOutput?: any): boolean; - toBeLessThan(expected: number, expectationFailOutput?: any): boolean; - toBeGreaterThan(expected: number, expectationFailOutput?: any): boolean; - toBeCloseTo(expected: number, precision?: any, expectationFailOutput?: any): boolean; - toThrow(expected?: any): boolean; - toThrowError(message?: string | RegExp): boolean; - toThrowError(expected?: new (...args: any[]) => Error, message?: string | RegExp): boolean; - not: Matchers; - - Any: Any; - } - - interface Reporter { - reportRunnerStarting(runner: Runner): void; - reportRunnerResults(runner: Runner): void; - reportSuiteResults(suite: Suite): void; - reportSpecStarting(spec: Spec): void; - reportSpecResults(spec: Spec): void; - log(str: string): void; - } - - interface MultiReporter extends Reporter { - addReporter(reporter: Reporter): void; - } - - interface Runner { - - new (env: Env): any; - - execute(): void; - beforeEach(beforeEachFunction: SpecFunction): void; - afterEach(afterEachFunction: SpecFunction): void; - beforeAll(beforeAllFunction: SpecFunction): void; - afterAll(afterAllFunction: SpecFunction): void; - finishCallback(): void; - addSuite(suite: Suite): void; - add(block: Block): void; - specs(): Spec[]; - suites(): Suite[]; - topLevelSuites(): Suite[]; - results(): NestedResults; - } - - interface SpecFunction { - (spec?: Spec): void; - } - - interface SuiteOrSpec { - id: number; - env: Env; - description: string; - queue: Queue; - } - - interface Spec extends SuiteOrSpec { - - new (env: Env, suite: Suite, description: string): any; - - suite: Suite; - - afterCallbacks: SpecFunction[]; - spies_: Spy[]; - - results_: NestedResults; - matchersClass: Matchers; - - getFullName(): string; - results(): NestedResults; - log(arguments: any): any; - runs(func: SpecFunction): Spec; - addToQueue(block: Block): void; - addMatcherResult(result: Result): void; - expect(actual: any): any; - waits(timeout: number): Spec; - waitsFor(latchFunction: SpecFunction, timeoutMessage?: string, timeout?: number): Spec; - fail(e?: any): void; - getMatchersClass_(): Matchers; - addMatchers(matchersPrototype: CustomMatcherFactories): void; - finishCallback(): void; - finish(onComplete?: () => void): void; - after(doAfter: SpecFunction): void; - execute(onComplete?: () => void): any; - addBeforesAndAftersToQueue(): void; - explodes(): void; - spyOn(obj: any, methodName: string, ignoreMethodDoesntExist: boolean): Spy; - removeAllSpies(): void; - } - - interface XSpec { - id: number; - runs(): void; - } - - interface Suite extends SuiteOrSpec { - - new (env: Env, description: string, specDefinitions: () => void, parentSuite: Suite): any; - - parentSuite: Suite; - - getFullName(): string; - finish(onComplete?: () => void): void; - beforeEach(beforeEachFunction: SpecFunction): void; - afterEach(afterEachFunction: SpecFunction): void; - beforeAll(beforeAllFunction: SpecFunction): void; - afterAll(afterAllFunction: SpecFunction): void; - results(): NestedResults; - add(suiteOrSpec: SuiteOrSpec): void; - specs(): Spec[]; - suites(): Suite[]; - children(): any[]; - execute(onComplete?: () => void): void; - } - - interface XSuite { - execute(): void; - } - - interface Spy { - (...params: any[]): any; - - identity: string; - and: SpyAnd; - calls: Calls; - mostRecentCall: { args: any[]; }; - argsForCall: any[]; - wasCalled: boolean; - } - - interface SpyAnd { - /** By chaining the spy with and.callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation. */ - callThrough(): Spy; - /** By chaining the spy with and.returnValue, all calls to the function will return a specific value. */ - returnValue(val: any): Spy; - /** By chaining the spy with and.returnValues, all calls to the function will return specific values in order until it reaches the end of the return values list. */ - returnValues(...values: any[]): Spy; - /** By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied function. */ - callFake(fn: Function): Spy; - /** By chaining the spy with and.throwError, all calls to the spy will throw the specified value. */ - throwError(msg: string): Spy; - /** When a calling strategy is used for a spy, the original stubbing behavior can be returned at any time with and.stub. */ - stub(): Spy; - } - - interface Calls { - /** By chaining the spy with calls.any(), will return false if the spy has not been called at all, and then true once at least one call happens. **/ - any(): boolean; - /** By chaining the spy with calls.count(), will return the number of times the spy was called **/ - count(): number; - /** By chaining the spy with calls.argsFor(), will return the arguments passed to call number index **/ - argsFor(index: number): any[]; - /** By chaining the spy with calls.allArgs(), will return the arguments to all calls **/ - allArgs(): any[]; - /** By chaining the spy with calls.all(), will return the context (the this) and arguments passed all calls **/ - all(): CallInfo[]; - /** By chaining the spy with calls.mostRecent(), will return the context (the this) and arguments for the most recent call **/ - mostRecent(): CallInfo; - /** By chaining the spy with calls.first(), will return the context (the this) and arguments for the first call **/ - first(): CallInfo; - /** By chaining the spy with calls.reset(), will clears all tracking for a spy **/ - reset(): void; - } - - interface CallInfo { - /** The context (the this) for the call */ - object: any; - /** All arguments passed to the call */ - args: any[]; - /** The return value of the call */ - returnValue: any; - } - - interface Util { - inherit(childClass: Function, parentClass: Function): any; - formatException(e: any): any; - htmlEscape(str: string): string; - argsToArray(args: any): any; - extend(destination: any, source: any): any; - } - - interface JsApiReporter extends Reporter { - - started: boolean; - finished: boolean; - result: any; - messages: any; - - new (): any; - - suites(): Suite[]; - summarize_(suiteOrSpec: SuiteOrSpec): any; - results(): any; - resultsForSpec(specId: any): any; - log(str: any): any; - resultsForSpecs(specIds: any): any; - summarizeResult_(result: any): any; - } - - interface Jasmine { - Spec: Spec; - clock: Clock; - util: Util; - } - - export var HtmlReporter: HtmlReporter; - export var HtmlSpecFilter: HtmlSpecFilter; - export var DEFAULT_TIMEOUT_INTERVAL: number; -} \ No newline at end of file diff --git a/typings/globals/jasmine/typings.json b/typings/globals/jasmine/typings.json deleted file mode 100644 index 3fb336cf1..000000000 --- a/typings/globals/jasmine/typings.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "resolution": "main", - "tree": { - "src": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/c49913aa9ea419ea46c1c684e488cf2a10303b1a/jasmine/jasmine.d.ts", - "raw": "registry:dt/jasmine#2.2.0+20160621224255", - "typings": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/c49913aa9ea419ea46c1c684e488cf2a10303b1a/jasmine/jasmine.d.ts" - } -} diff --git a/typings/index.d.ts b/typings/index.d.ts deleted file mode 100644 index 7cf8a3f75..000000000 --- a/typings/index.d.ts +++ /dev/null @@ -1 +0,0 @@ -///