chore: default tabs

This commit is contained in:
Nathan Walker
2020-07-09 23:46:02 -07:00
parent 8100cf7089
commit 41f0573d8e
353 changed files with 55344 additions and 55344 deletions

View File

@@ -2,7 +2,7 @@
// apply polyfills first
import { initGlobal } from '../globals';
if (!(<any>global).hasInitGlobal) {
initGlobal();
initGlobal();
}
// Types
@@ -23,22 +23,22 @@ export * from './application-interfaces';
const events = new Observable();
let launched = false;
function setLaunched() {
launched = true;
events.off('launch', setLaunched);
launched = true;
events.off('launch', setLaunched);
}
events.on('launch', setLaunched);
if (profilingLevel() > 0) {
events.on('displayed', () => {
const duration = uptime();
const end = time();
const start = end - duration;
profilingTrace(`Displayed in ${duration.toFixed(2)}ms`, start, end);
});
events.on('displayed', () => {
const duration = uptime();
const end = time();
const start = end - duration;
profilingTrace(`Displayed in ${duration.toFixed(2)}ms`, start, end);
});
}
export function hasLaunched(): boolean {
return launched;
return launched;
}
export const launchEvent = 'launch';
@@ -59,11 +59,11 @@ const SYSTEM_APPEARANCE_CSS_CLASSES = [`${CLASS_PREFIX}${SystemAppearance.light}
let cssFile: string = './app.css';
export function getResources() {
return bindableResources.get();
return bindableResources.get();
}
export function setResources(res: any) {
bindableResources.set(res);
bindableResources.set(res);
}
export let android: AndroidApplication = undefined;
@@ -76,124 +76,124 @@ export const hasListeners: typeof events.hasListeners = events.hasListeners.bind
let app: iOSApplication | AndroidApplication;
export function setApplication(instance: iOSApplication | AndroidApplication): void {
app = instance;
app = instance;
}
export function livesync(rootView: View, context?: ModuleContext) {
events.notify(<EventData>{ eventName: 'livesync', object: app });
const liveSyncCore = global.__onLiveSyncCore;
let reapplyAppStyles = false;
events.notify(<EventData>{ eventName: 'livesync', object: app });
const liveSyncCore = global.__onLiveSyncCore;
let reapplyAppStyles = false;
// ModuleContext is available only for Hot Module Replacement
if (context && context.path) {
const styleExtensions = ['css', 'scss'];
const appStylesFullFileName = getCssFileName();
const appStylesFileName = appStylesFullFileName.substring(0, appStylesFullFileName.lastIndexOf('.') + 1);
reapplyAppStyles = styleExtensions.some((ext) => context.path === appStylesFileName.concat(ext));
}
// ModuleContext is available only for Hot Module Replacement
if (context && context.path) {
const styleExtensions = ['css', 'scss'];
const appStylesFullFileName = getCssFileName();
const appStylesFileName = appStylesFullFileName.substring(0, appStylesFullFileName.lastIndexOf('.') + 1);
reapplyAppStyles = styleExtensions.some((ext) => context.path === appStylesFileName.concat(ext));
}
// Handle application styles
if (rootView && reapplyAppStyles) {
rootView._onCssStateChange();
} else if (liveSyncCore) {
liveSyncCore(context);
}
// Handle application styles
if (rootView && reapplyAppStyles) {
rootView._onCssStateChange();
} else if (liveSyncCore) {
liveSyncCore(context);
}
}
export function setCssFileName(cssFileName: string) {
cssFile = cssFileName;
events.notify(<CssChangedEventData>{
eventName: 'cssChanged',
object: app,
cssFile: cssFileName,
});
cssFile = cssFileName;
events.notify(<CssChangedEventData>{
eventName: 'cssChanged',
object: app,
cssFile: cssFileName,
});
}
export function getCssFileName(): string {
return cssFile;
return cssFile;
}
export function loadAppCss(): void {
try {
events.notify(<LoadAppCSSEventData>{
eventName: 'loadAppCss',
object: app,
cssFile: getCssFileName(),
});
} catch (e) {
throw new Error(`The app CSS file ${getCssFileName()} couldn't be loaded!`);
}
try {
events.notify(<LoadAppCSSEventData>{
eventName: 'loadAppCss',
object: app,
cssFile: getCssFileName(),
});
} catch (e) {
throw new Error(`The app CSS file ${getCssFileName()} couldn't be loaded!`);
}
}
function addCssClass(rootView: View, cssClass: string) {
pushToSystemCssClasses(cssClass);
rootView.cssClasses.add(cssClass);
pushToSystemCssClasses(cssClass);
rootView.cssClasses.add(cssClass);
}
function removeCssClass(rootView: View, cssClass: string) {
removeSystemCssClass(cssClass);
rootView.cssClasses.delete(cssClass);
removeSystemCssClass(cssClass);
rootView.cssClasses.delete(cssClass);
}
function increaseStyleScopeApplicationCssSelectorVersion(rootView: View) {
const styleScope = rootView._styleScope || ((<any>rootView).currentPage && (<any>rootView).currentPage._styleScope);
const styleScope = rootView._styleScope || ((<any>rootView).currentPage && (<any>rootView).currentPage._styleScope);
if (styleScope) {
styleScope._increaseApplicationCssSelectorVersion();
}
if (styleScope) {
styleScope._increaseApplicationCssSelectorVersion();
}
}
function applyCssClass(rootView: View, cssClasses: string[], newCssClass: string) {
if (!rootView.cssClasses.has(newCssClass)) {
cssClasses.forEach((cssClass) => removeCssClass(rootView, cssClass));
addCssClass(rootView, newCssClass);
increaseStyleScopeApplicationCssSelectorVersion(rootView);
rootView._onCssStateChange();
}
if (!rootView.cssClasses.has(newCssClass)) {
cssClasses.forEach((cssClass) => removeCssClass(rootView, cssClass));
addCssClass(rootView, newCssClass);
increaseStyleScopeApplicationCssSelectorVersion(rootView);
rootView._onCssStateChange();
}
}
export function orientationChanged(rootView: View, newOrientation: 'portrait' | 'landscape' | 'unknown'): void {
if (!rootView) {
return;
}
if (!rootView) {
return;
}
const newOrientationCssClass = `${CLASS_PREFIX}${newOrientation}`;
applyCssClass(rootView, ORIENTATION_CSS_CLASSES, newOrientationCssClass);
const newOrientationCssClass = `${CLASS_PREFIX}${newOrientation}`;
applyCssClass(rootView, ORIENTATION_CSS_CLASSES, newOrientationCssClass);
const rootModalViews = <Array<View>>rootView._getRootModalViews();
rootModalViews.forEach((rootModalView) => {
applyCssClass(rootModalView, ORIENTATION_CSS_CLASSES, newOrientationCssClass);
});
const rootModalViews = <Array<View>>rootView._getRootModalViews();
rootModalViews.forEach((rootModalView) => {
applyCssClass(rootModalView, ORIENTATION_CSS_CLASSES, newOrientationCssClass);
});
}
export function systemAppearanceChanged(rootView: View, newSystemAppearance: 'dark' | 'light'): void {
if (!rootView) {
return;
}
if (!rootView) {
return;
}
const newSystemAppearanceCssClass = `${CLASS_PREFIX}${newSystemAppearance}`;
applyCssClass(rootView, SYSTEM_APPEARANCE_CSS_CLASSES, newSystemAppearanceCssClass);
const newSystemAppearanceCssClass = `${CLASS_PREFIX}${newSystemAppearance}`;
applyCssClass(rootView, SYSTEM_APPEARANCE_CSS_CLASSES, newSystemAppearanceCssClass);
const rootModalViews = <Array<View>>rootView._getRootModalViews();
rootModalViews.forEach((rootModalView) => {
applyCssClass(rootModalView, SYSTEM_APPEARANCE_CSS_CLASSES, newSystemAppearanceCssClass);
});
const rootModalViews = <Array<View>>rootView._getRootModalViews();
rootModalViews.forEach((rootModalView) => {
applyCssClass(rootModalView, SYSTEM_APPEARANCE_CSS_CLASSES, newSystemAppearanceCssClass);
});
}
global.__onUncaughtError = function (error: NativeScriptError) {
events.notify(<UnhandledErrorEventData>{
eventName: uncaughtErrorEvent,
object: app,
android: error,
ios: error,
error: error,
});
events.notify(<UnhandledErrorEventData>{
eventName: uncaughtErrorEvent,
object: app,
android: error,
ios: error,
error: error,
});
};
global.__onDiscardedError = function (error: NativeScriptError) {
events.notify(<DiscardedErrorEventData>{
eventName: discardedErrorEvent,
object: app,
error: error,
});
events.notify(<DiscardedErrorEventData>{
eventName: discardedErrorEvent,
object: app,
error: error,
});
};

View File

@@ -6,84 +6,84 @@ import { View } from '../ui/core/view';
* An extended JavaScript Error which will have the nativeError property initialized in case the error is caused by executing platform-specific code.
*/
export interface NativeScriptError extends Error {
/**
* Represents the native error object.
*/
nativeError: any;
/**
* Represents the native error object.
*/
nativeError: any;
}
export interface ApplicationEventData extends EventData {
ios?: any;
android?: any;
eventName: string;
object: any;
ios?: any;
android?: any;
eventName: string;
object: any;
}
export interface LaunchEventData extends ApplicationEventData {
root?: View;
savedInstanceState?: any /* android.os.Bundle */;
root?: View;
savedInstanceState?: any /* android.os.Bundle */;
}
export interface OrientationChangedEventData extends ApplicationEventData {
newValue: 'portrait' | 'landscape' | 'unknown';
newValue: 'portrait' | 'landscape' | 'unknown';
}
export interface SystemAppearanceChangedEventData extends ApplicationEventData {
newValue: 'light' | 'dark';
newValue: 'light' | 'dark';
}
export interface UnhandledErrorEventData extends ApplicationEventData {
ios?: NativeScriptError;
android?: NativeScriptError;
error: NativeScriptError;
ios?: NativeScriptError;
android?: NativeScriptError;
error: NativeScriptError;
}
export interface DiscardedErrorEventData extends ApplicationEventData {
error: NativeScriptError;
error: NativeScriptError;
}
export interface CssChangedEventData extends EventData {
cssFile?: string;
cssText?: string;
cssFile?: string;
cssText?: string;
}
export interface AndroidActivityEventData {
activity: any /* androidx.appcompat.app.AppCompatActivity */;
eventName: string;
object: any;
activity: any /* androidx.appcompat.app.AppCompatActivity */;
eventName: string;
object: any;
}
export interface AndroidActivityBundleEventData extends AndroidActivityEventData {
bundle: any /* android.os.Bundle */;
bundle: any /* android.os.Bundle */;
}
export interface AndroidActivityRequestPermissionsEventData extends AndroidActivityEventData {
requestCode: number;
permissions: Array<string>;
grantResults: Array<number>;
requestCode: number;
permissions: Array<string>;
grantResults: Array<number>;
}
export interface AndroidActivityResultEventData extends AndroidActivityEventData {
requestCode: number;
resultCode: number;
intent: any /* android.content.Intent */;
requestCode: number;
resultCode: number;
intent: any /* android.content.Intent */;
}
export interface AndroidActivityNewIntentEventData extends AndroidActivityEventData {
intent: any /* android.content.Intent */;
intent: any /* android.content.Intent */;
}
export interface AndroidActivityBackPressedEventData extends AndroidActivityEventData {
cancel: boolean;
cancel: boolean;
}
/**
* @deprecated
*/
export interface RootViewControllerImpl {
contentController: any;
contentController: any;
}
export interface LoadAppCSSEventData extends EventData {
cssFile: string;
cssFile: string;
}

View File

@@ -25,112 +25,112 @@ const ActivityNewIntent = 'activityNewIntent';
const ActivityRequestPermissions = 'activityRequestPermissions';
export class AndroidApplication extends Observable implements AndroidApplicationDefinition {
public static activityCreatedEvent = ActivityCreated;
public static activityDestroyedEvent = ActivityDestroyed;
public static activityStartedEvent = ActivityStarted;
public static activityPausedEvent = ActivityPaused;
public static activityResumedEvent = ActivityResumed;
public static activityStoppedEvent = ActivityStopped;
public static saveActivityStateEvent = SaveActivityState;
public static activityResultEvent = ActivityResult;
public static activityBackPressedEvent = ActivityBackPressed;
public static activityNewIntentEvent = ActivityNewIntent;
public static activityRequestPermissionsEvent = ActivityRequestPermissions;
public static activityCreatedEvent = ActivityCreated;
public static activityDestroyedEvent = ActivityDestroyed;
public static activityStartedEvent = ActivityStarted;
public static activityPausedEvent = ActivityPaused;
public static activityResumedEvent = ActivityResumed;
public static activityStoppedEvent = ActivityStopped;
public static saveActivityStateEvent = SaveActivityState;
public static activityResultEvent = ActivityResult;
public static activityBackPressedEvent = ActivityBackPressed;
public static activityNewIntentEvent = ActivityNewIntent;
public static activityRequestPermissionsEvent = ActivityRequestPermissions;
private _orientation: 'portrait' | 'landscape' | 'unknown';
private _systemAppearance: 'light' | 'dark';
public paused: boolean;
public nativeApp: android.app.Application;
public context: android.content.Context;
public foregroundActivity: androidx.appcompat.app.AppCompatActivity;
public startActivity: androidx.appcompat.app.AppCompatActivity;
public packageName: string;
// we are using these property to store the callbacks to avoid early GC collection which would trigger MarkReachableObjects
private callbacks: any = {};
private _orientation: 'portrait' | 'landscape' | 'unknown';
private _systemAppearance: 'light' | 'dark';
public paused: boolean;
public nativeApp: android.app.Application;
public context: android.content.Context;
public foregroundActivity: androidx.appcompat.app.AppCompatActivity;
public startActivity: androidx.appcompat.app.AppCompatActivity;
public packageName: string;
// we are using these property to store the callbacks to avoid early GC collection which would trigger MarkReachableObjects
private callbacks: any = {};
public init(nativeApp: android.app.Application) {
if (this.nativeApp === nativeApp) {
return;
}
public init(nativeApp: android.app.Application) {
if (this.nativeApp === nativeApp) {
return;
}
if (this.nativeApp) {
throw new Error('application.android already initialized.');
}
if (this.nativeApp) {
throw new Error('application.android already initialized.');
}
this.nativeApp = nativeApp;
this.packageName = nativeApp.getPackageName();
this.context = nativeApp.getApplicationContext();
this.nativeApp = nativeApp;
this.packageName = nativeApp.getPackageName();
this.context = nativeApp.getApplicationContext();
// we store those callbacks and add a function for clearing them later so that the objects will be eligable for GC
this.callbacks.lifecycleCallbacks = initLifecycleCallbacks();
this.callbacks.componentCallbacks = initComponentCallbacks();
this.nativeApp.registerActivityLifecycleCallbacks(this.callbacks.lifecycleCallbacks);
this.nativeApp.registerComponentCallbacks(this.callbacks.componentCallbacks);
// we store those callbacks and add a function for clearing them later so that the objects will be eligable for GC
this.callbacks.lifecycleCallbacks = initLifecycleCallbacks();
this.callbacks.componentCallbacks = initComponentCallbacks();
this.nativeApp.registerActivityLifecycleCallbacks(this.callbacks.lifecycleCallbacks);
this.nativeApp.registerComponentCallbacks(this.callbacks.componentCallbacks);
this._registerPendingReceivers();
}
this._registerPendingReceivers();
}
private _registeredReceivers = {};
private _pendingReceiverRegistrations = new Array<(context: android.content.Context) => void>();
private _registerPendingReceivers() {
this._pendingReceiverRegistrations.forEach((func) => func(this.context));
this._pendingReceiverRegistrations.length = 0;
}
private _registeredReceivers = {};
private _pendingReceiverRegistrations = new Array<(context: android.content.Context) => void>();
private _registerPendingReceivers() {
this._pendingReceiverRegistrations.forEach((func) => func(this.context));
this._pendingReceiverRegistrations.length = 0;
}
get orientation(): 'portrait' | 'landscape' | 'unknown' {
if (!this._orientation) {
const resources = this.context.getResources();
const configuration = <android.content.res.Configuration>resources.getConfiguration();
get orientation(): 'portrait' | 'landscape' | 'unknown' {
if (!this._orientation) {
const resources = this.context.getResources();
const configuration = <android.content.res.Configuration>resources.getConfiguration();
this._orientation = getOrientationValue(configuration);
}
this._orientation = getOrientationValue(configuration);
}
return this._orientation;
}
return this._orientation;
}
set orientation(value: 'portrait' | 'landscape' | 'unknown') {
this._orientation = value;
}
set orientation(value: 'portrait' | 'landscape' | 'unknown') {
this._orientation = value;
}
get systemAppearance(): 'light' | 'dark' {
if (!this._systemAppearance) {
const resources = this.context.getResources();
const configuration = <android.content.res.Configuration>resources.getConfiguration();
get systemAppearance(): 'light' | 'dark' {
if (!this._systemAppearance) {
const resources = this.context.getResources();
const configuration = <android.content.res.Configuration>resources.getConfiguration();
this._systemAppearance = getSystemAppearanceValue(configuration);
}
this._systemAppearance = getSystemAppearanceValue(configuration);
}
return this._systemAppearance;
}
return this._systemAppearance;
}
set systemAppearance(value: 'light' | 'dark') {
this._systemAppearance = value;
}
set systemAppearance(value: 'light' | 'dark') {
this._systemAppearance = value;
}
public registerBroadcastReceiver(intentFilter: string, onReceiveCallback: (context: android.content.Context, intent: android.content.Intent) => void) {
ensureBroadCastReceiverClass();
const that = this;
const registerFunc = function (context: android.content.Context) {
const receiver: android.content.BroadcastReceiver = new BroadcastReceiverClass(onReceiveCallback);
context.registerReceiver(receiver, new android.content.IntentFilter(intentFilter));
that._registeredReceivers[intentFilter] = receiver;
};
public registerBroadcastReceiver(intentFilter: string, onReceiveCallback: (context: android.content.Context, intent: android.content.Intent) => void) {
ensureBroadCastReceiverClass();
const that = this;
const registerFunc = function (context: android.content.Context) {
const receiver: android.content.BroadcastReceiver = new BroadcastReceiverClass(onReceiveCallback);
context.registerReceiver(receiver, new android.content.IntentFilter(intentFilter));
that._registeredReceivers[intentFilter] = receiver;
};
if (this.context) {
registerFunc(this.context);
} else {
this._pendingReceiverRegistrations.push(registerFunc);
}
}
if (this.context) {
registerFunc(this.context);
} else {
this._pendingReceiverRegistrations.push(registerFunc);
}
}
public unregisterBroadcastReceiver(intentFilter: string) {
const receiver = this._registeredReceivers[intentFilter];
if (receiver) {
this.context.unregisterReceiver(receiver);
this._registeredReceivers[intentFilter] = undefined;
delete this._registeredReceivers[intentFilter];
}
}
public unregisterBroadcastReceiver(intentFilter: string) {
const receiver = this._registeredReceivers[intentFilter];
if (receiver) {
this.context.unregisterReceiver(receiver);
this._registeredReceivers[intentFilter] = undefined;
delete this._registeredReceivers[intentFilter];
}
}
}
// HACK: Use an interface with the same name, so that the class above fulfills the 'implements' requirement
@@ -138,18 +138,18 @@ export class AndroidApplication extends Observable implements AndroidApplication
// HACK: We declare all these 'on' statements, so that they can appear in the API reference
// HACK: Do we need this? Is it useful? There are static fields to the AndroidApplication class for the event names.
export interface AndroidApplication {
on(eventNames: string, callback: (data: AndroidActivityEventData) => void, thisArg?: any);
on(event: 'activityCreated', callback: (args: AndroidActivityBundleEventData) => void, thisArg?: any);
on(event: 'activityDestroyed', callback: (args: AndroidActivityEventData) => void, thisArg?: any);
on(event: 'activityStarted', callback: (args: AndroidActivityEventData) => void, thisArg?: any);
on(event: 'activityPaused', callback: (args: AndroidActivityEventData) => void, thisArg?: any);
on(event: 'activityResumed', callback: (args: AndroidActivityEventData) => void, thisArg?: any);
on(event: 'activityStopped', callback: (args: AndroidActivityEventData) => void, thisArg?: any);
on(event: 'saveActivityState', callback: (args: AndroidActivityBundleEventData) => void, thisArg?: any);
on(event: 'activityResult', callback: (args: AndroidActivityResultEventData) => void, thisArg?: any);
on(event: 'activityBackPressed', callback: (args: AndroidActivityBackPressedEventData) => void, thisArg?: any);
on(event: 'activityNewIntent', callback: (args: AndroidActivityNewIntentEventData) => void, thisArg?: any);
on(event: 'activityRequestPermissions', callback: (args: AndroidActivityRequestPermissionsEventData) => void, thisArg?: any);
on(eventNames: string, callback: (data: AndroidActivityEventData) => void, thisArg?: any);
on(event: 'activityCreated', callback: (args: AndroidActivityBundleEventData) => void, thisArg?: any);
on(event: 'activityDestroyed', callback: (args: AndroidActivityEventData) => void, thisArg?: any);
on(event: 'activityStarted', callback: (args: AndroidActivityEventData) => void, thisArg?: any);
on(event: 'activityPaused', callback: (args: AndroidActivityEventData) => void, thisArg?: any);
on(event: 'activityResumed', callback: (args: AndroidActivityEventData) => void, thisArg?: any);
on(event: 'activityStopped', callback: (args: AndroidActivityEventData) => void, thisArg?: any);
on(event: 'saveActivityState', callback: (args: AndroidActivityBundleEventData) => void, thisArg?: any);
on(event: 'activityResult', callback: (args: AndroidActivityResultEventData) => void, thisArg?: any);
on(event: 'activityBackPressed', callback: (args: AndroidActivityBackPressedEventData) => void, thisArg?: any);
on(event: 'activityNewIntent', callback: (args: AndroidActivityNewIntentEventData) => void, thisArg?: any);
on(event: 'activityRequestPermissions', callback: (args: AndroidActivityRequestPermissionsEventData) => void, thisArg?: any);
}
const androidApp = new AndroidApplication();
@@ -161,347 +161,347 @@ let mainEntry: NavigationEntry;
let started = false;
export function run(entry?: NavigationEntry | string) {
if (started) {
throw new Error('Application is already started.');
}
if (started) {
throw new Error('Application is already started.');
}
started = true;
mainEntry = typeof entry === 'string' ? { moduleName: entry } : entry;
if (!androidApp.nativeApp) {
const nativeApp = getNativeApplication();
androidApp.init(nativeApp);
}
started = true;
mainEntry = typeof entry === 'string' ? { moduleName: entry } : entry;
if (!androidApp.nativeApp) {
const nativeApp = getNativeApplication();
androidApp.init(nativeApp);
}
}
export function addCss(cssText: string, attributeScoped?: boolean): void {
notify(<CssChangedEventData>{
eventName: 'cssChanged',
object: androidApp,
cssText: cssText,
});
if (!attributeScoped) {
const rootView = getRootView();
if (rootView) {
rootView._onCssStateChange();
}
}
notify(<CssChangedEventData>{
eventName: 'cssChanged',
object: androidApp,
cssText: cssText,
});
if (!attributeScoped) {
const rootView = getRootView();
if (rootView) {
rootView._onCssStateChange();
}
}
}
const CALLBACKS = '_callbacks';
export function _resetRootView(entry?: NavigationEntry | string) {
const activity = androidApp.foregroundActivity;
if (!activity) {
throw new Error('Cannot find android activity.');
}
const activity = androidApp.foregroundActivity;
if (!activity) {
throw new Error('Cannot find android activity.');
}
mainEntry = typeof entry === 'string' ? { moduleName: entry } : entry;
const callbacks: AndroidActivityCallbacks = activity[CALLBACKS];
if (!callbacks) {
throw new Error('Cannot find android activity callbacks.');
}
callbacks.resetActivityContent(activity);
mainEntry = typeof entry === 'string' ? { moduleName: entry } : entry;
const callbacks: AndroidActivityCallbacks = activity[CALLBACKS];
if (!callbacks) {
throw new Error('Cannot find android activity callbacks.');
}
callbacks.resetActivityContent(activity);
}
export function getMainEntry() {
return mainEntry;
return mainEntry;
}
export function getRootView(): View {
// Use start activity as a backup when foregroundActivity is still not set
// in cases when we are getting the root view before activity.onResumed event is fired
const activity = androidApp.foregroundActivity || androidApp.startActivity;
if (!activity) {
return undefined;
}
const callbacks: AndroidActivityCallbacks = activity[CALLBACKS];
// Use start activity as a backup when foregroundActivity is still not set
// in cases when we are getting the root view before activity.onResumed event is fired
const activity = androidApp.foregroundActivity || androidApp.startActivity;
if (!activity) {
return undefined;
}
const callbacks: AndroidActivityCallbacks = activity[CALLBACKS];
return callbacks ? callbacks.getRootView() : undefined;
return callbacks ? callbacks.getRootView() : undefined;
}
export function getNativeApplication(): android.app.Application {
// Try getting it from module - check whether application.android.init has been explicitly called
let nativeApp = androidApp.nativeApp;
if (!nativeApp) {
// check whether the com.tns.NativeScriptApplication type exists
if (!nativeApp && com.tns.NativeScriptApplication) {
nativeApp = com.tns.NativeScriptApplication.getInstance();
}
// Try getting it from module - check whether application.android.init has been explicitly called
let nativeApp = androidApp.nativeApp;
if (!nativeApp) {
// check whether the com.tns.NativeScriptApplication type exists
if (!nativeApp && com.tns.NativeScriptApplication) {
nativeApp = com.tns.NativeScriptApplication.getInstance();
}
// the getInstance might return null if com.tns.NativeScriptApplication exists but is not the starting app type
if (!nativeApp) {
// TODO: Should we handle the case when a custom application type is provided and the user has not explicitly initialized the application module?
const clazz = java.lang.Class.forName('android.app.ActivityThread');
if (clazz) {
const method = clazz.getMethod('currentApplication', null);
if (method) {
nativeApp = method.invoke(null, null);
}
}
}
// the getInstance might return null if com.tns.NativeScriptApplication exists but is not the starting app type
if (!nativeApp) {
// TODO: Should we handle the case when a custom application type is provided and the user has not explicitly initialized the application module?
const clazz = java.lang.Class.forName('android.app.ActivityThread');
if (clazz) {
const method = clazz.getMethod('currentApplication', null);
if (method) {
nativeApp = method.invoke(null, null);
}
}
}
// we cannot work without having the app instance
if (!nativeApp) {
throw new Error("Failed to retrieve native Android Application object. If you have a custom android.app.Application type implemented make sure that you've called the '<application-module>.android.init' method.");
}
}
// we cannot work without having the app instance
if (!nativeApp) {
throw new Error("Failed to retrieve native Android Application object. If you have a custom android.app.Application type implemented make sure that you've called the '<application-module>.android.init' method.");
}
}
return nativeApp;
return nativeApp;
}
export function orientation(): 'portrait' | 'landscape' | 'unknown' {
return androidApp.orientation;
return androidApp.orientation;
}
export function systemAppearance(): 'dark' | 'light' {
return androidApp.systemAppearance;
return androidApp.systemAppearance;
}
global.__onLiveSync = function __onLiveSync(context?: ModuleContext) {
if (androidApp && androidApp.paused) {
return;
}
if (androidApp && androidApp.paused) {
return;
}
const rootView = getRootView();
livesync(rootView, context);
const rootView = getRootView();
livesync(rootView, context);
};
function getOrientationValue(configuration: android.content.res.Configuration): 'portrait' | 'landscape' | 'unknown' {
const orientation = configuration.orientation;
const orientation = configuration.orientation;
switch (orientation) {
case android.content.res.Configuration.ORIENTATION_LANDSCAPE:
return 'landscape';
case android.content.res.Configuration.ORIENTATION_PORTRAIT:
return 'portrait';
default:
return 'unknown';
}
switch (orientation) {
case android.content.res.Configuration.ORIENTATION_LANDSCAPE:
return 'landscape';
case android.content.res.Configuration.ORIENTATION_PORTRAIT:
return 'portrait';
default:
return 'unknown';
}
}
// https://developer.android.com/guide/topics/ui/look-and-feel/darktheme#configuration_changes
function getSystemAppearanceValue(configuration: android.content.res.Configuration): 'dark' | 'light' {
const systemAppearance = configuration.uiMode & android.content.res.Configuration.UI_MODE_NIGHT_MASK;
const systemAppearance = configuration.uiMode & android.content.res.Configuration.UI_MODE_NIGHT_MASK;
switch (systemAppearance) {
case android.content.res.Configuration.UI_MODE_NIGHT_YES:
return 'dark';
case android.content.res.Configuration.UI_MODE_NIGHT_NO:
case android.content.res.Configuration.UI_MODE_NIGHT_UNDEFINED:
return 'light';
}
switch (systemAppearance) {
case android.content.res.Configuration.UI_MODE_NIGHT_YES:
return 'dark';
case android.content.res.Configuration.UI_MODE_NIGHT_NO:
case android.content.res.Configuration.UI_MODE_NIGHT_UNDEFINED:
return 'light';
}
}
function initLifecycleCallbacks() {
const setThemeOnLaunch = profile('setThemeOnLaunch', (activity: androidx.appcompat.app.AppCompatActivity) => {
// Set app theme after launch screen was used during startup
const activityInfo = activity.getPackageManager().getActivityInfo(activity.getComponentName(), android.content.pm.PackageManager.GET_META_DATA);
if (activityInfo.metaData) {
const setThemeOnLaunch = activityInfo.metaData.getInt('SET_THEME_ON_LAUNCH', -1);
if (setThemeOnLaunch !== -1) {
activity.setTheme(setThemeOnLaunch);
}
}
});
const setThemeOnLaunch = profile('setThemeOnLaunch', (activity: androidx.appcompat.app.AppCompatActivity) => {
// Set app theme after launch screen was used during startup
const activityInfo = activity.getPackageManager().getActivityInfo(activity.getComponentName(), android.content.pm.PackageManager.GET_META_DATA);
if (activityInfo.metaData) {
const setThemeOnLaunch = activityInfo.metaData.getInt('SET_THEME_ON_LAUNCH', -1);
if (setThemeOnLaunch !== -1) {
activity.setTheme(setThemeOnLaunch);
}
}
});
const notifyActivityCreated = profile('notifyActivityCreated', function (activity: androidx.appcompat.app.AppCompatActivity, savedInstanceState: android.os.Bundle) {
androidApp.notify(<AndroidActivityBundleEventData>{
eventName: ActivityCreated,
object: androidApp,
activity,
bundle: savedInstanceState,
});
});
const notifyActivityCreated = profile('notifyActivityCreated', function (activity: androidx.appcompat.app.AppCompatActivity, savedInstanceState: android.os.Bundle) {
androidApp.notify(<AndroidActivityBundleEventData>{
eventName: ActivityCreated,
object: androidApp,
activity,
bundle: savedInstanceState,
});
});
const subscribeForGlobalLayout = profile('subscribeForGlobalLayout', function (activity: androidx.appcompat.app.AppCompatActivity) {
const rootView = activity.getWindow().getDecorView().getRootView();
// store the listener not to trigger GC collection before collecting the method
global.onGlobalLayoutListener = new android.view.ViewTreeObserver.OnGlobalLayoutListener({
onGlobalLayout() {
notify({
eventName: displayedEvent,
object: androidApp,
activity,
});
let viewTreeObserver = rootView.getViewTreeObserver();
viewTreeObserver.removeOnGlobalLayoutListener(global.onGlobalLayoutListener);
},
});
rootView.getViewTreeObserver().addOnGlobalLayoutListener(global.onGlobalLayoutListener);
});
const subscribeForGlobalLayout = profile('subscribeForGlobalLayout', function (activity: androidx.appcompat.app.AppCompatActivity) {
const rootView = activity.getWindow().getDecorView().getRootView();
// store the listener not to trigger GC collection before collecting the method
global.onGlobalLayoutListener = new android.view.ViewTreeObserver.OnGlobalLayoutListener({
onGlobalLayout() {
notify({
eventName: displayedEvent,
object: androidApp,
activity,
});
let viewTreeObserver = rootView.getViewTreeObserver();
viewTreeObserver.removeOnGlobalLayoutListener(global.onGlobalLayoutListener);
},
});
rootView.getViewTreeObserver().addOnGlobalLayoutListener(global.onGlobalLayoutListener);
});
const lifecycleCallbacks = new android.app.Application.ActivityLifecycleCallbacks({
onActivityCreated: <any>profile('onActivityCreated', function (activity: androidx.appcompat.app.AppCompatActivity, savedInstanceState: android.os.Bundle) {
setThemeOnLaunch(activity, undefined, undefined);
const lifecycleCallbacks = new android.app.Application.ActivityLifecycleCallbacks({
onActivityCreated: <any>profile('onActivityCreated', function (activity: androidx.appcompat.app.AppCompatActivity, savedInstanceState: android.os.Bundle) {
setThemeOnLaunch(activity, undefined, undefined);
if (!androidApp.startActivity) {
androidApp.startActivity = activity;
}
if (!androidApp.startActivity) {
androidApp.startActivity = activity;
}
notifyActivityCreated(activity, <any>savedInstanceState, undefined);
notifyActivityCreated(activity, <any>savedInstanceState, undefined);
if (hasListeners(displayedEvent)) {
subscribeForGlobalLayout(activity, undefined, undefined);
}
}),
if (hasListeners(displayedEvent)) {
subscribeForGlobalLayout(activity, undefined, undefined);
}
}),
onActivityDestroyed: <any>profile('onActivityDestroyed', function (activity: androidx.appcompat.app.AppCompatActivity) {
if (activity === androidApp.foregroundActivity) {
androidApp.foregroundActivity = undefined;
}
onActivityDestroyed: <any>profile('onActivityDestroyed', function (activity: androidx.appcompat.app.AppCompatActivity) {
if (activity === androidApp.foregroundActivity) {
androidApp.foregroundActivity = undefined;
}
if (activity === androidApp.startActivity) {
androidApp.startActivity = undefined;
}
if (activity === androidApp.startActivity) {
androidApp.startActivity = undefined;
}
androidApp.notify(<AndroidActivityEventData>{
eventName: ActivityDestroyed,
object: androidApp,
activity: activity,
});
// TODO: This is a temporary workaround to force the V8's Garbage Collector, which will force the related Java Object to be collected.
gc();
}),
androidApp.notify(<AndroidActivityEventData>{
eventName: ActivityDestroyed,
object: androidApp,
activity: activity,
});
// TODO: This is a temporary workaround to force the V8's Garbage Collector, which will force the related Java Object to be collected.
gc();
}),
onActivityPaused: <any>profile('onActivityPaused', function (activity: androidx.appcompat.app.AppCompatActivity) {
if ((<any>activity).isNativeScriptActivity) {
androidApp.paused = true;
notify(<ApplicationEventData>{
eventName: suspendEvent,
object: androidApp,
android: activity,
});
}
onActivityPaused: <any>profile('onActivityPaused', function (activity: androidx.appcompat.app.AppCompatActivity) {
if ((<any>activity).isNativeScriptActivity) {
androidApp.paused = true;
notify(<ApplicationEventData>{
eventName: suspendEvent,
object: androidApp,
android: activity,
});
}
androidApp.notify(<AndroidActivityEventData>{
eventName: ActivityPaused,
object: androidApp,
activity: activity,
});
}),
androidApp.notify(<AndroidActivityEventData>{
eventName: ActivityPaused,
object: androidApp,
activity: activity,
});
}),
onActivityResumed: <any>profile('onActivityResumed', function (activity: androidx.appcompat.app.AppCompatActivity) {
androidApp.foregroundActivity = activity;
onActivityResumed: <any>profile('onActivityResumed', function (activity: androidx.appcompat.app.AppCompatActivity) {
androidApp.foregroundActivity = activity;
androidApp.notify(<AndroidActivityEventData>{
eventName: ActivityResumed,
object: androidApp,
activity: activity,
});
}),
androidApp.notify(<AndroidActivityEventData>{
eventName: ActivityResumed,
object: androidApp,
activity: activity,
});
}),
onActivitySaveInstanceState: <any>profile('onActivitySaveInstanceState', function (activity: androidx.appcompat.app.AppCompatActivity, outState: android.os.Bundle) {
androidApp.notify(<AndroidActivityBundleEventData>{
eventName: SaveActivityState,
object: androidApp,
activity: activity,
bundle: outState,
});
}),
onActivitySaveInstanceState: <any>profile('onActivitySaveInstanceState', function (activity: androidx.appcompat.app.AppCompatActivity, outState: android.os.Bundle) {
androidApp.notify(<AndroidActivityBundleEventData>{
eventName: SaveActivityState,
object: androidApp,
activity: activity,
bundle: outState,
});
}),
onActivityStarted: <any>profile('onActivityStarted', function (activity: androidx.appcompat.app.AppCompatActivity) {
androidApp.notify(<AndroidActivityEventData>{
eventName: ActivityStarted,
object: androidApp,
activity: activity,
});
}),
onActivityStarted: <any>profile('onActivityStarted', function (activity: androidx.appcompat.app.AppCompatActivity) {
androidApp.notify(<AndroidActivityEventData>{
eventName: ActivityStarted,
object: androidApp,
activity: activity,
});
}),
onActivityStopped: <any>profile('onActivityStopped', function (activity: androidx.appcompat.app.AppCompatActivity) {
androidApp.notify(<AndroidActivityEventData>{
eventName: ActivityStopped,
object: androidApp,
activity: activity,
});
}),
});
onActivityStopped: <any>profile('onActivityStopped', function (activity: androidx.appcompat.app.AppCompatActivity) {
androidApp.notify(<AndroidActivityEventData>{
eventName: ActivityStopped,
object: androidApp,
activity: activity,
});
}),
});
return lifecycleCallbacks;
return lifecycleCallbacks;
}
function initComponentCallbacks() {
let componentCallbacks = new android.content.ComponentCallbacks2({
onLowMemory: <any>profile('onLowMemory', function () {
gc();
java.lang.System.gc();
notify(<ApplicationEventData>{
eventName: lowMemoryEvent,
object: this,
android: this,
});
}),
let componentCallbacks = new android.content.ComponentCallbacks2({
onLowMemory: <any>profile('onLowMemory', function () {
gc();
java.lang.System.gc();
notify(<ApplicationEventData>{
eventName: lowMemoryEvent,
object: this,
android: this,
});
}),
onTrimMemory: <any>profile('onTrimMemory', function (level: number) {
// TODO: This is skipped for now, test carefully for OutOfMemory exceptions
}),
onTrimMemory: <any>profile('onTrimMemory', function (level: number) {
// TODO: This is skipped for now, test carefully for OutOfMemory exceptions
}),
onConfigurationChanged: <any>profile('onConfigurationChanged', function (newConfiguration: android.content.res.Configuration) {
const rootView = getRootView();
const newOrientation = getOrientationValue(newConfiguration);
onConfigurationChanged: <any>profile('onConfigurationChanged', function (newConfiguration: android.content.res.Configuration) {
const rootView = getRootView();
const newOrientation = getOrientationValue(newConfiguration);
if (androidApp.orientation !== newOrientation) {
androidApp.orientation = newOrientation;
orientationChanged(rootView, newOrientation);
if (androidApp.orientation !== newOrientation) {
androidApp.orientation = newOrientation;
orientationChanged(rootView, newOrientation);
notify(<OrientationChangedEventData>{
eventName: orientationChangedEvent,
android: androidApp.nativeApp,
newValue: androidApp.orientation,
object: androidApp,
});
notify(<OrientationChangedEventData>{
eventName: orientationChangedEvent,
android: androidApp.nativeApp,
newValue: androidApp.orientation,
object: androidApp,
});
return;
}
return;
}
const newSystemAppearance = getSystemAppearanceValue(newConfiguration);
const newSystemAppearance = getSystemAppearanceValue(newConfiguration);
if (androidApp.systemAppearance !== newSystemAppearance) {
androidApp.systemAppearance = newSystemAppearance;
systemAppearanceChanged(rootView, newSystemAppearance);
if (androidApp.systemAppearance !== newSystemAppearance) {
androidApp.systemAppearance = newSystemAppearance;
systemAppearanceChanged(rootView, newSystemAppearance);
notify(<SystemAppearanceChangedEventData>{
eventName: systemAppearanceChangedEvent,
android: androidApp.nativeApp,
newValue: androidApp.systemAppearance,
object: androidApp,
});
}
}),
});
notify(<SystemAppearanceChangedEventData>{
eventName: systemAppearanceChangedEvent,
android: androidApp.nativeApp,
newValue: androidApp.systemAppearance,
object: androidApp,
});
}
}),
});
return componentCallbacks;
return componentCallbacks;
}
let BroadcastReceiverClass;
function ensureBroadCastReceiverClass() {
if (BroadcastReceiverClass) {
return;
}
if (BroadcastReceiverClass) {
return;
}
class BroadcastReceiver extends android.content.BroadcastReceiver {
private _onReceiveCallback: (context: android.content.Context, intent: android.content.Intent) => void;
class BroadcastReceiver extends android.content.BroadcastReceiver {
private _onReceiveCallback: (context: android.content.Context, intent: android.content.Intent) => void;
constructor(onReceiveCallback: (context: android.content.Context, intent: android.content.Intent) => void) {
super();
this._onReceiveCallback = onReceiveCallback;
constructor(onReceiveCallback: (context: android.content.Context, intent: android.content.Intent) => void) {
super();
this._onReceiveCallback = onReceiveCallback;
return global.__native(this);
}
return global.__native(this);
}
public onReceive(context: android.content.Context, intent: android.content.Intent) {
if (this._onReceiveCallback) {
this._onReceiveCallback(context, intent);
}
}
}
public onReceive(context: android.content.Context, intent: android.content.Intent) {
if (this._onReceiveCallback) {
this._onReceiveCallback(context, intent);
}
}
}
BroadcastReceiverClass = BroadcastReceiver;
BroadcastReceiverClass = BroadcastReceiver;
}
declare namespace com {
namespace tns {
class NativeScriptApplication extends android.app.Application {
static getInstance(): NativeScriptApplication;
}
}
namespace tns {
class NativeScriptApplication extends android.app.Application {
static getInstance(): NativeScriptApplication;
}
}
}

View File

@@ -58,82 +58,82 @@ export const systemAppearanceChangedEvent: string;
* Event data containing information for the application events.
*/
export interface ApplicationEventData extends EventData {
/**
* Gets the native iOS event arguments. Valid only when running on iOS.
*/
ios?: any;
/**
* Gets the native iOS event arguments. Valid only when running on iOS.
*/
ios?: any;
/**
* Gets the native Android event arguments. Valid only when running on Android.
*/
android?: any;
/**
* Gets the native Android event arguments. Valid only when running on Android.
*/
android?: any;
/**
* The name of the event.
*/
eventName: string;
/**
* The name of the event.
*/
eventName: string;
/**
* The instance that has raised the event.
*/
object: any;
/**
* The instance that has raised the event.
*/
object: any;
}
/**
* Event data containing information for launch event.
*/
export interface LaunchEventData extends ApplicationEventData {
/**
* The root view for this Window on iOS or Activity for Android.
* If not set a new Frame will be created as a root view in order to maintain backwards compatibility.
*/
root?: View;
/**
* The root view for this Window on iOS or Activity for Android.
* If not set a new Frame will be created as a root view in order to maintain backwards compatibility.
*/
root?: View;
savedInstanceState?: any /* android.os.Bundle */;
savedInstanceState?: any /* android.os.Bundle */;
}
/**
* Event data containing information for orientation changed event.
*/
export interface OrientationChangedEventData extends ApplicationEventData {
/**
* New orientation value.
*/
newValue: 'portrait' | 'landscape' | 'unknown';
/**
* New orientation value.
*/
newValue: 'portrait' | 'landscape' | 'unknown';
}
/**
* Event data containing information for system appearance changed event.
*/
export interface SystemAppearanceChangedEventData extends ApplicationEventData {
/**
* New system appearance value.
*/
newValue: 'light' | 'dark';
/**
* New system appearance value.
*/
newValue: 'light' | 'dark';
}
/**
* Event data containing information about unhandled application errors.
*/
export interface UnhandledErrorEventData extends ApplicationEventData {
ios?: NativeScriptError;
android?: NativeScriptError;
error: NativeScriptError;
ios?: NativeScriptError;
android?: NativeScriptError;
error: NativeScriptError;
}
/**
* Event data containing information about discarded application errors.
*/
export interface DiscardedErrorEventData extends ApplicationEventData {
error: NativeScriptError;
error: NativeScriptError;
}
/**
* Event data containing information about application css change.
*/
export interface CssChangedEventData extends EventData {
cssFile?: string;
cssText?: string;
cssFile?: string;
cssText?: string;
}
/**
@@ -321,277 +321,277 @@ export let ios: iOSApplication;
* Data for the Android activity events.
*/
export interface AndroidActivityEventData {
/**
* The activity.
*/
activity: any /* androidx.appcompat.app.AppCompatActivity */;
/**
* The activity.
*/
activity: any /* androidx.appcompat.app.AppCompatActivity */;
/**
* The name of the event.
*/
eventName: string;
/**
* The name of the event.
*/
eventName: string;
/**
* The instance that has raised the event.
*/
object: any;
/**
* The instance that has raised the event.
*/
object: any;
}
/**
* Data for the Android activity events with bundle.
*/
export interface AndroidActivityBundleEventData extends AndroidActivityEventData {
/**
* The bundle.
*/
bundle: any /* android.os.Bundle */;
/**
* The bundle.
*/
bundle: any /* android.os.Bundle */;
}
/**
* Data for the Android activity onRequestPermissions callback
*/
export interface AndroidActivityRequestPermissionsEventData extends AndroidActivityEventData {
/**
* The request code.
*/
requestCode: number;
/**
* The request code.
*/
requestCode: number;
/**
* The Permissions.
*/
permissions: Array<string>;
/**
* The Permissions.
*/
permissions: Array<string>;
/**
* The Granted.
*/
grantResults: Array<number>;
/**
* The Granted.
*/
grantResults: Array<number>;
}
/**
* Data for the Android activity result event.
*/
export interface AndroidActivityResultEventData extends AndroidActivityEventData {
/**
* The request code.
*/
requestCode: number;
/**
* The request code.
*/
requestCode: number;
/**
* The result code.
*/
resultCode: number;
/**
* The result code.
*/
resultCode: number;
/**
* The intent.
*/
intent: any /* android.content.Intent */;
/**
* The intent.
*/
intent: any /* android.content.Intent */;
}
/**
* Data for the Android activity newIntent event.
*/
export interface AndroidActivityNewIntentEventData extends AndroidActivityEventData {
/**
* The intent.
*/
intent: any /* android.content.Intent */;
/**
* The intent.
*/
intent: any /* android.content.Intent */;
}
/**
* Data for the Android activity back pressed event.
*/
export interface AndroidActivityBackPressedEventData extends AndroidActivityEventData {
/**
* In the event handler, set this value to true if you want to cancel the back navigation and do something else instead.
*/
cancel: boolean;
/**
* In the event handler, set this value to true if you want to cancel the back navigation and do something else instead.
*/
cancel: boolean;
}
/**
* The abstraction of an Android-specific application object.
*/
export class AndroidApplication extends Observable {
/**
* The [android Application](http://developer.android.com/reference/android/app/Application.html) object instance provided to the init of the module.
*/
nativeApp: any /* android.app.Application */;
/**
* The [android Application](http://developer.android.com/reference/android/app/Application.html) object instance provided to the init of the module.
*/
nativeApp: any /* android.app.Application */;
/**
* The application's [android Context](http://developer.android.com/reference/android/content/Context.html) object instance.
*/
context: any /* android.content.Context */;
/**
* The application's [android Context](http://developer.android.com/reference/android/content/Context.html) object instance.
*/
context: any /* android.content.Context */;
/**
* The currently active (loaded) [android Activity](http://developer.android.com/reference/android/app/Activity.html). This property is automatically updated upon Activity events.
*/
foregroundActivity: any /* androidx.appcompat.app.AppCompatActivity */;
/**
* The currently active (loaded) [android Activity](http://developer.android.com/reference/android/app/Activity.html). This property is automatically updated upon Activity events.
*/
foregroundActivity: any /* androidx.appcompat.app.AppCompatActivity */;
/**
* The main (start) Activity for the application.
*/
startActivity: any /* androidx.appcompat.app.AppCompatActivity */;
/**
* The main (start) Activity for the application.
*/
startActivity: any /* androidx.appcompat.app.AppCompatActivity */;
/**
* Gets the orientation of the application.
* Available values: "portrait", "landscape", "unknown".
*/
orientation: 'portrait' | 'landscape' | 'unknown';
/**
* Gets the orientation of the application.
* Available values: "portrait", "landscape", "unknown".
*/
orientation: 'portrait' | 'landscape' | 'unknown';
/**
* Gets the system appearance.
* Available values: "dark", "light".
*/
systemAppearance: 'dark' | 'light';
/**
* Gets the system appearance.
* Available values: "dark", "light".
*/
systemAppearance: 'dark' | 'light';
/**
* The name of the application package.
*/
packageName: string;
/**
* The name of the application package.
*/
packageName: string;
/**
* True if the main application activity is not running (suspended), false otherwise.
*/
paused: boolean;
/**
* True if the main application activity is not running (suspended), false otherwise.
*/
paused: boolean;
/**
* Initialized the android-specific application object with the native android.app.Application instance.
* This is useful when creating custom application types.
* @param nativeApp - the android.app.Application instance that started the app.
*/
init: (nativeApp) => void;
/**
* Initialized the android-specific application object with the native android.app.Application instance.
* This is useful when creating custom application types.
* @param nativeApp - the android.app.Application instance that started the app.
*/
init: (nativeApp) => void;
/**
* A basic method signature to hook an event listener (shortcut alias to the addEventListener method).
* @param eventNames - String corresponding to events (e.g. "propertyChange"). Optionally could be used more events separated by `,` (e.g. "propertyChange", "change").
* @param callback - Callback function which will be executed when event is raised.
* @param thisArg - An optional parameter which will be used as `this` context for callback execution.
*/
on(eventNames: string, callback: (data: AndroidActivityEventData) => void, thisArg?: any);
/**
* A basic method signature to hook an event listener (shortcut alias to the addEventListener method).
* @param eventNames - String corresponding to events (e.g. "propertyChange"). Optionally could be used more events separated by `,` (e.g. "propertyChange", "change").
* @param callback - Callback function which will be executed when event is raised.
* @param thisArg - An optional parameter which will be used as `this` context for callback execution.
*/
on(eventNames: string, callback: (data: AndroidActivityEventData) => void, thisArg?: any);
/**
* This event is raised on android application ActivityCreated.
*/
on(event: 'activityCreated', callback: (args: AndroidActivityBundleEventData) => void, thisArg?: any);
/**
* This event is raised on android application ActivityCreated.
*/
on(event: 'activityCreated', callback: (args: AndroidActivityBundleEventData) => void, thisArg?: any);
/**
* This event is raised on android application ActivityDestroyed.
*/
on(event: 'activityDestroyed', callback: (args: AndroidActivityEventData) => void, thisArg?: any);
/**
* This event is raised on android application ActivityDestroyed.
*/
on(event: 'activityDestroyed', callback: (args: AndroidActivityEventData) => void, thisArg?: any);
/**
* This event is raised on android application ActivityStarted.
*/
on(event: 'activityStarted', callback: (args: AndroidActivityEventData) => void, thisArg?: any);
/**
* This event is raised on android application ActivityStarted.
*/
on(event: 'activityStarted', callback: (args: AndroidActivityEventData) => void, thisArg?: any);
/**
* This event is raised on android application ActivityPaused.
*/
on(event: 'activityPaused', callback: (args: AndroidActivityEventData) => void, thisArg?: any);
/**
* This event is raised on android application ActivityPaused.
*/
on(event: 'activityPaused', callback: (args: AndroidActivityEventData) => void, thisArg?: any);
/**
* This event is raised on android application ActivityResumed.
*/
on(event: 'activityResumed', callback: (args: AndroidActivityEventData) => void, thisArg?: any);
/**
* This event is raised on android application ActivityResumed.
*/
on(event: 'activityResumed', callback: (args: AndroidActivityEventData) => void, thisArg?: any);
/**
* This event is raised on android application ActivityStopped.
*/
on(event: 'activityStopped', callback: (args: AndroidActivityEventData) => void, thisArg?: any);
/**
* This event is raised on android application ActivityStopped.
*/
on(event: 'activityStopped', callback: (args: AndroidActivityEventData) => void, thisArg?: any);
/**
* This event is raised on android application SaveActivityState.
*/
on(event: 'saveActivityState', callback: (args: AndroidActivityBundleEventData) => void, thisArg?: any);
/**
* This event is raised on android application SaveActivityState.
*/
on(event: 'saveActivityState', callback: (args: AndroidActivityBundleEventData) => void, thisArg?: any);
/**
* This event is raised on android application ActivityResult.
*/
on(event: 'activityResult', callback: (args: AndroidActivityResultEventData) => void, thisArg?: any);
/**
* This event is raised on android application ActivityResult.
*/
on(event: 'activityResult', callback: (args: AndroidActivityResultEventData) => void, thisArg?: any);
/**
* This event is raised on the back button is pressed in an android application.
*/
on(event: 'activityBackPressed', callback: (args: AndroidActivityBackPressedEventData) => void, thisArg?: any);
/**
* This event is raised on the back button is pressed in an android application.
*/
on(event: 'activityBackPressed', callback: (args: AndroidActivityBackPressedEventData) => void, thisArg?: any);
/**
* This event is raised when the Android app was launched by an Intent with data.
*/
on(event: 'activityNewIntent', callback: (args: AndroidActivityNewIntentEventData) => void, thisArg?: any);
/**
* This event is raised when the Android app was launched by an Intent with data.
*/
on(event: 'activityNewIntent', callback: (args: AndroidActivityNewIntentEventData) => void, thisArg?: any);
/**
* This event is raised when the Android activity requests permissions.
*/
on(event: 'activityRequestPermissions', callback: (args: AndroidActivityRequestPermissionsEventData) => void, thisArg?: any);
/**
* This event is raised when the Android activity requests permissions.
*/
on(event: 'activityRequestPermissions', callback: (args: AndroidActivityRequestPermissionsEventData) => void, thisArg?: any);
/**
* String value used when hooking to activityCreated event.
*/
public static activityCreatedEvent: string;
/**
* String value used when hooking to activityCreated event.
*/
public static activityCreatedEvent: string;
/**
* String value used when hooking to activityDestroyed event.
*/
public static activityDestroyedEvent: string;
/**
* String value used when hooking to activityDestroyed event.
*/
public static activityDestroyedEvent: string;
/**
* String value used when hooking to activityStarted event.
*/
public static activityStartedEvent: string;
/**
* String value used when hooking to activityStarted event.
*/
public static activityStartedEvent: string;
/**
* String value used when hooking to activityPaused event.
*/
public static activityPausedEvent: string;
/**
* String value used when hooking to activityPaused event.
*/
public static activityPausedEvent: string;
/**
* String value used when hooking to activityResumed event.
*/
public static activityResumedEvent: string;
/**
* String value used when hooking to activityResumed event.
*/
public static activityResumedEvent: string;
/**
* String value used when hooking to activityStopped event.
*/
public static activityStoppedEvent: string;
/**
* String value used when hooking to activityStopped event.
*/
public static activityStoppedEvent: string;
/**
* String value used when hooking to saveActivityState event.
*/
public static saveActivityStateEvent: string;
/**
* String value used when hooking to saveActivityState event.
*/
public static saveActivityStateEvent: string;
/**
* String value used when hooking to activityResult event.
*/
public static activityResultEvent: string;
/**
* String value used when hooking to activityResult event.
*/
public static activityResultEvent: string;
/**
* String value used when hooking to activityBackPressed event.
*/
public static activityBackPressedEvent: string;
/**
* String value used when hooking to activityBackPressed event.
*/
public static activityBackPressedEvent: string;
/**
* String value used when hooking to activityNewIntent event.
*/
public static activityNewIntentEvent: string;
/**
* String value used when hooking to activityNewIntent event.
*/
public static activityNewIntentEvent: string;
/**
* String value used when hooking to requestPermissions event.
*/
public static activityRequestPermissionsEvent: string;
/**
* String value used when hooking to requestPermissions event.
*/
public static activityRequestPermissionsEvent: string;
/**
* Register a BroadcastReceiver to be run in the main activity thread. The receiver will be called with any broadcast Intent that matches filter, in the main application thread.
* For more information, please visit 'http://developer.android.com/reference/android/content/Context.html#registerReceiver%28android.content.BroadcastReceiver,%20android.content.IntentFilter%29'
* @param intentFilter A string containing the intent filter.
* @param onReceiveCallback A callback function that will be called each time the receiver receives a broadcast.
*/
registerBroadcastReceiver(intentFilter: string, onReceiveCallback: (context: any /* android.content.Context */, intent: any /* android.content.Intent */) => void): void;
/**
* Register a BroadcastReceiver to be run in the main activity thread. The receiver will be called with any broadcast Intent that matches filter, in the main application thread.
* For more information, please visit 'http://developer.android.com/reference/android/content/Context.html#registerReceiver%28android.content.BroadcastReceiver,%20android.content.IntentFilter%29'
* @param intentFilter A string containing the intent filter.
* @param onReceiveCallback A callback function that will be called each time the receiver receives a broadcast.
*/
registerBroadcastReceiver(intentFilter: string, onReceiveCallback: (context: any /* android.content.Context */, intent: any /* android.content.Intent */) => void): void;
/**
* Unregister a previously registered BroadcastReceiver.
* For more information, please visit 'http://developer.android.com/reference/android/content/Context.html#unregisterReceiver(android.content.BroadcastReceiver)'
* @param intentFilter A string containing the intent filter with which the receiver was originally registered.
*/
unregisterBroadcastReceiver(intentFilter: string): void;
/**
* Unregister a previously registered BroadcastReceiver.
* For more information, please visit 'http://developer.android.com/reference/android/content/Context.html#unregisterReceiver(android.content.BroadcastReceiver)'
* @param intentFilter A string containing the intent filter with which the receiver was originally registered.
*/
unregisterBroadcastReceiver(intentFilter: string): void;
}
/* tslint:disable */
@@ -599,64 +599,64 @@ export class AndroidApplication extends Observable {
* The abstraction of an iOS-specific application object.
*/
export class iOSApplication {
/* tslint:enable */
/**
* The root view controller for the application.
*/
rootController: any /* UIViewController */;
/* tslint:enable */
/**
* The root view controller for the application.
*/
rootController: any /* UIViewController */;
/* tslint:enable */
/**
* The key window.
*/
window: any /* UIWindow */;
/* tslint:enable */
/**
* The key window.
*/
window: any /* UIWindow */;
/**
* The [UIApplicationDelegate](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplicationDelegate_Protocol/index.html) class.
*/
delegate: any /* typeof UIApplicationDelegate */;
/**
* The [UIApplicationDelegate](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplicationDelegate_Protocol/index.html) class.
*/
delegate: any /* typeof UIApplicationDelegate */;
/**
* Gets or sets the orientation of the application.
* Available values: "portrait", "landscape", "unknown".
*/
orientation: 'portrait' | 'landscape' | 'unknown';
/**
* Gets or sets the orientation of the application.
* Available values: "portrait", "landscape", "unknown".
*/
orientation: 'portrait' | 'landscape' | 'unknown';
/**
* Gets the system appearance.
* Available values: "dark", "light", null.
* Null for iOS <= 11.
*/
systemAppearance: 'dark' | 'light' | null;
/**
* Gets the system appearance.
* Available values: "dark", "light", null.
* Null for iOS <= 11.
*/
systemAppearance: 'dark' | 'light' | null;
/**
* The [UIApplication](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplication_Class/index.html).
*/
nativeApp: any /* UIApplication */;
/**
* The [UIApplication](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplication_Class/index.html).
*/
nativeApp: any /* UIApplication */;
/**
* Adds an observer to the default notification center for the specified notification.
* For more information, please visit 'https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/#//apple_ref/occ/instm/NSNotificationCenter/addObserver:selector:name:object:'
* @param notificationName A string containing the name of the notification.
* @param onReceiveCallback A callback function that will be called each time the observer receives a notification.
*/
addNotificationObserver(notificationName: string, onReceiveCallback: (notification: any /* NSNotification */) => void): any;
/**
* Adds an observer to the default notification center for the specified notification.
* For more information, please visit 'https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/#//apple_ref/occ/instm/NSNotificationCenter/addObserver:selector:name:object:'
* @param notificationName A string containing the name of the notification.
* @param onReceiveCallback A callback function that will be called each time the observer receives a notification.
*/
addNotificationObserver(notificationName: string, onReceiveCallback: (notification: any /* NSNotification */) => void): any;
/**
* Removes the observer for the specified notification from the default notification center.
* For more information, please visit 'https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/#//apple_ref/occ/instm/NSNotificationCenter/addObserver:selector:name:object:'
* @param observer The observer that was returned from the addNotificationObserver method.
* @param notificationName A string containing the name of the notification.
* @param onReceiveCallback A callback function that will be called each time the observer receives a notification.
*/
removeNotificationObserver(observer: any, notificationName: string): void;
/**
* Removes the observer for the specified notification from the default notification center.
* For more information, please visit 'https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/#//apple_ref/occ/instm/NSNotificationCenter/addObserver:selector:name:object:'
* @param observer The observer that was returned from the addNotificationObserver method.
* @param notificationName A string containing the name of the notification.
* @param onReceiveCallback A callback function that will be called each time the observer receives a notification.
*/
removeNotificationObserver(observer: any, notificationName: string): void;
}
/**
* @deprecated
*/
export interface RootViewControllerImpl {
contentController: any;
contentController: any;
}
export function getNativeApplication(): any;
@@ -667,5 +667,5 @@ export function getNativeApplication(): any;
export function hasLaunched(): boolean;
export interface LoadAppCSSEventData extends EventData {
cssFile: string;
cssFile: string;
}

View File

@@ -26,313 +26,313 @@ const majorVersion = ios.MajorVersion;
// TODO: Refactor the UIResponder to use Typescript extends when this issue is resolved:
// https://github.com/NativeScript/ios-runtime/issues/1012
const Responder = (<any>UIResponder).extend(
{
get window() {
return iosApp ? iosApp.window : undefined;
},
set window(setWindow) {
// NOOP
},
},
{
protocols: [UIApplicationDelegate],
}
{
get window() {
return iosApp ? iosApp.window : undefined;
},
set window(setWindow) {
// NOOP
},
},
{
protocols: [UIApplicationDelegate],
}
);
class NotificationObserver extends NSObject {
private _onReceiveCallback: (notification: NSNotification) => void;
private _onReceiveCallback: (notification: NSNotification) => void;
public static initWithCallback(onReceiveCallback: (notification: NSNotification) => void): NotificationObserver {
const observer = <NotificationObserver>super.new();
observer._onReceiveCallback = onReceiveCallback;
public static initWithCallback(onReceiveCallback: (notification: NSNotification) => void): NotificationObserver {
const observer = <NotificationObserver>super.new();
observer._onReceiveCallback = onReceiveCallback;
return observer;
}
return observer;
}
public onReceive(notification: NSNotification): void {
this._onReceiveCallback(notification);
}
public onReceive(notification: NSNotification): void {
this._onReceiveCallback(notification);
}
public static ObjCExposedMethods = {
onReceive: { returns: interop.types.void, params: [NSNotification] },
};
public static ObjCExposedMethods = {
onReceive: { returns: interop.types.void, params: [NSNotification] },
};
}
let displayedOnce = false;
let displayedLinkTarget;
let displayedLink;
class CADisplayLinkTarget extends NSObject {
onDisplayed(link: CADisplayLink) {
link.invalidate();
const ios = UIApplication.sharedApplication;
const object = iosApp;
displayedOnce = true;
notify(<ApplicationEventData>{
eventName: displayedEvent,
object,
ios,
});
displayedLinkTarget = null;
displayedLink = null;
}
public static ObjCExposedMethods = {
onDisplayed: { returns: interop.types.void, params: [CADisplayLink] },
};
onDisplayed(link: CADisplayLink) {
link.invalidate();
const ios = UIApplication.sharedApplication;
const object = iosApp;
displayedOnce = true;
notify(<ApplicationEventData>{
eventName: displayedEvent,
object,
ios,
});
displayedLinkTarget = null;
displayedLink = null;
}
public static ObjCExposedMethods = {
onDisplayed: { returns: interop.types.void, params: [CADisplayLink] },
};
}
/* tslint:disable */
export class iOSApplication implements iOSApplicationDefinition {
/* tslint:enable */
private _backgroundColor = majorVersion <= 12 || !UIColor.systemBackgroundColor ? UIColor.whiteColor : UIColor.systemBackgroundColor;
private _delegate: typeof UIApplicationDelegate;
private _window: UIWindow;
private _observers: Array<NotificationObserver>;
private _orientation: 'portrait' | 'landscape' | 'unknown';
private _rootView: View;
private _systemAppearance: 'light' | 'dark';
/* tslint:enable */
private _backgroundColor = majorVersion <= 12 || !UIColor.systemBackgroundColor ? UIColor.whiteColor : UIColor.systemBackgroundColor;
private _delegate: typeof UIApplicationDelegate;
private _window: UIWindow;
private _observers: Array<NotificationObserver>;
private _orientation: 'portrait' | 'landscape' | 'unknown';
private _rootView: View;
private _systemAppearance: 'light' | 'dark';
constructor() {
this._observers = new Array<NotificationObserver>();
this.addNotificationObserver(UIApplicationDidFinishLaunchingNotification, this.didFinishLaunchingWithOptions.bind(this));
this.addNotificationObserver(UIApplicationDidBecomeActiveNotification, this.didBecomeActive.bind(this));
this.addNotificationObserver(UIApplicationDidEnterBackgroundNotification, this.didEnterBackground.bind(this));
this.addNotificationObserver(UIApplicationWillTerminateNotification, this.willTerminate.bind(this));
this.addNotificationObserver(UIApplicationDidReceiveMemoryWarningNotification, this.didReceiveMemoryWarning.bind(this));
this.addNotificationObserver(UIApplicationDidChangeStatusBarOrientationNotification, this.didChangeStatusBarOrientation.bind(this));
}
constructor() {
this._observers = new Array<NotificationObserver>();
this.addNotificationObserver(UIApplicationDidFinishLaunchingNotification, this.didFinishLaunchingWithOptions.bind(this));
this.addNotificationObserver(UIApplicationDidBecomeActiveNotification, this.didBecomeActive.bind(this));
this.addNotificationObserver(UIApplicationDidEnterBackgroundNotification, this.didEnterBackground.bind(this));
this.addNotificationObserver(UIApplicationWillTerminateNotification, this.willTerminate.bind(this));
this.addNotificationObserver(UIApplicationDidReceiveMemoryWarningNotification, this.didReceiveMemoryWarning.bind(this));
this.addNotificationObserver(UIApplicationDidChangeStatusBarOrientationNotification, this.didChangeStatusBarOrientation.bind(this));
}
get orientation(): 'portrait' | 'landscape' | 'unknown' {
if (!this._orientation) {
const statusBarOrientation = UIApplication.sharedApplication.statusBarOrientation;
this._orientation = this.getOrientationValue(statusBarOrientation);
}
get orientation(): 'portrait' | 'landscape' | 'unknown' {
if (!this._orientation) {
const statusBarOrientation = UIApplication.sharedApplication.statusBarOrientation;
this._orientation = this.getOrientationValue(statusBarOrientation);
}
return this._orientation;
}
return this._orientation;
}
get rootController(): UIViewController {
return this._window.rootViewController;
}
get rootController(): UIViewController {
return this._window.rootViewController;
}
get systemAppearance(): 'light' | 'dark' | null {
// userInterfaceStyle is available on UITraitCollection since iOS 12.
if (majorVersion <= 11) {
return null;
}
get systemAppearance(): 'light' | 'dark' | null {
// userInterfaceStyle is available on UITraitCollection since iOS 12.
if (majorVersion <= 11) {
return null;
}
if (!this._systemAppearance) {
const userInterfaceStyle = this.rootController.traitCollection.userInterfaceStyle;
this._systemAppearance = getSystemAppearanceValue(userInterfaceStyle);
}
if (!this._systemAppearance) {
const userInterfaceStyle = this.rootController.traitCollection.userInterfaceStyle;
this._systemAppearance = getSystemAppearanceValue(userInterfaceStyle);
}
return this._systemAppearance;
}
return this._systemAppearance;
}
get nativeApp(): UIApplication {
return UIApplication.sharedApplication;
}
get nativeApp(): UIApplication {
return UIApplication.sharedApplication;
}
get window(): UIWindow {
return this._window;
}
get window(): UIWindow {
return this._window;
}
get delegate(): typeof UIApplicationDelegate {
return this._delegate;
}
get delegate(): typeof UIApplicationDelegate {
return this._delegate;
}
set delegate(value: typeof UIApplicationDelegate) {
if (this._delegate !== value) {
this._delegate = value;
}
}
set delegate(value: typeof UIApplicationDelegate) {
if (this._delegate !== value) {
this._delegate = value;
}
}
get rootView(): View {
return this._rootView;
}
get rootView(): View {
return this._rootView;
}
public addNotificationObserver(notificationName: string, onReceiveCallback: (notification: NSNotification) => void): NotificationObserver {
const observer = NotificationObserver.initWithCallback(onReceiveCallback);
NSNotificationCenter.defaultCenter.addObserverSelectorNameObject(observer, 'onReceive', notificationName, null);
this._observers.push(observer);
public addNotificationObserver(notificationName: string, onReceiveCallback: (notification: NSNotification) => void): NotificationObserver {
const observer = NotificationObserver.initWithCallback(onReceiveCallback);
NSNotificationCenter.defaultCenter.addObserverSelectorNameObject(observer, 'onReceive', notificationName, null);
this._observers.push(observer);
return observer;
}
return observer;
}
public removeNotificationObserver(observer: any, notificationName: string) {
const index = this._observers.indexOf(observer);
if (index >= 0) {
this._observers.splice(index, 1);
NSNotificationCenter.defaultCenter.removeObserverNameObject(observer, notificationName, null);
}
}
public removeNotificationObserver(observer: any, notificationName: string) {
const index = this._observers.indexOf(observer);
if (index >= 0) {
this._observers.splice(index, 1);
NSNotificationCenter.defaultCenter.removeObserverNameObject(observer, notificationName, null);
}
}
@profile
private didFinishLaunchingWithOptions(notification: NSNotification) {
if (!displayedOnce) {
displayedLinkTarget = CADisplayLinkTarget.new();
displayedLink = CADisplayLink.displayLinkWithTargetSelector(displayedLinkTarget, 'onDisplayed');
displayedLink.addToRunLoopForMode(NSRunLoop.mainRunLoop, NSDefaultRunLoopMode);
displayedLink.addToRunLoopForMode(NSRunLoop.mainRunLoop, UITrackingRunLoopMode);
}
@profile
private didFinishLaunchingWithOptions(notification: NSNotification) {
if (!displayedOnce) {
displayedLinkTarget = CADisplayLinkTarget.new();
displayedLink = CADisplayLink.displayLinkWithTargetSelector(displayedLinkTarget, 'onDisplayed');
displayedLink.addToRunLoopForMode(NSRunLoop.mainRunLoop, NSDefaultRunLoopMode);
displayedLink.addToRunLoopForMode(NSRunLoop.mainRunLoop, UITrackingRunLoopMode);
}
this._window = UIWindow.alloc().initWithFrame(UIScreen.mainScreen.bounds);
// TODO: Expose Window module so that it can we styled from XML & CSS
this._window.backgroundColor = this._backgroundColor;
this._window = UIWindow.alloc().initWithFrame(UIScreen.mainScreen.bounds);
// TODO: Expose Window module so that it can we styled from XML & CSS
this._window.backgroundColor = this._backgroundColor;
this.notifyAppStarted(notification);
}
this.notifyAppStarted(notification);
}
public notifyAppStarted(notification?: NSNotification) {
const args: LaunchEventData = {
eventName: launchEvent,
object: this,
ios: (notification && notification.userInfo && notification.userInfo.objectForKey('UIApplicationLaunchOptionsLocalNotificationKey')) || null,
};
public notifyAppStarted(notification?: NSNotification) {
const args: LaunchEventData = {
eventName: launchEvent,
object: this,
ios: (notification && notification.userInfo && notification.userInfo.objectForKey('UIApplicationLaunchOptionsLocalNotificationKey')) || null,
};
notify(args);
notify(<LoadAppCSSEventData>{
eventName: 'loadAppCss',
object: <any>this,
cssFile: getCssFileName(),
});
notify(args);
notify(<LoadAppCSSEventData>{
eventName: 'loadAppCss',
object: <any>this,
cssFile: getCssFileName(),
});
// this._window will be undefined when NS app is embedded in a native one
if (this._window) {
this.setWindowContent(args.root);
} else {
this._window = UIApplication.sharedApplication.delegate.window;
}
}
// this._window will be undefined when NS app is embedded in a native one
if (this._window) {
this.setWindowContent(args.root);
} else {
this._window = UIApplication.sharedApplication.delegate.window;
}
}
@profile
private didBecomeActive(notification: NSNotification) {
const ios = UIApplication.sharedApplication;
const object = this;
notify(<ApplicationEventData>{ eventName: resumeEvent, object, ios });
const rootView = this._rootView;
if (rootView && !rootView.isLoaded) {
rootView.callLoaded();
}
}
@profile
private didBecomeActive(notification: NSNotification) {
const ios = UIApplication.sharedApplication;
const object = this;
notify(<ApplicationEventData>{ eventName: resumeEvent, object, ios });
const rootView = this._rootView;
if (rootView && !rootView.isLoaded) {
rootView.callLoaded();
}
}
private didEnterBackground(notification: NSNotification) {
notify(<ApplicationEventData>{
eventName: suspendEvent,
object: this,
ios: UIApplication.sharedApplication,
});
const rootView = this._rootView;
if (rootView && rootView.isLoaded) {
rootView.callUnloaded();
}
}
private didEnterBackground(notification: NSNotification) {
notify(<ApplicationEventData>{
eventName: suspendEvent,
object: this,
ios: UIApplication.sharedApplication,
});
const rootView = this._rootView;
if (rootView && rootView.isLoaded) {
rootView.callUnloaded();
}
}
private willTerminate(notification: NSNotification) {
notify(<ApplicationEventData>{
eventName: exitEvent,
object: this,
ios: UIApplication.sharedApplication,
});
const rootView = this._rootView;
if (rootView && rootView.isLoaded) {
rootView.callUnloaded();
}
}
private willTerminate(notification: NSNotification) {
notify(<ApplicationEventData>{
eventName: exitEvent,
object: this,
ios: UIApplication.sharedApplication,
});
const rootView = this._rootView;
if (rootView && rootView.isLoaded) {
rootView.callUnloaded();
}
}
private didChangeStatusBarOrientation(notification: NSNotification) {
const statusBarOrientation = UIApplication.sharedApplication.statusBarOrientation;
const newOrientation = this.getOrientationValue(statusBarOrientation);
private didChangeStatusBarOrientation(notification: NSNotification) {
const statusBarOrientation = UIApplication.sharedApplication.statusBarOrientation;
const newOrientation = this.getOrientationValue(statusBarOrientation);
if (this._orientation !== newOrientation) {
this._orientation = newOrientation;
orientationChanged(getRootView(), newOrientation);
if (this._orientation !== newOrientation) {
this._orientation = newOrientation;
orientationChanged(getRootView(), newOrientation);
notify(<OrientationChangedEventData>{
eventName: orientationChangedEvent,
ios: this,
newValue: this._orientation,
object: this,
});
}
}
notify(<OrientationChangedEventData>{
eventName: orientationChangedEvent,
ios: this,
newValue: this._orientation,
object: this,
});
}
}
private didReceiveMemoryWarning(notification: NSNotification) {
notify(<ApplicationEventData>{
eventName: lowMemoryEvent,
object: this,
ios: UIApplication.sharedApplication,
});
}
private didReceiveMemoryWarning(notification: NSNotification) {
notify(<ApplicationEventData>{
eventName: lowMemoryEvent,
object: this,
ios: UIApplication.sharedApplication,
});
}
private getOrientationValue(orientation: number): 'portrait' | 'landscape' | 'unknown' {
switch (orientation) {
case UIInterfaceOrientation.LandscapeRight:
case UIInterfaceOrientation.LandscapeLeft:
return 'landscape';
case UIInterfaceOrientation.PortraitUpsideDown:
case UIInterfaceOrientation.Portrait:
return 'portrait';
case UIInterfaceOrientation.Unknown:
return 'unknown';
}
}
private getOrientationValue(orientation: number): 'portrait' | 'landscape' | 'unknown' {
switch (orientation) {
case UIInterfaceOrientation.LandscapeRight:
case UIInterfaceOrientation.LandscapeLeft:
return 'landscape';
case UIInterfaceOrientation.PortraitUpsideDown:
case UIInterfaceOrientation.Portrait:
return 'portrait';
case UIInterfaceOrientation.Unknown:
return 'unknown';
}
}
public _onLivesync(context?: ModuleContext): void {
// Handle application root module
const isAppRootModuleChanged = context && context.path && context.path.includes(getMainEntry().moduleName) && context.type !== 'style';
public _onLivesync(context?: ModuleContext): void {
// Handle application root module
const isAppRootModuleChanged = context && context.path && context.path.includes(getMainEntry().moduleName) && context.type !== 'style';
// Set window content when:
// + Application root module is changed
// + View did not handle the change
// Note:
// The case when neither app root module is changed, nor livesync is handled on View,
// then changes will not apply until navigate forward to the module.
if (isAppRootModuleChanged || (this._rootView && !this._rootView._onLivesync(context))) {
this.setWindowContent();
}
}
// Set window content when:
// + Application root module is changed
// + View did not handle the change
// Note:
// The case when neither app root module is changed, nor livesync is handled on View,
// then changes will not apply until navigate forward to the module.
if (isAppRootModuleChanged || (this._rootView && !this._rootView._onLivesync(context))) {
this.setWindowContent();
}
}
public setWindowContent(view?: View): void {
if (this._rootView) {
// if we already have a root view, we reset it.
this._rootView._onRootViewReset();
}
const rootView = createRootView(view);
const controller = getViewController(rootView);
public setWindowContent(view?: View): void {
if (this._rootView) {
// if we already have a root view, we reset it.
this._rootView._onRootViewReset();
}
const rootView = createRootView(view);
const controller = getViewController(rootView);
this._rootView = rootView;
this._rootView = rootView;
// setup view as styleScopeHost
rootView._setupAsRootView({});
// setup view as styleScopeHost
rootView._setupAsRootView({});
setViewControllerView(rootView);
setViewControllerView(rootView);
const haveController = this._window.rootViewController !== null;
this._window.rootViewController = controller;
const haveController = this._window.rootViewController !== null;
this._window.rootViewController = controller;
setRootViewsSystemAppearanceCssClass(rootView);
setRootViewsSystemAppearanceCssClass(rootView);
if (!haveController) {
this._window.makeKeyAndVisible();
}
if (!haveController) {
this._window.makeKeyAndVisible();
}
rootView.on(IOSHelper.traitCollectionColorAppearanceChangedEvent, () => {
const userInterfaceStyle = controller.traitCollection.userInterfaceStyle;
const newSystemAppearance = getSystemAppearanceValue(userInterfaceStyle);
rootView.on(IOSHelper.traitCollectionColorAppearanceChangedEvent, () => {
const userInterfaceStyle = controller.traitCollection.userInterfaceStyle;
const newSystemAppearance = getSystemAppearanceValue(userInterfaceStyle);
if (this._systemAppearance !== newSystemAppearance) {
this._systemAppearance = newSystemAppearance;
systemAppearanceChanged(rootView, newSystemAppearance);
if (this._systemAppearance !== newSystemAppearance) {
this._systemAppearance = newSystemAppearance;
systemAppearanceChanged(rootView, newSystemAppearance);
notify(<SystemAppearanceChangedEventData>{
eventName: systemAppearanceChangedEvent,
ios: this,
newValue: this._systemAppearance,
object: this,
});
}
});
}
notify(<SystemAppearanceChangedEventData>{
eventName: systemAppearanceChangedEvent,
ios: this,
newValue: this._systemAppearance,
object: this,
});
}
});
}
}
/* tslint:disable */
@@ -343,179 +343,179 @@ setApplication(iosApp);
// attach on global, so it can be overwritten in NativeScript Angular
(<any>global).__onLiveSyncCore = function (context?: ModuleContext) {
iosApp._onLivesync(context);
iosApp._onLivesync(context);
};
let mainEntry: NavigationEntry;
function createRootView(v?: View) {
let rootView = v;
if (!rootView) {
// try to navigate to the mainEntry (if specified)
if (!mainEntry) {
throw new Error('Main entry is missing. App cannot be started. Verify app bootstrap.');
} else {
rootView = Builder.createViewFromEntry(mainEntry);
}
}
let rootView = v;
if (!rootView) {
// try to navigate to the mainEntry (if specified)
if (!mainEntry) {
throw new Error('Main entry is missing. App cannot be started. Verify app bootstrap.');
} else {
rootView = Builder.createViewFromEntry(mainEntry);
}
}
setRootViewsCssClasses(rootView);
setRootViewsCssClasses(rootView);
return rootView;
return rootView;
}
export function getMainEntry() {
return mainEntry;
return mainEntry;
}
export function getRootView() {
return iosApp.rootView;
return iosApp.rootView;
}
let started: boolean = false;
export function run(entry?: string | NavigationEntry) {
mainEntry = typeof entry === 'string' ? { moduleName: entry } : entry;
started = true;
mainEntry = typeof entry === 'string' ? { moduleName: entry } : entry;
started = true;
if (!iosApp.nativeApp) {
// Normal NativeScript app will need UIApplicationMain.
UIApplicationMain(0, null, null, iosApp && iosApp.delegate ? NSStringFromClass(<any>iosApp.delegate) : NSStringFromClass(Responder));
} else {
// TODO: this rootView should be held alive until rootController dismissViewController is called.
const rootView = createRootView();
if (rootView) {
// Attach to the existing iOS app
const window = iosApp.nativeApp.keyWindow || (iosApp.nativeApp.windows.count > 0 && iosApp.nativeApp.windows[0]);
if (window) {
const rootController = window.rootViewController;
if (rootController) {
const controller = getViewController(rootView);
rootView._setupAsRootView({});
let embedderDelegate = NativeScriptEmbedder.sharedInstance().delegate;
if (embedderDelegate) {
embedderDelegate.presentNativeScriptApp(controller);
} else {
let visibleVC = getVisibleViewController(rootController);
visibleVC.presentViewControllerAnimatedCompletion(controller, true, null);
}
if (!iosApp.nativeApp) {
// Normal NativeScript app will need UIApplicationMain.
UIApplicationMain(0, null, null, iosApp && iosApp.delegate ? NSStringFromClass(<any>iosApp.delegate) : NSStringFromClass(Responder));
} else {
// TODO: this rootView should be held alive until rootController dismissViewController is called.
const rootView = createRootView();
if (rootView) {
// Attach to the existing iOS app
const window = iosApp.nativeApp.keyWindow || (iosApp.nativeApp.windows.count > 0 && iosApp.nativeApp.windows[0]);
if (window) {
const rootController = window.rootViewController;
if (rootController) {
const controller = getViewController(rootView);
rootView._setupAsRootView({});
let embedderDelegate = NativeScriptEmbedder.sharedInstance().delegate;
if (embedderDelegate) {
embedderDelegate.presentNativeScriptApp(controller);
} else {
let visibleVC = getVisibleViewController(rootController);
visibleVC.presentViewControllerAnimatedCompletion(controller, true, null);
}
// Mind root view CSS classes in future work
// on embedding NativeScript applications
setRootViewsSystemAppearanceCssClass(rootView);
rootView.on(IOSHelper.traitCollectionColorAppearanceChangedEvent, () => {
const userInterfaceStyle = controller.traitCollection.userInterfaceStyle;
const newSystemAppearance = getSystemAppearanceValue(userInterfaceStyle);
// Mind root view CSS classes in future work
// on embedding NativeScript applications
setRootViewsSystemAppearanceCssClass(rootView);
rootView.on(IOSHelper.traitCollectionColorAppearanceChangedEvent, () => {
const userInterfaceStyle = controller.traitCollection.userInterfaceStyle;
const newSystemAppearance = getSystemAppearanceValue(userInterfaceStyle);
if (this._systemAppearance !== newSystemAppearance) {
this._systemAppearance = newSystemAppearance;
if (this._systemAppearance !== newSystemAppearance) {
this._systemAppearance = newSystemAppearance;
notify(<SystemAppearanceChangedEventData>{
eventName: systemAppearanceChangedEvent,
ios: this,
newValue: this._systemAppearance,
object: this,
});
}
});
iosApp.notifyAppStarted();
}
}
}
}
notify(<SystemAppearanceChangedEventData>{
eventName: systemAppearanceChangedEvent,
ios: this,
newValue: this._systemAppearance,
object: this,
});
}
});
iosApp.notifyAppStarted();
}
}
}
}
}
export function addCss(cssText: string, attributeScoped?: boolean): void {
notify(<CssChangedEventData>{
eventName: 'cssChanged',
object: <any>iosApp,
cssText: cssText,
});
if (!attributeScoped) {
const rootView = getRootView();
if (rootView) {
rootView._onCssStateChange();
}
}
notify(<CssChangedEventData>{
eventName: 'cssChanged',
object: <any>iosApp,
cssText: cssText,
});
if (!attributeScoped) {
const rootView = getRootView();
if (rootView) {
rootView._onCssStateChange();
}
}
}
export function _resetRootView(entry?: NavigationEntry | string) {
mainEntry = typeof entry === 'string' ? { moduleName: entry } : entry;
iosApp.setWindowContent();
mainEntry = typeof entry === 'string' ? { moduleName: entry } : entry;
iosApp.setWindowContent();
}
export function getNativeApplication(): UIApplication {
return iosApp.nativeApp;
return iosApp.nativeApp;
}
function getSystemAppearanceValue(userInterfaceStyle: number): 'dark' | 'light' {
switch (userInterfaceStyle) {
case UIUserInterfaceStyle.Dark:
return 'dark';
case UIUserInterfaceStyle.Light:
case UIUserInterfaceStyle.Unspecified:
return 'light';
}
switch (userInterfaceStyle) {
case UIUserInterfaceStyle.Dark:
return 'dark';
case UIUserInterfaceStyle.Light:
case UIUserInterfaceStyle.Unspecified:
return 'light';
}
}
function getViewController(rootView: View): UIViewController {
let viewController: UIViewController = rootView.viewController || rootView.ios;
let viewController: UIViewController = rootView.viewController || rootView.ios;
if (!(viewController instanceof UIViewController)) {
// We set UILayoutViewController dynamically to the root view if it doesn't have a view controller
// At the moment the root view doesn't have its native view created. We set it in the setViewControllerView func
viewController = IOSHelper.UILayoutViewController.initWithOwner(new WeakRef(rootView)) as UIViewController;
rootView.viewController = viewController;
}
if (!(viewController instanceof UIViewController)) {
// We set UILayoutViewController dynamically to the root view if it doesn't have a view controller
// At the moment the root view doesn't have its native view created. We set it in the setViewControllerView func
viewController = IOSHelper.UILayoutViewController.initWithOwner(new WeakRef(rootView)) as UIViewController;
rootView.viewController = viewController;
}
return viewController;
return viewController;
}
function setViewControllerView(view: View): void {
const viewController: UIViewController = view.viewController || view.ios;
const nativeView = view.ios || view.nativeViewProtected;
const viewController: UIViewController = view.viewController || view.ios;
const nativeView = view.ios || view.nativeViewProtected;
if (!nativeView || !viewController) {
throw new Error('Root should be either UIViewController or UIView');
}
if (!nativeView || !viewController) {
throw new Error('Root should be either UIViewController or UIView');
}
if (viewController instanceof IOSHelper.UILayoutViewController) {
viewController.view.addSubview(nativeView);
}
if (viewController instanceof IOSHelper.UILayoutViewController) {
viewController.view.addSubview(nativeView);
}
}
function setRootViewsCssClasses(rootView: View): void {
const deviceType = Device.deviceType.toLowerCase();
const deviceType = Device.deviceType.toLowerCase();
pushToSystemCssClasses(`${CLASS_PREFIX}${IOS_PLATFORM}`);
pushToSystemCssClasses(`${CLASS_PREFIX}${deviceType}`);
pushToSystemCssClasses(`${CLASS_PREFIX}${iosApp.orientation}`);
pushToSystemCssClasses(`${CLASS_PREFIX}${IOS_PLATFORM}`);
pushToSystemCssClasses(`${CLASS_PREFIX}${deviceType}`);
pushToSystemCssClasses(`${CLASS_PREFIX}${iosApp.orientation}`);
rootView.cssClasses.add(ROOT_VIEW_CSS_CLASS);
const rootViewCssClasses = getSystemCssClasses();
rootViewCssClasses.forEach((c) => rootView.cssClasses.add(c));
rootView.cssClasses.add(ROOT_VIEW_CSS_CLASS);
const rootViewCssClasses = getSystemCssClasses();
rootViewCssClasses.forEach((c) => rootView.cssClasses.add(c));
}
function setRootViewsSystemAppearanceCssClass(rootView: View): void {
if (majorVersion >= 13) {
const systemAppearanceCssClass = `${CLASS_PREFIX}${iosApp.systemAppearance}`;
pushToSystemCssClasses(systemAppearanceCssClass);
rootView.cssClasses.add(systemAppearanceCssClass);
}
if (majorVersion >= 13) {
const systemAppearanceCssClass = `${CLASS_PREFIX}${iosApp.systemAppearance}`;
pushToSystemCssClasses(systemAppearanceCssClass);
rootView.cssClasses.add(systemAppearanceCssClass);
}
}
export function orientation(): 'portrait' | 'landscape' | 'unknown' {
return iosApp.orientation;
return iosApp.orientation;
}
export function systemAppearance(): 'dark' | 'light' {
return iosApp.systemAppearance;
return iosApp.systemAppearance;
}
global.__onLiveSync = function __onLiveSync(context?: ModuleContext) {
if (!started) {
return;
}
if (!started) {
return;
}
const rootView = getRootView();
livesync(rootView, context);
const rootView = getRootView();
livesync(rootView, context);
};