Merge branch 'frame_nav_events' of github.com:Akylas/NativeScript

# Conflicts:
#	apps/automated/src/test-runner.ts
#	packages/core/css/parser.ts
#	packages/core/global-types.d.ts
#	packages/core/ui/bottom-navigation/index.android.ts
#	packages/core/ui/styling/style-scope.ts
#	packages/core/ui/tabs/index.android.ts
#	packages/core/ui/tabs/index.ios.ts
This commit is contained in:
Martin Guillon
2020-11-12 10:02:51 +01:00
174 changed files with 1979 additions and 1723 deletions

View File

@ -4,15 +4,27 @@
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module",
"project": "./tsconfig.json"
"project": ["packages/core/tsconfig.json", "packages/webpack/tsconfig.json"]
},
"ignorePatterns": ["**/*"],
"plugins": ["@typescript-eslint", "@nrwl/nx"],
"extends": ["eslint:recommended", "plugin:@typescript-eslint/eslint-recommended", "plugin:@typescript-eslint/recommended", "prettier", "prettier/@typescript-eslint"],
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended", "prettier", "prettier/@typescript-eslint"],
"rules": {
"@typescript-eslint/explicit-member-accessibility": "off",
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/no-parameter-properties": "off",
"@typescript-eslint/no-empty-function": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/no-namespace": "off",
"@typescript-eslint/ban-types": "off",
"@typescript-eslint/ban-ts-comment": "off",
"@typescript-eslint/no-this-alias": "off",
"@typescript-eslint/no-empty-interface": "off",
"@typescript-eslint/triple-slash-reference": "off",
"no-prototype-builtins": "off",
"no-inner-declarations": "off",
"no-constant-condition": "off",
"@nrwl/nx/enforce-module-boundaries": [
"error",
{

View File

@ -309,11 +309,10 @@ export function isRunningOnEmulator(): boolean {
if (tempTest) {
allTests[singleTest] = tempTest;
} else {
console.log("Test does not exist", singleTest);
console.log('Test does not exist', singleTest);
}
}
const testsSuitesWithLongDelay = {
HTTP: 15 * 1000,
};
@ -442,6 +441,15 @@ function log(): void {
TKUnit.write(testsName + ' COMPLETED for ' + duration.toFixed(2) + ' BACKSTACK DEPTH: ' + Frame.topmost().backStack.length, Trace.messageType.info);
}
function getAllProperties(obj: any) {
let properties = new Set<string>();
let currentObj = obj;
do {
Object.getOwnPropertyNames(currentObj).map((item) => properties.add(item));
} while ((currentObj = Object.getPrototypeOf(currentObj)) && currentObj !== Object.prototype);
return [...properties.keys()];
}
let testsSelector: string;
export function runAll(testSelector?: string) {
testsSelector = testSelector;
@ -496,7 +504,7 @@ export function runAll(testSelector?: string) {
testsQueue.push(new TestInfo(test.setUpModule, test));
}
for (const testName in test) {
for (const testName of getAllProperties(test)) {
if (singleTestName && singleTestName !== testName.toLowerCase()) {
continue;
}

View File

@ -1,8 +1,8 @@
import * as TKUnit from '../../tk-unit';
import * as testModule from '../../ui-test';
import * as datePickerTestsNative from './date-picker-tests-native';
import * as color from '@nativescript/core/color';
import * as platform from '@nativescript/core/platform';
import { Color } from '@nativescript/core';
// >> date-picker-require
import * as datePickerModule from '@nativescript/core/ui/date-picker';
@ -77,10 +77,13 @@ export class DatePickerTest extends testModule.UITest<datePickerModule.DatePicke
public test_set_color() {
if (platform.Device.os === platform.platformNames.ios) {
this.testView.color = new color.Color('red');
const SUPPORT_TEXT_COLOR = parseFloat(platform.Device.osVersion) < 14.0;
if (SUPPORT_TEXT_COLOR) {
this.testView.color = new Color('red');
TKUnit.assertEqual(this.testView.color.ios.CGColor, this.testView.ios.valueForKey('textColor').CGColor, 'datePicker.color');
}
}
}
public test_WhenCreated_YearIsCurrentYear() {
const actualValue = this.testView.year;

View File

@ -608,7 +608,7 @@ export class ListViewTest extends UITest<ListView> {
if (isAndroid) {
// simulates Angular way of removing views
(<any>listView)._realizedItems.forEach((view, nativeView, map) => {
(<any>listView)._realizedItems.forEach(({ view }, nativeView, map) => {
//console.log("view: " + view);
listView._removeView(view);
});
@ -902,6 +902,29 @@ export class ListViewTest extends UITest<ListView> {
TKUnit.assertEqual(secondNativeElementText, 'green', 'second element text');
}
public test_ItemTemplateSelector_DoesNotThrowWhenItemsChangeMidRender() {
let listView = this.testView;
listView.height = 200;
listView.itemTemplates = this._itemTemplatesString;
listView.itemTemplateSelector = "age === 0 ? 'red' : 'green'";
listView.items = ListViewTest.generateItemsForMultipleTemplatesTests(4);
listView.items[0].age = 0;
listView.once('itemLoading', () => {
if (listView.items && listView.items.length) {
listView.items[0].age = listView.items[0].age !== 0 ? 0 : 1;
}
});
listView.refresh();
TKUnit.wait(0.1);
listView.scrollToIndex(1);
TKUnit.wait(0.1);
listView.scrollToIndex(2);
TKUnit.wait(0.1);
listView.scrollToIndex(3);
TKUnit.wait(0.1);
}
public test_ItemTemplateSelector_TestVirtualization() {
let listView = this.testView;
listView.height = 300;

View File

@ -1,9 +1,9 @@
import * as TKUnit from '../../tk-unit';
import * as testModule from '../../ui-test';
import * as timePickerTestsNative from './time-picker-tests-native';
import * as color from '@nativescript/core/color';
import * as platform from '@nativescript/core/platform';
import * as helper from '../../ui-helper';
import { Color } from '@nativescript/core';
// >> require-time-picker
import * as timePickerModule from '@nativescript/core/ui/time-picker';
@ -50,10 +50,13 @@ export class TimePickerTest extends testModule.UITest<timePickerModule.TimePicke
// Supported in iOS only.
public test_set_color() {
if (platform.Device.os === platform.platformNames.ios) {
this.testView.color = new color.Color('red');
const SUPPORT_TEXT_COLOR = parseFloat(platform.Device.osVersion) < 14.0;
if (SUPPORT_TEXT_COLOR) {
this.testView.color = new Color('red');
TKUnit.assertEqual(this.testView.color.ios.CGColor, this.testView.ios.valueForKey('textColor').CGColor, 'timePicker.color');
}
}
}
public test_WhenCreated_MinuteIntervalIs1() {
let actualValue = this.testView.minuteInterval;

View File

@ -278,8 +278,8 @@ describe('css', () => {
const cssparser = new CSS3Parser(themeCoreLightIos);
const stylesheet = cssparser.tokenize();
let original = themeCoreLightIos.replace(/\/\*([^\/]|\/[^\*])*\*\//g, '').replace(/\n/g, ' ');
let roundtrip = stylesheet
const original = themeCoreLightIos.replace(/\/\*([^\/]|\/[^\*])*\*\//g, '').replace(/\n/g, ' ');
const roundtrip = stylesheet
.map((m) => {
if (!m) {
return '';
@ -293,8 +293,8 @@ describe('css', () => {
})
.join('');
let lastIndex = Math.min(original.length, roundtrip.length);
for (var i = 0; i < lastIndex; i++) {
const lastIndex = Math.min(original.length, roundtrip.length);
for (let i = 0; i < lastIndex; i++) {
if (original[i] !== roundtrip[i]) {
assert.equal(roundtrip.substr(i, 50), original.substr(i, 50), 'Round-tripped CSS string differ at index: ' + i);
}

View File

@ -5,7 +5,7 @@ describe('observable', () => {
describe('once', () => {
let observable: Observable;
let handler: () => void;
let callCount: number = 0;
let callCount = 0;
beforeEach('create handlers', () => {
handler = function () {

View File

@ -21,30 +21,30 @@ describe('ui', () => {
);
});
function create(css: string, source: string = 'css-selectors.ts@test'): { rules: selector.RuleSet[]; map: selector.SelectorsMap<any> } {
let parse = parser.parse(css, { source });
let rulesAst = parse.stylesheet.rules.filter((n) => n.type === 'rule');
let rules = selector.fromAstNodes(rulesAst);
let map = new selector.SelectorsMap(rules);
function create(css: string, source = 'css-selectors.ts@test'): { rules: selector.RuleSet[]; map: selector.SelectorsMap<any> } {
const parse = parser.parse(css, { source });
const rulesAst = parse.stylesheet.rules.filter((n) => n.type === 'rule');
const rules = selector.fromAstNodes(rulesAst);
const map = new selector.SelectorsMap(rules);
return { rules, map };
}
function createOne(css: string, source: string = 'css-selectors.ts@test'): selector.RuleSet {
let { rules } = create(css, source);
function createOne(css: string, source = 'css-selectors.ts@test'): selector.RuleSet {
const { rules } = create(css, source);
assert.equal(rules.length, 1);
return rules[0];
}
it('single selector', () => {
let rule = createOne(`* { color: red; }`);
const rule = createOne(`* { color: red; }`);
assert.isTrue(rule.selectors[0].match({ cssType: 'button' }));
assert.isTrue(rule.selectors[0].match({ cssType: 'image' }));
});
it('two selectors', () => {
let rule = createOne(`button, image { color: red; }`);
const rule = createOne(`button, image { color: red; }`);
assert.isTrue(rule.selectors[0].match({ cssType: 'button' }));
assert.isTrue(rule.selectors[1].match({ cssType: 'image' }));
assert.isFalse(rule.selectors[0].match({ cssType: 'stacklayout' }));
@ -52,24 +52,24 @@ describe('ui', () => {
});
it('narrow selection', () => {
let { map } = create(`
const { map } = create(`
.login { color: blue; }
button { color: red; }
image { color: green; }
`);
let buttonQuerry = map.query({ cssType: 'button' }).selectors;
const buttonQuerry = map.query({ cssType: 'button' }).selectors;
assert.equal(buttonQuerry.length, 1);
assert.includeDeepMembers(buttonQuerry[0].ruleset.declarations, [{ property: 'color', value: 'red' }]);
let imageQuerry = map.query({ cssType: 'image', cssClasses: new Set(['login']) }).selectors;
const imageQuerry = map.query({ cssType: 'image', cssClasses: new Set(['login']) }).selectors;
assert.equal(imageQuerry.length, 2);
// Note class before type
assert.includeDeepMembers(imageQuerry[0].ruleset.declarations, [{ property: 'color', value: 'green' }]);
assert.includeDeepMembers(imageQuerry[1].ruleset.declarations, [{ property: 'color', value: 'blue' }]);
});
let positiveMatches = {
const positiveMatches = {
'*': (view) => true,
type: (view) => view.cssType === 'type',
'#id': (view) => view.id === 'id',
@ -79,7 +79,7 @@ describe('ui', () => {
"[src2='src-value']": (view) => view['src2'] === 'src-value',
};
let positivelyMatchingView = {
const positivelyMatchingView = {
cssType: 'type',
id: 'id',
cssClasses: new Set(['class']),
@ -88,7 +88,7 @@ describe('ui', () => {
src2: 'src-value',
};
let negativelyMatchingView = {
const negativelyMatchingView = {
cssType: 'nottype',
id: 'notid',
cssClasses: new Set(['notclass']),
@ -98,9 +98,9 @@ describe('ui', () => {
};
it('simple selectors match', () => {
for (let sel in positiveMatches) {
let css = sel + ' { color: red; }';
let rule = createOne(css);
for (const sel in positiveMatches) {
const css = sel + ' { color: red; }';
const rule = createOne(css);
assert.isTrue(rule.selectors[0].match(positivelyMatchingView), 'Expected successful match for: ' + css);
if (sel !== '*') {
assert.isFalse(rule.selectors[0].match(negativelyMatchingView), 'Expected match failure for: ' + css);
@ -109,11 +109,11 @@ describe('ui', () => {
});
it('two selector sequence positive match', () => {
for (let firstStr in positiveMatches) {
for (let secondStr in positiveMatches) {
for (const firstStr in positiveMatches) {
for (const secondStr in positiveMatches) {
if (secondStr !== firstStr && secondStr !== '*' && secondStr !== 'type') {
let css = firstStr + secondStr + ' { color: red; }';
let rule = createOne(css);
const css = firstStr + secondStr + ' { color: red; }';
const rule = createOne(css);
assert.isTrue(rule.selectors[0].match(positivelyMatchingView), 'Expected successful match for: ' + css);
if (firstStr !== '*') {
assert.isFalse(rule.selectors[0].match(negativelyMatchingView), 'Expected match failure for: ' + css);
@ -124,7 +124,7 @@ describe('ui', () => {
});
it('direct parent combinator', () => {
let rule = createOne(`listview > item:selected { color: red; }`);
const rule = createOne(`listview > item:selected { color: red; }`);
assert.isTrue(
rule.selectors[0].match({
cssType: 'item',
@ -151,7 +151,7 @@ describe('ui', () => {
});
it('ancestor combinator', () => {
let rule = createOne(`listview item:selected { color: red; }`);
const rule = createOne(`listview item:selected { color: red; }`);
assert.isTrue(
rule.selectors[0].match({
cssType: 'item',
@ -191,8 +191,8 @@ describe('ui', () => {
});
it('backtracking css selector', () => {
let sel = createOne(`a>b c { color: red; }`).selectors[0];
let child = {
const sel = createOne(`a>b c { color: red; }`).selectors[0];
const child = {
cssType: 'c',
parent: {
cssType: 'b',
@ -216,7 +216,7 @@ describe('ui', () => {
}
it('simple query match', () => {
let { map } = create(`list grid[promotion] button:highlighted { color: red; }`);
const { map } = create(`list grid[promotion] button:highlighted { color: red; }`);
let list, grid, button;
@ -235,16 +235,16 @@ describe('ui', () => {
},
};
let match = map.query(button);
const match = map.query(button);
assert.equal(match.selectors.length, 1, 'Expected match to have one selector.');
let expected = new Map<selector.Node, selector.Changes>().set(grid, { attributes: new Set(['promotion']) }).set(button, { pseudoClasses: new Set(['highlighted']) });
const expected = new Map<selector.Node, selector.Changes>().set(grid, { attributes: new Set(['promotion']) }).set(button, { pseudoClasses: new Set(['highlighted']) });
assert.deepEqual(match.changeMap, expected);
});
it('query match one child group', () => {
let { map } = create(`#prod[special] > gridlayout { color: red; }`);
const { map } = create(`#prod[special] > gridlayout { color: red; }`);
let gridlayout, prod;
gridlayout = {
@ -257,15 +257,15 @@ describe('ui', () => {
},
};
let match = map.query(gridlayout);
const match = map.query(gridlayout);
assert.equal(match.selectors.length, 1, 'Expected match to have one selector.');
let expected = new Map<selector.Node, selector.Changes>().set(prod, { attributes: new Set(['special']) });
const expected = new Map<selector.Node, selector.Changes>().set(prod, { attributes: new Set(['special']) });
assert.deepEqual(match.changeMap, expected);
});
it('query match one sibling group (deepEqual does not compare Map?)', () => {
let { map } = create(`list button:highlighted+button:disabled { color: red; }`);
const { map } = create(`list button:highlighted+button:disabled { color: red; }`);
let list, button, disabledButton;
list = {
@ -289,10 +289,10 @@ describe('ui', () => {
parent: list,
};
let match = map.query(disabledButton);
const match = map.query(disabledButton);
assert.equal(match.selectors.length, 1, 'Expected match to have one selector.');
let expected = new Map<selector.Node, selector.Changes>().set(disabledButton, { pseudoClasses: new Set(['disabled']) }).set(button, { pseudoClasses: new Set(['highlighted']) });
const expected = new Map<selector.Node, selector.Changes>().set(disabledButton, { pseudoClasses: new Set(['disabled']) }).set(button, { pseudoClasses: new Set(['highlighted']) });
assert.deepEqual(match.changeMap, expected);
});

View File

@ -1,12 +1,18 @@
import { queueMacrotask } from '../utils/macrotask-scheduler';
import { FPSCallback } from '../fps-meter/fps-native';
import { getTimeInFrameBase } from './animation-native';
import { Trace } from 'trace';
export interface FrameRequestCallback {
(time: number): void;
}
type AnimationFrameCallbacks = { [key: string]: FrameRequestCallback };
let animationId = 0;
let nextFrameAnimationCallbacks: { [key: string]: FrameRequestCallback } = {};
let currentFrameAnimationCallbacks: AnimationFrameCallbacks = {}; // requests that were scheduled in this frame and must be called ASAP
let currentFrameScheduled = false;
let nextFrameAnimationCallbacks: AnimationFrameCallbacks = {}; // requests there were scheduled in another request and must be called in the next frame
let shouldStop = true;
let inAnimationFrame = false;
let fpsCallback: FPSCallback;
@ -23,33 +29,59 @@ function ensureNative() {
fpsCallback = new FPSCallback(doFrame);
}
function callAnimationCallbacks(thisFrameCbs: AnimationFrameCallbacks, frameTime: number): void {
inAnimationFrame = true;
for (const animationId in thisFrameCbs) {
if (thisFrameCbs[animationId]) {
try {
thisFrameCbs[animationId](frameTime);
} catch (err) {
const msg = err ? err.stack || err : err;
Trace.write(`Error in requestAnimationFrame: ${msg}`, Trace.categories.Error, Trace.messageType.error);
}
}
}
inAnimationFrame = false;
}
function doCurrentFrame() {
// if we're not getting accurate frame times
// set last frame time as the current time
if (!fpsCallback || !fpsCallback.running) {
lastFrameTime = getTimeInFrameBase();
}
currentFrameScheduled = false;
const thisFrameCbs = currentFrameAnimationCallbacks;
currentFrameAnimationCallbacks = {};
callAnimationCallbacks(thisFrameCbs, lastFrameTime);
}
function doFrame(currentTimeMillis: number) {
lastFrameTime = currentTimeMillis;
shouldStop = true;
const thisFrameCbs = nextFrameAnimationCallbacks;
nextFrameAnimationCallbacks = {};
inAnimationFrame = true;
for (const animationId in thisFrameCbs) {
if (thisFrameCbs[animationId]) {
thisFrameCbs[animationId](lastFrameTime);
}
}
inAnimationFrame = false;
callAnimationCallbacks(thisFrameCbs, lastFrameTime);
if (shouldStop) {
fpsCallback.stop(); // TODO: check performance without stopping to allow consistent frame times
}
}
export function requestAnimationFrame(cb: FrameRequestCallback): number {
if (!inAnimationFrame) {
inAnimationFrame = true;
zonedCallback(cb)(getTimeInFrameBase()); // TODO: store and use lastFrameTime
inAnimationFrame = false;
function ensureCurrentFrameScheduled() {
if (!currentFrameScheduled) {
currentFrameScheduled = true;
queueMacrotask(doCurrentFrame);
}
}
return getNewId();
export function requestAnimationFrame(cb: FrameRequestCallback): number {
const animId = getNewId();
if (!inAnimationFrame) {
ensureCurrentFrameScheduled();
currentFrameAnimationCallbacks[animId] = zonedCallback(cb) as FrameRequestCallback;
return animId;
}
ensureNative();
const animId = getNewId();
nextFrameAnimationCallbacks[animId] = zonedCallback(cb) as FrameRequestCallback;
shouldStop = false;
fpsCallback.start();
@ -57,6 +89,7 @@ export function requestAnimationFrame(cb: FrameRequestCallback): number {
return animId;
}
export function cancelAnimationFrame(id: number) {
export function cancelAnimationFrame(id: number): void {
delete currentFrameAnimationCallbacks[id];
delete nextFrameAnimationCallbacks[id];
}

View File

@ -96,7 +96,7 @@ export function getAllKeys(): Array<string> {
const iterator = mappedPreferences.keySet().iterator();
const result = [];
while (iterator.hasNext()) {
let key = iterator.next();
const key = iterator.next();
result.push(key);
}

View File

@ -8,7 +8,6 @@ import { EventData } from '../data/observable';
import { View } from '../ui/core/view';
// Requires
import { Observable } from '../data/observable';
import * as bindableResources from '../ui/core/bindable/bindable-resources';
import { CSSUtils } from '../css/system-classes';
import { Enums } from '../ui/enums';
@ -34,7 +33,7 @@ const ORIENTATION_CSS_CLASSES = [`${CSSUtils.CLASS_PREFIX}${Enums.DeviceOrientat
const SYSTEM_APPEARANCE_CSS_CLASSES = [`${CSSUtils.CLASS_PREFIX}${Enums.SystemAppearance.light}`, `${CSSUtils.CLASS_PREFIX}${Enums.SystemAppearance.dark}`];
let cssFile: string = './app.css';
let cssFile = './app.css';
export function getResources() {
return bindableResources.get();
@ -44,8 +43,8 @@ export function setResources(res: any) {
bindableResources.set(res);
}
export let android: AndroidApplication = undefined;
export let ios: iOSApplication = undefined;
export const android: AndroidApplication = undefined;
export const ios: iOSApplication = undefined;
export const on = global.NativeScriptGlobals.events.on.bind(global.NativeScriptGlobals.events);
export const off = global.NativeScriptGlobals.events.off.bind(global.NativeScriptGlobals.events);

View File

@ -2,8 +2,11 @@
import { AndroidApplication as AndroidApplicationDefinition } from '.';
import { AndroidActivityBackPressedEventData, AndroidActivityBundleEventData, AndroidActivityEventData, AndroidActivityNewIntentEventData, AndroidActivityRequestPermissionsEventData, AndroidActivityResultEventData, ApplicationEventData, CssChangedEventData, OrientationChangedEventData, SystemAppearanceChangedEventData } from './application-interfaces';
// TODO: explain why we need to this or remov it
// Use requires to ensure order of imports is maintained
// eslint-disable-next-line @typescript-eslint/no-var-requires
const appCommon = require('./application-common');
// First reexport so that app module is initialized.
export * from './application-common';

View File

@ -198,21 +198,6 @@ export function loadAppCss();
*/
export function addCss(cssText: string, attributeScoped?: boolean): void;
/**
* This event is raised when application css is changed.
*/
export function on(event: 'cssChanged', callback: (args: CssChangedEventData) => void, thisArg?: any);
/**
* Event raised then livesync operation is performed.
*/
export function on(event: 'livesync', callback: (args: EventData) => void);
/**
* Removes listener for the specified event name.
*/
export function off(eventNames: string, callback?: any, thisArg?: any);
/**
* Call this method to run the application. Important: All code after this method call will not be executed!
* Compared to start this method won't create Frame as root view.
@ -226,12 +211,9 @@ export function run(entry?: NavigationEntry | string);
export function _resetRootView(entry?: NavigationEntry | string);
/**
* A basic method signature to hook an event listener (shortcut alias to the addEventListener method).
* @param eventNames - String corresponding to events (e.g. "onLaunch"). Optionally could be used more events separated by `,` (e.g. "onLaunch", "onSuspend").
* @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.
* Removes listener for the specified event name.
*/
export function on(eventNames: string, callback: (data: any) => void, thisArg?: any);
export function off(eventNames: string, callback?: any, thisArg?: any);
/**
* Shortcut alias to the removeEventListener method.
@ -253,6 +235,34 @@ export function notify(data: any): void;
*/
export function hasListeners(eventName: string): boolean;
/**
* A basic method signature to hook an event listener (shortcut alias to the addEventListener method).
* @param eventNames - String corresponding to events (e.g. "onLaunch"). Optionally could be used more events separated by `,` (e.g. "onLaunch", "onSuspend").
* @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.
*/
export function on(eventNames: string, callback: (data: any) => void, thisArg?: any);
/**
* This event is raised when application css is changed.
*/
export function on(event: 'cssChanged', callback: (args: CssChangedEventData) => void, thisArg?: any);
/**
* Event raised then livesync operation is performed.
*/
export function on(event: 'livesync', callback: (args: EventData) => void);
/**
* This event is raised when application css is changed.
*/
export function on(event: 'cssChanged', callback: (args: CssChangedEventData) => void, thisArg?: any);
/**
* Event raised then livesync operation is performed.
*/
export function on(event: 'livesync', callback: (args: EventData) => void);
/**
* This event is raised on application launchEvent.
*/

View File

@ -2,7 +2,9 @@
import { iOSApplication as iOSApplicationDefinition } from '.';
import { ApplicationEventData, CssChangedEventData, LaunchEventData, LoadAppCSSEventData, OrientationChangedEventData, SystemAppearanceChangedEventData } from './application-interfaces';
// TODO: explain why we need to this or remov it
// Use requires to ensure order of imports is maintained
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { displayedEvent, exitEvent, getCssFileName, launchEvent, livesync, lowMemoryEvent, notify, on, orientationChanged, orientationChangedEvent, resumeEvent, setApplication, suspendEvent, systemAppearanceChanged, systemAppearanceChangedEvent } = require('./application-common');
// First reexport so that app module is initialized.
export * from './application-common';
@ -381,7 +383,7 @@ export function getRootView() {
return iosApp.rootView;
}
let started: boolean = false;
let started = false;
export function run(entry?: string | NavigationEntry) {
mainEntry = typeof entry === 'string' ? { moduleName: entry } : entry;
started = true;
@ -400,11 +402,11 @@ export function run(entry?: string | NavigationEntry) {
if (rootController) {
const controller = getViewController(rootView);
rootView._setupAsRootView({});
let embedderDelegate = NativeScriptEmbedder.sharedInstance().delegate;
const embedderDelegate = NativeScriptEmbedder.sharedInstance().delegate;
if (embedderDelegate) {
embedderDelegate.presentNativeScriptApp(controller);
} else {
let visibleVC = getVisibleViewController(rootController);
const visibleVC = getVisibleViewController(rootController);
visibleVC.presentViewControllerAnimatedCompletion(controller, true, null);
}

View File

@ -13,9 +13,9 @@ export class Color implements definition.Color {
constructor(color: number);
constructor(color: string);
constructor(a: number, r: number, g: number, b: number);
constructor() {
if (arguments.length === 1) {
const arg = arguments[0];
constructor(...args) {
if (args.length === 1) {
const arg = args[0];
if (types.isString(arg)) {
if (isRgbOrRgba(arg)) {
this._argb = argbFromRgbOrRgba(arg);
@ -40,8 +40,8 @@ export class Color implements definition.Color {
} else {
throw new Error('Expected 1 or 4 constructor parameters.');
}
} else if (arguments.length === 4) {
this._argb = (arguments[0] & 0xff) * 0x01000000 + (arguments[1] & 0xff) * 0x00010000 + (arguments[2] & 0xff) * 0x00000100 + (arguments[3] & 0xff) * 0x00000001;
} else if (args.length === 4) {
this._argb = (args[0] & 0xff) * 0x01000000 + (args[1] & 0xff) * 0x00010000 + (args[2] & 0xff) * 0x00000100 + (args[3] & 0xff) * 0x00000001;
} else {
throw new Error('Expected 1 or 4 constructor parameters.');
}

View File

@ -9,7 +9,7 @@ function mapSelectors(selector: string): string[] {
}
function mapPosition(node, css) {
let res: any = {
const res: any = {
start: {
line: node.loc.start.line,
column: node.loc.start.column,
@ -47,7 +47,7 @@ function transformAst(node, css, type = null) {
}
if (node.type === 'Atrule') {
let atrule: any = {
const atrule: any = {
type: node.name,
};
@ -86,9 +86,9 @@ function transformAst(node, css, type = null) {
}
if (node.type === 'Rule') {
let value = node.prelude.value;
const value = node.prelude.value;
let res: any = {
const res: any = {
type: type != null ? type : 'rule',
declarations: transformAst(node.block, css),
position: mapPosition(node, css),
@ -128,8 +128,8 @@ function transformAst(node, css, type = null) {
}
export function cssTreeParse(css, source): any {
let errors = [];
let ast = parse(css, {
const errors = [];
const ast = parse(css, {
parseValue: false,
parseAtrulePrelude: false,
parseRulePrelude: false,

View File

@ -1,4 +1,4 @@
import { getKnownColor } from "color/known-colors";
import { getKnownColor } from "../color/known-colors";
export type Parsed<V> = { start: number; end: number; value: V };
@ -54,7 +54,7 @@ export interface BackgroundPosition {
text?: string;
}
const urlRegEx = /\s*url\((?:('|")([^\1]*)\1|([^\)]*))\)\s*/gy;
const urlRegEx = /\s*url\((?:('|")([^\1]*)\1|([^)]*))\)\s*/gy;
export function parseURL(text: string, start = 0): Parsed<URL> {
urlRegEx.lastIndex = start;
const result = urlRegEx.exec(text);
@ -128,10 +128,10 @@ export function convertHSLToRGBColor(hue: number, saturation: number, lightness:
hue /= 60;
lightness /= 100;
let chroma = ((1 - Math.abs(2 * lightness - 1)) * saturation) / 100,
X = chroma * (1 - Math.abs((hue % 2) - 1)),
const chroma = ((1 - Math.abs(2 * lightness - 1)) * saturation) / 100,
X = chroma * (1 - Math.abs((hue % 2) - 1));
// Add lightness match to all RGB components beforehand
{ m: r, m: g, m: b } = { m: lightness - chroma / 2 };
let { m: r, m: g, m: b } = { m: lightness - chroma / 2 };
if (0 <= hue && hue < 1) {
r += chroma;
@ -212,7 +212,7 @@ export function parseColor(value: string, start = 0, keyword = parseKeyword(valu
return parseHexColor(value, start) || parseColorKeyword(value, start, keyword) || parseRGBColor(value, start) || parseRGBAColor(value, start) || parseHSLColor(value, start) || parseHSLAColor(value, start);
}
const keywordRegEx = /\s*([a-z][\w\-]*)\s*/giy;
const keywordRegEx = /\s*([a-z][\w-]*)\s*/giy;
function parseKeyword(text: string, start = 0): Parsed<Keyword> {
keywordRegEx.lastIndex = start;
const result = keywordRegEx.exec(text);
@ -237,7 +237,7 @@ export function parseRepeat(value: string, start = 0, keyword = parseKeyword(val
return null;
}
const unitRegEx = /\s*([\+\-]?(?:\d+\.\d+|\d+|\.\d+)(?:[eE][\+\-]?\d+)?)([a-zA-Z]+|%)?\s*/gy;
const unitRegEx = /\s*([+-]?(?:\d+\.\d+|\d+|\.\d+)(?:[eE][+-]?\d+)?)([a-zA-Z]+|%)?\s*/gy;
export function parseUnit(text: string, start = 0): Parsed<Unit<string>> {
unitRegEx.lastIndex = start;
const result = unitRegEx.exec(text);
@ -743,7 +743,7 @@ export function parseSimpleIdentifierSelector(text: string, start = 0): Parsed<T
return { start, end, value };
}
const attributeSelectorRegEx = /\[\s*([_-\w][_-\w\d]*)\s*(?:(=|\^=|\$=|\*=|\~=|\|=)\s*(?:([_-\w][_-\w\d]*)|"((?:[^\\"]|\\(?:"|n|r|f|\\|0-9a-f))*)"|'((?:[^\\']|\\(?:'|n|r|f|\\|0-9a-f))*)')\s*)?\]/gy;
const attributeSelectorRegEx = /\[\s*([_-\w][_-\w\d]*)\s*(?:(=|\^=|\$=|\*=|~=|\|=)\s*(?:([_-\w][_-\w\d]*)|"((?:[^\\"]|\\(?:"|n|r|f|\\|0-9a-f))*)"|'((?:[^\\']|\\(?:'|n|r|f|\\|0-9a-f))*)')\s*)?\]/gy;
export function parseAttributeSelector(text: string, start: number): Parsed<AttributeSelector> {
attributeSelectorRegEx.lastIndex = start;
const result = attributeSelectorRegEx.exec(text);
@ -852,12 +852,13 @@ export interface QualifiedRule {
const whitespaceRegEx = /[\s\t\n\r\f]*/gmy;
const singleQuoteStringRegEx = /'((?:[^\n\r\f\']|\\(?:\$|\n|[0-9a-fA-F]{1,6}\s?))*)(:?'|$)/gmy; // Besides $n, parse escape
const doubleQuoteStringRegEx = /"((?:[^\n\r\f\"]|\\(?:\$|\n|[0-9a-fA-F]{1,6}\s?))*)(:?"|$)/gmy; // Besides $n, parse escape
const singleQuoteStringRegEx = /'((?:[^\n\r\f']|\\(?:\$|\n|[0-9a-fA-F]{1,6}\s?))*)(:?'|$)/gmy; // Besides $n, parse escape
const doubleQuoteStringRegEx = /"((?:[^\n\r\f"]|\\(?:\$|\n|[0-9a-fA-F]{1,6}\s?))*)(:?"|$)/gmy; // Besides $n, parse escape
const commentRegEx = /(\/\*(?:[^\*]|\*[^\/])*\*\/)/gmy;
const numberRegEx = /[\+\-]?(?:\d+\.\d+|\d+|\.\d+)(?:[eE][\+\-]?\d+)?/gmy;
const nameRegEx = /-?(?:(?:[a-zA-Z_]|[^\x00-\x7F]|\\(?:\$|\n|[0-9a-fA-F]{1,6}\s?))(?:[a-zA-Z_0-9\-]*|\\(?:\$|\n|[0-9a-fA-F]{1,6}\s?))*)/gmy;
const commentRegEx = /(\/\*(?:[^*]|\*[^/])*\*\/)/gmy;
const numberRegEx = /[+-]?(?:\d+\.\d+|\d+|\.\d+)(?:[eE][+-]?\d+)?/gmy;
// eslint-disable-next-line no-control-regex
const nameRegEx = /-?(?:(?:[a-zA-Z_]|[^\x00-\x7F]|\\(?:\$|\n|[0-9a-fA-F]{1,6}\s?))(?:[a-zA-Z_0-9-]*|\\(?:\$|\n|[0-9a-fA-F]{1,6}\s?))*)/gmy;
// const nonQuoteURLRegEx = /(:?[^\)\s\t\n\r\f\'\"\(]|\\(?:\$|\n|[0-9a-fA-F]{1,6}\s?))*/gym; // TODO: non-printable code points omitted
type InputToken = '(' | ')' | '{' | '}' | '[' | ']' | ':' | ';' | ',' | ' ' | '^=' | '|=' | '$=' | '*=' | '~=' | '<!--' | '-->' | undefined | /* <EOF-token> */ InputTokenObject | FunctionInputToken | FunctionToken | SimpleBlock | AtKeywordToken;
@ -1334,7 +1335,7 @@ export class CSS3Parser {
case ' ':
continue;
case '<!--':
case '-->':
case '-->':{
if (this.topLevelFlag) {
continue;
}
@ -1345,6 +1346,7 @@ export class CSS3Parser {
}
continue;
}
}
if ((<InputTokenObject>inputToken).type === TokenObjectType.atKeyword) {
this.reconsumeTheCurrentInputToken(inputToken);
const atRule = this.consumeAnAtRule();
@ -1511,17 +1513,19 @@ export class CSS3Parser {
}
const nextInputToken = this.text[this.nextInputCodePointIndex];
switch (nextInputToken) {
case ')':
case ')':{
this.nextInputCodePointIndex++;
const end = this.nextInputCodePointIndex;
funcToken.text = name + '(' + this.text.substring(start, end);
return funcToken;
default:
}
default:{
const component = this.consumeAComponentValue();
if (component) {
funcToken.components.push(component);
}
}
// TODO: Else we won't advance
}
} while (true);

View File

@ -1,3 +1,4 @@
/* eslint-disable prefer-rest-params */
import { Observable, EventData } from '../observable';
import * as types from '../../utils/types';
@ -59,6 +60,7 @@ export class ObservableArray<T> extends Observable {
if (arguments.length === 1 && Array.isArray(arguments[0])) {
this._array = arguments[0].slice();
} else {
// eslint-disable-next-line prefer-spread
this._array = Array.apply(null, arguments);
}
@ -67,7 +69,7 @@ export class ObservableArray<T> extends Observable {
object: this,
action: ChangeType.Add,
index: null,
removed: new Array(),
removed: [],
addedCount: 1,
};
@ -92,7 +94,7 @@ export class ObservableArray<T> extends Observable {
* Sets item at specified index.
*/
setItem(index: number, value: T) {
let oldValue = this._array[index];
const oldValue = this._array[index];
this._array[index] = value;
this.notify(<ChangedData<T>>{
@ -114,7 +116,7 @@ export class ObservableArray<T> extends Observable {
set length(value: number) {
if (types.isNumber(value) && this._array && this._array.length !== value) {
let added=[];
const added=[];
for (let i=this._array.length;i < value;++i) {
added.push(undefined);
}
@ -137,9 +139,9 @@ export class ObservableArray<T> extends Observable {
* Combines two or more arrays.
* @param items Additional items to add to the end of array1.
*/
concat(_args?: any): T[] {
concat(...args): T[] {
this._addArgs.index = this._array.length;
const result = this._array.concat.apply(this._array, arguments);
const result = this._array.concat(...args);
return result;
}
@ -182,7 +184,7 @@ export class ObservableArray<T> extends Observable {
this._array.push(source[i]);
}
} else {
this._array.push.apply(this._array, arguments);
this._array.push(...args);
}
this._addArgs.addedCount = this._array.length - this._addArgs.index;
@ -245,7 +247,7 @@ export class ObservableArray<T> extends Observable {
*/
splice(start: number, deleteCount?: number, ...items: any): T[] {
const length = this._array.length;
const result = this._array.splice.apply(this._array, arguments);
const result = this._array.splice(start, deleteCount, ...items);
this.notify(<ChangedData<T>>{
eventName: CHANGE,
@ -276,7 +278,7 @@ export class ObservableArray<T> extends Observable {
*/
unshift(...args: any): number {
const length = this._array.length;
const result = this._array.unshift.apply(this._array, arguments);
const result = this._array.unshift(...args);
this._addArgs.index = 0;
this._addArgs.addedCount = result - length;

View File

@ -1,5 +1,5 @@
declare var __registerDomainDispatcher;
declare var __inspectorSendEvent;
declare let __registerDomainDispatcher;
declare let __inspectorSendEvent;
export function DomainDispatcher(domain: string): ClassDecorator {
return (klass) => __registerDomainDispatcher(domain, klass);
}

View File

@ -6,11 +6,13 @@ import { getNodeById } from './dom-node';
import { mainThreadify } from '../utils';
// Use lazy requires for core modules
// eslint-disable-next-line @typescript-eslint/no-var-requires
const getAppRootView = () => require('../application').getRootView();
let unsetValue;
function unsetViewValue(view, name) {
if (!unsetValue) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
unsetValue = require('../ui/core/properties').unsetValue;
}
@ -55,7 +57,7 @@ export const removeNode = mainThreadify(function removeNode(nodeId) {
const view = getViewById(nodeId);
if (view) {
// Avoid importing layout and content view
let parent = <any>view.parent;
const parent = <any>view.parent;
if (parent.removeChild) {
parent.removeChild(view);
} else if (parent.content === view) {
@ -70,14 +72,14 @@ export const setAttributeAsText = mainThreadify(function setAttributeAsText(node
const view = getViewById(nodeId);
if (view) {
// attribute is registered for the view instance
let hasOriginalAttribute = !!name.trim();
const hasOriginalAttribute = !!name.trim();
if (text) {
let textParts = text.split('=');
const textParts = text.split('=');
if (textParts.length === 2) {
let attrName = textParts[0];
let attrValue = textParts[1].replace(/['"]+/g, '');
const attrName = textParts[0];
const attrValue = textParts[1].replace(/['"]+/g, '');
// if attr name is being replaced with another
if (name !== attrName && hasOriginalAttribute) {

View File

@ -14,8 +14,11 @@ function lazy<T>(action: () => T): () => T {
return () => _value || (_value = action());
}
// eslint-disable-next-line @typescript-eslint/no-var-requires
const percentLengthToStringLazy = lazy<(length) => string>(() => require('../ui/styling/style-properties').PercentLength.convertToString);
// eslint-disable-next-line @typescript-eslint/no-var-requires
const getSetPropertiesLazy = lazy<(view: ViewBase) => [string, any][]>(() => require('../ui/core/properties').getSetProperties);
// eslint-disable-next-line @typescript-eslint/no-var-requires
const getComputedCssValuesLazy = lazy<(view: ViewBase) => [string, any][]>(() => require('../ui/core/properties').getComputedCssValues);
export function registerInspectorEvents(inspector: InspectorEvents) {
@ -128,7 +131,7 @@ export class DOMNode {
return true;
});
const index = !!previousChild ? previousChild._domId : 0;
const index = previousChild ? previousChild._domId : 0;
childView.ensureDomNode();
ins.childNodeInserted(this.nodeId, index, childView.domNode);

View File

@ -208,7 +208,7 @@ export namespace NetworkAgent {
}
function mimeTypeToType(mimeType: string): string {
let type: string = 'Document';
let type = 'Document';
if (mimeType) {
if (mimeType.indexOf('image') === 0) {

View File

@ -1,4 +1,5 @@
import * as inspectorCommandTypes from './InspectorBackendCommands.ios';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const inspectorCommands: typeof inspectorCommandTypes = require('./InspectorBackendCommands');
import * as debuggerDomains from '.';

View File

@ -1,4 +1,5 @@
import * as inspectorCommandTypes from './InspectorBackendCommands.ios';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const inspectorCommands: typeof inspectorCommandTypes = require('./InspectorBackendCommands');
import * as debuggerDomains from '.';

View File

@ -1,11 +1,12 @@
import * as inspectorCommandTypes from './InspectorBackendCommands.ios';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const inspectorCommands: typeof inspectorCommandTypes = require('./InspectorBackendCommands');
import * as debuggerDomains from '.';
declare var __inspectorSendEvent;
declare let __inspectorSendEvent;
declare var __inspectorTimestamp;
declare let __inspectorTimestamp;
const frameId = 'NativeScriptMainFrameIdentifier';
const loaderId = 'Loader Identifier';
@ -222,11 +223,11 @@ export class NetworkDomainDebugger implements inspectorCommandTypes.NetworkDomai
* Loads a resource in the context of a frame on the inspected page without cross origin checks.
*/
loadResource(params: inspectorCommandTypes.NetworkDomain.LoadResourceMethodArguments): { content: string; mimeType: string; status: number } {
let appPath = NSBundle.mainBundle.bundlePath;
let pathUrl = params.url.replace('file://', appPath);
let fileManager = NSFileManager.defaultManager;
let data = fileManager.fileExistsAtPath(pathUrl) ? fileManager.contentsAtPath(pathUrl) : undefined;
let content = data ? NSString.alloc().initWithDataEncoding(data, NSUTF8StringEncoding) : '';
const appPath = NSBundle.mainBundle.bundlePath;
const pathUrl = params.url.replace('file://', appPath);
const fileManager = NSFileManager.defaultManager;
const data = fileManager.fileExistsAtPath(pathUrl) ? fileManager.contentsAtPath(pathUrl) : undefined;
const content = data ? NSString.alloc().initWithDataEncoding(data, NSUTF8StringEncoding) : '';
return {
content: content.toString(), // Not sure why however we need to call toString() for NSString
@ -235,10 +236,10 @@ export class NetworkDomainDebugger implements inspectorCommandTypes.NetworkDomai
};
}
public static idSequence: number = 0;
public static idSequence = 0;
create(): Request {
let id = (++NetworkDomainDebugger.idSequence).toString();
let resourceData = new Request(this, id);
const id = (++NetworkDomainDebugger.idSequence).toString();
const resourceData = new Request(this, id);
resources_datas[id] = resourceData;
return resourceData;

View File

@ -449,7 +449,7 @@ export class FileSystemAccess {
}
let childFile: java.io.File;
let success: boolean = false;
let success = false;
for (let i = 0; i < filesList.length; i++) {
childFile = filesList[i];

View File

@ -536,7 +536,7 @@ export class Folder extends FileSystemEntity {
}
}
export module knownFolders {
export namespace knownFolders {
let _documents: Folder;
let _temp: Folder;
let _app: Folder;
@ -574,7 +574,7 @@ export module knownFolders {
return _app;
}
export module ios {
export namespace ios {
function _checkPlatform(knownFolderName: string) {
if (!global.isIOS) {
throw new Error(`The "${knownFolderName}" known folder is available on iOS only!`);
@ -585,7 +585,7 @@ export module knownFolders {
export function library(): Folder {
_checkPlatform('library');
if (!_library) {
let existingFolderInfo = getExistingFolderInfo(NSSearchPathDirectory.LibraryDirectory);
const existingFolderInfo = getExistingFolderInfo(NSSearchPathDirectory.LibraryDirectory);
if (existingFolderInfo) {
_library = existingFolderInfo.folder;
@ -601,7 +601,7 @@ export module knownFolders {
export function developer(): Folder {
_checkPlatform('developer');
if (!_developer) {
let existingFolderInfo = getExistingFolderInfo(NSSearchPathDirectory.DeveloperDirectory);
const existingFolderInfo = getExistingFolderInfo(NSSearchPathDirectory.DeveloperDirectory);
if (existingFolderInfo) {
_developer = existingFolderInfo.folder;
@ -617,7 +617,7 @@ export module knownFolders {
export function desktop(): Folder {
_checkPlatform('desktop');
if (!_desktop) {
let existingFolderInfo = getExistingFolderInfo(NSSearchPathDirectory.DesktopDirectory);
const existingFolderInfo = getExistingFolderInfo(NSSearchPathDirectory.DesktopDirectory);
if (existingFolderInfo) {
_desktop = existingFolderInfo.folder;
@ -633,7 +633,7 @@ export module knownFolders {
export function downloads(): Folder {
_checkPlatform('downloads');
if (!_downloads) {
let existingFolderInfo = getExistingFolderInfo(NSSearchPathDirectory.DownloadsDirectory);
const existingFolderInfo = getExistingFolderInfo(NSSearchPathDirectory.DownloadsDirectory);
if (existingFolderInfo) {
_downloads = existingFolderInfo.folder;
@ -649,7 +649,7 @@ export module knownFolders {
export function movies(): Folder {
_checkPlatform('movies');
if (!_movies) {
let existingFolderInfo = getExistingFolderInfo(NSSearchPathDirectory.MoviesDirectory);
const existingFolderInfo = getExistingFolderInfo(NSSearchPathDirectory.MoviesDirectory);
if (existingFolderInfo) {
_movies = existingFolderInfo.folder;
@ -665,7 +665,7 @@ export module knownFolders {
export function music(): Folder {
_checkPlatform('music');
if (!_music) {
let existingFolderInfo = getExistingFolderInfo(NSSearchPathDirectory.MusicDirectory);
const existingFolderInfo = getExistingFolderInfo(NSSearchPathDirectory.MusicDirectory);
if (existingFolderInfo) {
_music = existingFolderInfo.folder;
@ -681,7 +681,7 @@ export module knownFolders {
export function pictures(): Folder {
_checkPlatform('pictures');
if (!_pictures) {
let existingFolderInfo = getExistingFolderInfo(NSSearchPathDirectory.PicturesDirectory);
const existingFolderInfo = getExistingFolderInfo(NSSearchPathDirectory.PicturesDirectory);
if (existingFolderInfo) {
_pictures = existingFolderInfo.folder;
@ -697,7 +697,7 @@ export module knownFolders {
export function sharedPublic(): Folder {
_checkPlatform('sharedPublic');
if (!_sharedPublic) {
let existingFolderInfo = getExistingFolderInfo(NSSearchPathDirectory.SharedPublicDirectory);
const existingFolderInfo = getExistingFolderInfo(NSSearchPathDirectory.SharedPublicDirectory);
if (existingFolderInfo) {
_sharedPublic = existingFolderInfo.folder;
@ -726,7 +726,7 @@ export module knownFolders {
}
}
export module path {
export namespace path {
export function normalize(path: string): string {
return getFileAccess().normalizePath(path);
}

View File

@ -5,14 +5,14 @@ class FrameHandlerImpl extends NSObject {
private _owner: WeakRef<FPSCallback>;
public static initWithOwner(owner: WeakRef<FPSCallback>): FrameHandlerImpl {
let handler = <FrameHandlerImpl>FrameHandlerImpl.new();
const handler = <FrameHandlerImpl>FrameHandlerImpl.new();
handler._owner = owner;
return handler;
}
public handleFrame(sender: CADisplayLink): void {
let owner = this._owner.get();
const owner = this._owner.get();
if (owner) {
owner._handleFrame(sender);
}

View File

@ -86,7 +86,7 @@ export function removeCallback(id: number) {
function notify(fps) {
let callback: Function;
for (let id in callbacks) {
for (const id in callbacks) {
callback = callbacks[id];
callback(fps, _minFps);
}

View File

@ -1,4 +1,5 @@
declare let global: NodeJS.Global & typeof globalThis;
/* eslint-disable no-var */
declare var global: NodeJS.Global & typeof globalThis;
interface ModuleResolver {
/**
@ -253,12 +254,6 @@ declare function NativeClass<T extends { new (...args: any[]): {} }>(options?: N
*/
declare function Interfaces(...interfaces): ClassDecorator;
/**
* Decorates class that extends native Java class
* @param nativeClassName The name of the newly generated class. Must be unique in the application.
*/
declare function JavaProxy(nativeClassName: string): ClassDecorator;
/**
* Important: Not applicable to Objective-C classes (iOS platform)
* Decorates class that extends native Java class
@ -266,6 +261,12 @@ declare function JavaProxy(nativeClassName: string): ClassDecorator;
*/
declare function Interfaces(interfaces: any[]): ClassDecorator;
/**
* Decorates class that extends native Java class
* @param nativeClassName The name of the newly generated class. Must be unique in the application.
*/
declare function JavaProxy(nativeClassName: string): ClassDecorator;
/**
* Important: Not applicable to Java classes (Android platform)
* Decorates a class that implements native Objective-C protocols.

View File

@ -1,4 +1,5 @@
import * as tslibType from 'tslib';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const tslib: typeof tslibType = require('tslib');
import { Observable } from '../data/observable';
import { trace as profilingTrace, time, uptime, level as profilingLevel } from '../profiling';
@ -18,10 +19,10 @@ function registerOnGlobalContext(moduleName: string, exportName: string): void {
Object.defineProperty(global, exportName, {
get: function () {
// We do not need to cache require() call since it is already cached in the runtime.
let m = global.loadModule(moduleName);
const m = global.loadModule(moduleName);
// Redefine the property to make sure the above code is executed only once.
let resolvedValue = m[exportName];
const resolvedValue = m[exportName];
Object.defineProperty(global, exportName, {
value: resolvedValue,
configurable: true,
@ -117,7 +118,7 @@ export function initGlobal() {
// Required by V8 snapshot generator
if (!(<any>global).__extends) {
(<any>global).__extends = function (d, b) {
for (let p in b) {
for (const p in b) {
if (b.hasOwnProperty(p)) {
d[p] = b[p];
}
@ -234,7 +235,7 @@ export function initGlobal() {
return modules.has(name);
};
global.loadModule = function loadModule(name: string, isUIModule: boolean = false): any {
global.loadModule = function loadModule(name: string, isUIModule = false): any {
const moduleInfo = modules.get(name);
if (moduleInfo) {
if (isUIModule) {
@ -250,7 +251,7 @@ export function initGlobal() {
return result;
}
for (let resolver of (<any>global).moduleResolvers) {
for (const resolver of (<any>global).moduleResolvers) {
const result = resolver(name);
if (result) {
modules.set(name, { moduleId: name, loader: () => result });
@ -270,7 +271,7 @@ export function initGlobal() {
// This method iterates all the keys in the source exports object and copies them to the destination exports one.
// Note: the method will not check for naming collisions and will override any already existing entries in the destination exports.
global.moduleMerge = function (sourceExports: any, destExports: any) {
for (let key in sourceExports) {
for (const key in sourceExports) {
destExports[key] = sourceExports[key];
}
};

View File

@ -191,7 +191,7 @@ function buildJavaOptions(options: httpModule.HttpRequestOptions) {
const arrayList = new java.util.ArrayList<org.nativescript.widgets.Async.Http.KeyValuePair>();
const pair = org.nativescript.widgets.Async.Http.KeyValuePair;
for (let key in options.headers) {
for (const key in options.headers) {
arrayList.add(new pair(key, options.headers[key] + ''));
}

View File

@ -87,7 +87,7 @@ export function request(options: httpModule.HttpRequestOptions): Promise<httpMod
urlRequest.setValueForHTTPHeaderField(USER_AGENT, USER_AGENT_HEADER);
if (options.headers) {
for (let header in options.headers) {
for (const header in options.headers) {
urlRequest.setValueForHTTPHeaderField(options.headers[header] + '', header);
}
}

View File

@ -36,9 +36,9 @@ export class ImageAssetBase extends Observable implements ImageAssetDefinition {
}
export function getAspectSafeDimensions(sourceWidth, sourceHeight, reqWidth, reqHeight) {
let widthCoef = sourceWidth / reqWidth;
let heightCoef = sourceHeight / reqHeight;
let aspectCoef = Math.min(widthCoef, heightCoef);
const widthCoef = sourceWidth / reqWidth;
const heightCoef = sourceHeight / reqHeight;
const aspectCoef = Math.min(widthCoef, heightCoef);
return {
width: Math.floor(sourceWidth / aspectCoef),
@ -51,7 +51,7 @@ export function getRequestedImageSize(src: { width: number; height: number }, op
let reqHeight = options.height || Math.min(src.height, Screen.mainScreen.heightPixels);
if (options && options.keepAspectRatio) {
let safeAspectSize = getAspectSafeDimensions(src.width, src.height, reqWidth, reqHeight);
const safeAspectSize = getAspectSafeDimensions(src.width, src.height, reqWidth, reqHeight);
reqWidth = safeAspectSize.width;
reqHeight = safeAspectSize.height;
}

View File

@ -25,19 +25,19 @@ export class ImageAsset extends ImageAssetBase {
}
public getImageAsync(callback: (image, error) => void) {
let bitmapOptions = new android.graphics.BitmapFactory.Options();
const bitmapOptions = new android.graphics.BitmapFactory.Options();
bitmapOptions.inJustDecodeBounds = true;
// read only the file size
let bitmap = android.graphics.BitmapFactory.decodeFile(this.android, bitmapOptions);
let sourceSize = {
const sourceSize = {
width: bitmapOptions.outWidth,
height: bitmapOptions.outHeight,
};
let requestedSize = getRequestedImageSize(sourceSize, this.options);
const requestedSize = getRequestedImageSize(sourceSize, this.options);
let sampleSize = org.nativescript.widgets.image.Fetcher.calculateInSampleSize(bitmapOptions.outWidth, bitmapOptions.outHeight, requestedSize.width, requestedSize.height);
const sampleSize = org.nativescript.widgets.image.Fetcher.calculateInSampleSize(bitmapOptions.outWidth, bitmapOptions.outHeight, requestedSize.width, requestedSize.height);
let finalBitmapOptions = new android.graphics.BitmapFactory.Options();
const finalBitmapOptions = new android.graphics.BitmapFactory.Options();
finalBitmapOptions.inSampleSize = sampleSize;
try {
let error = null;

View File

@ -35,25 +35,25 @@ export class ImageAsset extends ImageAssetBase {
callback(null, 'Asset cannot be found.');
}
let srcWidth = this.nativeImage ? this.nativeImage.size.width : this.ios.pixelWidth;
let srcHeight = this.nativeImage ? this.nativeImage.size.height : this.ios.pixelHeight;
let requestedSize = getRequestedImageSize({ width: srcWidth, height: srcHeight }, this.options);
const srcWidth = this.nativeImage ? this.nativeImage.size.width : this.ios.pixelWidth;
const srcHeight = this.nativeImage ? this.nativeImage.size.height : this.ios.pixelHeight;
const requestedSize = getRequestedImageSize({ width: srcWidth, height: srcHeight }, this.options);
if (this.nativeImage) {
let newSize = CGSizeMake(requestedSize.width, requestedSize.height);
let resizedImage = this.scaleImage(this.nativeImage, newSize);
const newSize = CGSizeMake(requestedSize.width, requestedSize.height);
const resizedImage = this.scaleImage(this.nativeImage, newSize);
callback(resizedImage, null);
return;
}
let imageRequestOptions = PHImageRequestOptions.alloc().init();
const imageRequestOptions = PHImageRequestOptions.alloc().init();
imageRequestOptions.deliveryMode = PHImageRequestOptionsDeliveryMode.HighQualityFormat;
imageRequestOptions.networkAccessAllowed = true;
PHImageManager.defaultManager().requestImageForAssetTargetSizeContentModeOptionsResultHandler(this.ios, requestedSize, PHImageContentMode.AspectFit, imageRequestOptions, (image, imageResultInfo) => {
if (image) {
let resultImage = this.scaleImage(image, requestedSize);
const resultImage = this.scaleImage(image, requestedSize);
callback(resultImage, null);
} else {
callback(null, imageResultInfo.valueForKey(PHImageErrorKey));
@ -67,7 +67,7 @@ export class ImageAsset extends ImageAssetBase {
UIGraphicsBeginImageContextWithOptions(requestedSize, false, scaleFactor);
image.drawInRect(CGRectMake(0, 0, requestedSize.width, requestedSize.height));
let resultImage = UIGraphicsGetImageFromCurrentImageContext();
const resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resultImage;

View File

@ -110,7 +110,7 @@ export * from './trace';
export * from './ui';
import { GC, isFontIconURI, isDataURI, isFileOrResourcePath, executeOnMainThread, mainThreadify, isMainThread, dispatchToMainThread, releaseNativeObject, getModuleName, openFile, openUrl, isRealDevice, layout, ad as androidUtils, iOSNativeHelper as iosUtils, Source, RESOURCE_PREFIX, FILE_PREFIX } from './utils';
import { GC, isFontIconURI, isDataURI, isFileOrResourcePath, executeOnMainThread, mainThreadify, isMainThread, dispatchToMainThread, queueMacrotask, releaseNativeObject, getModuleName, openFile, openUrl, isRealDevice, layout, ad as androidUtils, iOSNativeHelper as iosUtils, Source, RESOURCE_PREFIX, FILE_PREFIX } from './utils';
import { ClassInfo, getClass, getBaseClasses, getClassInfo, isBoolean, isDefined, isFunction, isNullOrUndefined, isNumber, isObject, isString, isUndefined, toUIString, verifyCallback } from './utils/types';
export const Utils = {
@ -124,6 +124,7 @@ export const Utils = {
mainThreadify,
isMainThread,
dispatchToMainThread,
queueMacrotask,
releaseNativeObject,
getModuleName,

View File

@ -25,7 +25,7 @@ export interface Options {
source?: boolean
}
export module Syntax {
export namespace Syntax {
// Node
interface Node {
type: string
@ -69,10 +69,8 @@ export module Syntax {
}
// Statement
interface Statement extends Node {
}
interface EmptyStatement extends Statement {
}
type Statement = Node
type EmptyStatement = Statement
interface BlockStatement extends Statement {
body: SomeStatement[]
}
@ -137,8 +135,7 @@ export module Syntax {
}
interface VariableDeclaratorOrExpression extends VariableDeclarator, SomeExpression {
}
interface DebuggerStatement extends Statement {
}
type DebuggerStatement = Statement
interface SomeStatement extends
EmptyStatement, ExpressionStatement, BlockStatement, IfStatement,
LabeledStatement, BreakStatement, ContinueStatement, WithStatement,
@ -150,8 +147,7 @@ export module Syntax {
}
// Declration
interface Declration extends Statement {
}
type Declration = Statement
interface FunctionDeclration extends Declration {
id: Identifier
params: Identifier[] // Pattern
@ -171,16 +167,14 @@ export module Syntax {
}
// Expression
interface Expression extends Node { // | Pattern
}
type Expression = Node
interface SomeExpression extends
ThisExpression, ArrayExpression, ObjectExpression, FunctionExpression,
ArrowFunctionExpression, SequenceExpression, UnaryExpression, BinaryExpression,
AssignmentExpression, UpdateExpression, LogicalExpression, ConditionalExpression,
NewExpression, CallExpression, MemberExpression {
}
interface ThisExpression extends Expression {
}
type ThisExpression = Expression
interface ArrayExpression extends Expression {
elements: SomeExpression[] // [ Expression | null ]
}

View File

@ -39,7 +39,7 @@ export class ModuleNameResolver {
// This call will return a clean path without qualifiers
path = stripQualifiers(path);
let candidates = this.getCandidates(path, ext);
const candidates = this.getCandidates(path, ext);
result = findMatch(path, ext, candidates, this.context);
return result;

View File

@ -25,7 +25,7 @@ function processFile(file: fs.File) {
const loadContent = () => file.readTextSync();
switch (file.extension.toLocaleLowerCase()) {
case '.js':
case '.js':{
const noExtPath = filePathRelativeToApp.substr(0, filePathRelativeToApp.length - '.js'.length);
register(filePathRelativeToApp, function () {
@ -35,6 +35,7 @@ function processFile(file: fs.File) {
return global.require(file.path);
});
break;
}
case '.css':
register(filePathRelativeToApp, loadContent);
@ -48,8 +49,8 @@ function processFile(file: fs.File) {
if (file.name === 'package.json') {
const json = global.require(file.path);
if (json.main) {
let name = filePathRelativeToApp.substr(0, filePathRelativeToApp.length - 'package.json'.length - 1);
let requirePath = fs.path.join(file.parent.path, json.main);
const name = filePathRelativeToApp.substr(0, filePathRelativeToApp.length - 'package.json'.length - 1);
const requirePath = fs.path.join(file.parent.path, json.main);
register(name, () => global.require(requirePath));
}

View File

@ -1,6 +1,6 @@
const MIN_WH: string = 'minWH';
const MIN_W: string = 'minW';
const MIN_H: string = 'minH';
const MIN_WH = 'minWH';
const MIN_W = 'minW';
const MIN_H = 'minH';
const PRIORITY_STEP = 10000;
/**
@ -120,9 +120,9 @@ const supportedQualifiers: Array<QualifierSpec> = [minWidthHeightQualifier, minW
function checkQualifiers(path: string, context: PlatformContext): number {
let result = 0;
for (let i = 0; i < supportedQualifiers.length; i++) {
let qualifier = supportedQualifiers[i];
const qualifier = supportedQualifiers[i];
if (qualifier.isMatch(path)) {
let occurences = qualifier.getMatchOccurences(path);
const occurences = qualifier.getMatchOccurences(path);
// Always get the last qualifier among identical occurences
result = qualifier.getMatchValue(occurences[occurences.length - 1], context);
if (result < 0) {
@ -142,9 +142,9 @@ function checkQualifiers(path: string, context: PlatformContext): number {
export function stripQualifiers(path: string): string {
// Strip qualifiers from path if any
for (let i = 0; i < supportedQualifiers.length; i++) {
let qualifier = supportedQualifiers[i];
const qualifier = supportedQualifiers[i];
if (qualifier.isMatch(path)) {
let occurences = qualifier.getMatchOccurences(path);
const occurences = qualifier.getMatchOccurences(path);
for (let j = 0; j < occurences.length; j++) {
path = path.replace(occurences[j], '');
}
@ -155,7 +155,7 @@ export function stripQualifiers(path: string): string {
}
export function findMatch(path: string, ext: string, candidates: Array<string>, context: PlatformContext): string {
let fullPath: string = ext ? path + ext : path;
const fullPath: string = ext ? path + ext : path;
let bestValue = -1;
let result: string = null;

View File

@ -1,5 +1,5 @@
/* tslint:disable:class-name */
import { getNativeApplication, on, off, orientationChangedEvent, android as AndroidApplication } from '../application';
import { getNativeApplication, on, orientationChangedEvent, android as AndroidApplication } from '../application';
const MIN_TABLET_PIXELS = 600;

View File

@ -227,51 +227,51 @@ declare var MDCInkViewDelegate: {
prototype: MDCInkViewDelegate;
};
declare var MDCShadowElevationAppBar: number;
declare let MDCShadowElevationAppBar: number;
declare var MDCShadowElevationBottomNavigationBar: number;
declare let MDCShadowElevationBottomNavigationBar: number;
declare var MDCShadowElevationCardPickedUp: number;
declare let MDCShadowElevationCardPickedUp: number;
declare var MDCShadowElevationCardResting: number;
declare let MDCShadowElevationCardResting: number;
declare var MDCShadowElevationDialog: number;
declare let MDCShadowElevationDialog: number;
declare var MDCShadowElevationFABPressed: number;
declare let MDCShadowElevationFABPressed: number;
declare var MDCShadowElevationFABResting: number;
declare let MDCShadowElevationFABResting: number;
declare var MDCShadowElevationMenu: number;
declare let MDCShadowElevationMenu: number;
declare var MDCShadowElevationModalBottomSheet: number;
declare let MDCShadowElevationModalBottomSheet: number;
declare var MDCShadowElevationNavDrawer: number;
declare let MDCShadowElevationNavDrawer: number;
declare var MDCShadowElevationNone: number;
declare let MDCShadowElevationNone: number;
declare var MDCShadowElevationPicker: number;
declare let MDCShadowElevationPicker: number;
declare var MDCShadowElevationQuickEntry: number;
declare let MDCShadowElevationQuickEntry: number;
declare var MDCShadowElevationQuickEntryResting: number;
declare let MDCShadowElevationQuickEntryResting: number;
declare var MDCShadowElevationRaisedButtonPressed: number;
declare let MDCShadowElevationRaisedButtonPressed: number;
declare var MDCShadowElevationRaisedButtonResting: number;
declare let MDCShadowElevationRaisedButtonResting: number;
declare var MDCShadowElevationRefresh: number;
declare let MDCShadowElevationRefresh: number;
declare var MDCShadowElevationRightDrawer: number;
declare let MDCShadowElevationRightDrawer: number;
declare var MDCShadowElevationSearchBarResting: number;
declare let MDCShadowElevationSearchBarResting: number;
declare var MDCShadowElevationSearchBarScrolled: number;
declare let MDCShadowElevationSearchBarScrolled: number;
declare var MDCShadowElevationSnackbar: number;
declare let MDCShadowElevationSnackbar: number;
declare var MDCShadowElevationSubMenu: number;
declare let MDCShadowElevationSubMenu: number;
declare var MDCShadowElevationSwitch: number;
declare let MDCShadowElevationSwitch: number;
declare class MDCShadowLayer extends CALayer implements CALayerDelegate {
@ -716,7 +716,7 @@ declare class MDCTabBarViewController extends UIViewController implements MDCTab
tabBarWillSelectItem(tabBar: MDCTabBar, item: UITabBarItem): void;
}
declare var MDCTabBarViewControllerAnimationDuration: number;
declare let MDCTabBarViewControllerAnimationDuration: number;
declare class MDCTypography extends NSObject {
@ -804,6 +804,6 @@ declare var MDCTypographyFontLoading: {
prototype: MDCTypographyFontLoading;
};
declare var MaterialComponentsVersionNumber: number;
declare let MaterialComponentsVersionNumber: number;
declare var MaterialComponentsVersionString: interop.Reference<number>;
declare let MaterialComponentsVersionString: interop.Reference<number>;

View File

@ -1,5 +1,5 @@
declare var __startCPUProfiler: any;
declare var __stopCPUProfiler: any;
declare let __startCPUProfiler: any;
declare let __stopCPUProfiler: any;
export function uptime() {
return global.android ? (<any>org).nativescript.Process.getUpTime() : (<any>global).__tns_uptime();
@ -98,10 +98,10 @@ export function isRunning(name: string): boolean {
function countersProfileFunctionFactory<F extends Function>(fn: F, name: string, type: MemberType = MemberType.Instance): F {
profileNames.push(name);
return <any>function () {
return <any>function (...args) {
start(name);
try {
return fn.apply(this, arguments);
return fn(...args);
} finally {
stop(name);
}
@ -110,19 +110,19 @@ function countersProfileFunctionFactory<F extends Function>(fn: F, name: string,
function timelineProfileFunctionFactory<F extends Function>(fn: F, name: string, type: MemberType = MemberType.Instance): F {
return type === MemberType.Instance
? <any>function () {
? <any>function (...args) {
const start = time();
try {
return fn.apply(this, arguments);
return fn(...args);
} finally {
const end = time();
console.log(`Timeline: Modules: ${name} ${this} (${start}ms. - ${end}ms.)`);
}
}
: function () {
: function (...args) {
const start = time();
try {
return fn.apply(this, arguments);
return fn(...args);
} finally {
const end = time();
console.log(`Timeline: Modules: ${name} (${start}ms. - ${end}ms.)`);
@ -159,6 +159,7 @@ export function enable(mode: InstrumentationMode = 'counters') {
}
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const appConfig = require('~/package.json');
if (appConfig && appConfig.profiling) {
enable(appConfig.profiling);
@ -192,7 +193,7 @@ const profileMethodUnnamed = (target, key, descriptor) => {
className = target.constructor.name + '.';
}
let name = className + key;
const name = className + key;
//editing the descriptor/value parameter
descriptor.value = profileFunctionFactory(originalMethod, name, MemberType.Instance);
@ -213,7 +214,7 @@ const profileStaticMethodUnnamed = (ctor, key, descriptor) => {
if (ctor && ctor.name) {
className = ctor.name + '.';
}
let name = className + key;
const name = className + key;
//editing the descriptor/value parameter
descriptor.value = profileFunctionFactory(originalMethod, name, MemberType.Static);

View File

@ -1,6 +1,6 @@
export * from './text-common';
export module encoding {
export namespace encoding {
export const ISO_8859_1 = 'ISO-8859-1';
export const US_ASCII = 'US-ASCII';
export const UTF_16 = 'UTF-16';

View File

@ -3,7 +3,7 @@
/**
* Defines the supported character encodings.
*/
export module encoding {
export namespace encoding {
/**
* Denotes ISO-8859-1 character encoding.
*/

View File

@ -1,6 +1,6 @@
export * from './text-common';
export module encoding {
export namespace encoding {
export const ISO_8859_1 = 5; //NSISOLatin1StringEncoding
export const US_ASCII = 1; //NSASCIIStringEncoding
export const UTF_16 = 10; //NSUnicodeStringEncoding

View File

@ -2,11 +2,11 @@ const Object_prototype_toString = {}.toString;
const ArrayBufferString = Object_prototype_toString.call(ArrayBuffer.prototype);
function decoderReplacer(encoded) {
var codePoint = encoded.charCodeAt(0) << 24;
var leadingOnes = Math.clz32(~codePoint) | 0;
var endPos = 0,
stringLen = encoded.length | 0;
var result = '';
let codePoint = encoded.charCodeAt(0) << 24;
const leadingOnes = Math.clz32(~codePoint) | 0;
let endPos = 0;
const stringLen = encoded.length | 0;
let result = '';
if (leadingOnes < 5 && stringLen >= leadingOnes) {
codePoint = (codePoint << leadingOnes) >>> (24 + leadingOnes);
for (endPos = 1; endPos < leadingOnes; endPos = (endPos + 1) | 0) {
@ -35,9 +35,9 @@ function decoderReplacer(encoded) {
function encoderReplacer(nonAsciiChars) {
// make the UTF string into a binary UTF-8 encoded string
var point = nonAsciiChars.charCodeAt(0) | 0;
let point = nonAsciiChars.charCodeAt(0) | 0;
if (point >= 0xd800 && point <= 0xdbff) {
var nextcode = nonAsciiChars.charCodeAt(1) | 0;
const nextcode = nonAsciiChars.charCodeAt(1) | 0;
if (nextcode !== nextcode) {
// NaN because string is 1 code point long
return String.fromCharCode(0xef /*11101111*/, 0xbf /*10111111*/, 0xbd /*10111101*/);
@ -71,7 +71,7 @@ export class TextDecoder {
if (Object_prototype_toString.call(buffer) !== ArrayBufferString) {
throw Error("Failed to execute 'decode' on 'TextDecoder': The provided value is not of type '(ArrayBuffer or ArrayBufferView)'");
}
let inputAs8 = new Uint8Array(buffer);
const inputAs8 = new Uint8Array(buffer);
let resultingString = '';
for (let index = 0, len = inputAs8.length | 0; index < len; index = (index + 32768) | 0) {
resultingString += String.fromCharCode.apply(0, inputAs8.slice(index, (index + 32768) | 0));
@ -92,7 +92,7 @@ export class TextEncoder {
return 'utf-8';
}
public encode(input: string = ''): Uint8Array {
public encode(input = ''): Uint8Array {
// 0xc0 => 0b11000000; 0xff => 0b11111111; 0xc0-0xff => 0b11xxxxxx
// 0x80 => 0b10000000; 0xbf => 0b10111111; 0x80-0xbf => 0b10xxxxxx
const encodedString = input === undefined ? '' : ('' + input).replace(/[\x80-\uD7ff\uDC00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g, encoderReplacer);

View File

@ -43,7 +43,7 @@ export function setTimeout(callback: Function, milliseconds = 0, ...args): numbe
}
export function clearTimeout(id: number): void {
let index = id;
const index = id;
if (timeoutCallbacks[index]) {
timeoutHandler.removeCallbacks(timeoutCallbacks[index]);
delete timeoutCallbacks[index];

View File

@ -15,7 +15,7 @@ class TimerTargetImpl extends NSObject {
private shouldRepeat: boolean;
public static initWithCallback(callback: Function, id: number, shouldRepeat: boolean): TimerTargetImpl {
let handler = <TimerTargetImpl>TimerTargetImpl.new();
const handler = <TimerTargetImpl>TimerTargetImpl.new();
handler.callback = callback;
handler.id = id;
handler.shouldRepeat = shouldRepeat;
@ -37,7 +37,7 @@ class TimerTargetImpl extends NSObject {
if (!this.disposed) {
this.disposed = true;
let timer = timeoutCallbacks.get(this.id).k;
const timer = timeoutCallbacks.get(this.id).k;
timer.invalidate();
timeoutCallbacks.delete(this.id);
}
@ -53,14 +53,14 @@ function createTimerAndGetId(callback: Function, milliseconds: number, shouldRep
milliseconds += 0;
timerId++;
let id = timerId;
let timerTarget = TimerTargetImpl.initWithCallback(callback, id, shouldRepeat);
let timer = NSTimer.scheduledTimerWithTimeIntervalTargetSelectorUserInfoRepeats(milliseconds / 1000, timerTarget, 'tick', null, shouldRepeat);
const id = timerId;
const timerTarget = TimerTargetImpl.initWithCallback(callback, id, shouldRepeat);
const timer = NSTimer.scheduledTimerWithTimeIntervalTargetSelectorUserInfoRepeats(milliseconds / 1000, timerTarget, 'tick', null, shouldRepeat);
// https://github.com/NativeScript/NativeScript/issues/2116
NSRunLoop.currentRunLoop.addTimerForMode(timer, NSRunLoopCommonModes);
let pair: KeyValuePair<NSTimer, TimerTargetImpl> = {
const pair: KeyValuePair<NSTimer, TimerTargetImpl> = {
k: timer,
v: timerTarget,
};
@ -70,20 +70,20 @@ function createTimerAndGetId(callback: Function, milliseconds: number, shouldRep
}
export function setTimeout(callback: Function, milliseconds = 0, ...args): number {
let invoke = () => callback(...args);
const invoke = () => callback(...args);
return createTimerAndGetId(zonedCallback(invoke), milliseconds, false);
}
export function clearTimeout(id: number): void {
let pair = timeoutCallbacks.get(<number>(<any>id));
const pair = timeoutCallbacks.get(<number>(<any>id));
if (pair) {
pair.v.unregister();
}
}
export function setInterval(callback: Function, milliseconds = 0, ...args): number {
let invoke = () => callback(...args);
const invoke = () => callback(...args);
return createTimerAndGetId(zonedCallback(invoke), milliseconds, true);
}

View File

@ -22,8 +22,8 @@ export interface TraceErrorHandler {
let enabled = false;
let _categories = {};
let _writers: Array<TraceWriter> = [];
let _eventListeners: Array<TraceEventListener> = [];
const _writers: Array<TraceWriter> = [];
const _eventListeners: Array<TraceEventListener> = [];
let _errorHandler: TraceErrorHandler;
export namespace Trace {
@ -63,7 +63,7 @@ export namespace Trace {
* @param writer The TraceWriter instance to remove.
*/
export function removeWriter(writer: TraceWriter) {
let index = _writers.indexOf(writer);
const index = _writers.indexOf(writer);
if (index >= 0) {
_writers.splice(index, 1);
}
@ -92,7 +92,7 @@ export namespace Trace {
* @param categories The comma-separated list of categories. If not specified all messages from all categories will be traced.
*/
export function addCategories(categories: string) {
let split = categories.split(',');
const split = categories.split(',');
for (let i = 0; i < split.length; i++) {
_categories[split[i].trim()] = true;
}
@ -174,7 +174,7 @@ export namespace Trace {
}
}
export module messageType {
export namespace messageType {
export const log = 0;
export const info = 1;
export const warn = 2;
@ -184,7 +184,7 @@ export namespace Trace {
/**
* all predefined categories.
*/
export module categories {
export namespace categories {
export const VisualTreeEvents = 'VisualTreeEvents';
export const Layout = 'Layout';
export const Style = 'Style';
@ -206,13 +206,13 @@ export namespace Trace {
export function concat(...args: any): string {
let result: string;
for (let i = 0; i < arguments.length; i++) {
for (let i = 0; i < args.length; i++) {
if (!result) {
result = arguments[i];
result = args[i];
continue;
}
result = result.concat(separator, arguments[i]);
result = result.concat(separator, args[i]);
}
return result;

View File

@ -365,7 +365,7 @@ export function traceMissingIcon(icon: string) {
function convertToContentInset(this: void, value: string | Length): [CssProperty<any, any>, any][] {
if (typeof value === 'string' && value !== 'auto') {
let insets = value.split(/[ ,]+/);
const insets = value.split(/[ ,]+/);
return [
[androidContentInsetLeftProperty, Length.parse(insets[0])],

View File

@ -72,7 +72,7 @@ function initializeMenuItemClickListener(): void {
}
onMenuItemClick(item: android.view.MenuItem): boolean {
let itemId = item.getItemId();
const itemId = item.getItemId();
return this.owner._onAndroidItemSelected(itemId);
}
@ -225,7 +225,7 @@ export class ActionBar extends ActionBarBase {
// Find item with the right ID;
let menuItem: ActionItem = undefined;
let items = this.actionItems.getItems();
const items = this.actionItems.getItems();
for (let i = 0; i < items.length; i++) {
if ((<ActionItem>items[i])._getItemId() === itemId) {
menuItem = <ActionItem>items[i];
@ -262,11 +262,11 @@ export class ActionBar extends ActionBarBase {
// Set navigation content description, used by screen readers for the vision-impaired users
this.nativeViewProtected.setNavigationContentDescription(navButton.text || null);
let navBtn = new WeakRef(navButton);
const navBtn = new WeakRef(navButton);
this.nativeViewProtected.setNavigationOnClickListener(
new android.view.View.OnClickListener({
onClick: function (v) {
let owner = navBtn.get();
const owner = navBtn.get();
if (owner) {
owner._raiseTap();
}
@ -279,18 +279,18 @@ export class ActionBar extends ActionBarBase {
}
public _updateIcon() {
let visibility = getIconVisibility(this.android.iconVisibility);
const visibility = getIconVisibility(this.android.iconVisibility);
if (visibility) {
let icon = this.android.icon;
const icon = this.android.icon;
if (icon !== undefined) {
let drawableOrId = getDrawableOrResourceId(icon, appResources);
const drawableOrId = getDrawableOrResourceId(icon, appResources);
if (drawableOrId) {
this.nativeViewProtected.setLogo(drawableOrId);
} else {
traceMissingIcon(icon);
}
} else {
let defaultIcon = application.android.nativeApp.getApplicationInfo().icon;
const defaultIcon = application.android.nativeApp.getApplicationInfo().icon;
this.nativeViewProtected.setLogo(defaultIcon);
}
} else {
@ -301,13 +301,13 @@ export class ActionBar extends ActionBarBase {
public _updateTitleAndTitleView() {
if (!this.titleView) {
// No title view - show the title
let title = this.title;
const title = this.title;
if (title !== undefined) {
this.nativeViewProtected.setTitle(title);
} else {
let appContext = application.android.context;
let appInfo = appContext.getApplicationInfo();
let appLabel = appContext.getPackageManager().getApplicationLabel(appInfo);
const appContext = application.android.context;
const appInfo = appContext.getApplicationInfo();
const appLabel = appContext.getPackageManager().getApplicationLabel(appInfo);
if (appLabel) {
this.nativeViewProtected.setTitle(appLabel);
}
@ -316,13 +316,13 @@ export class ActionBar extends ActionBarBase {
}
public _addActionItems() {
let menu = this.nativeViewProtected.getMenu();
let items = this.actionItems.getVisibleItems();
const menu = this.nativeViewProtected.getMenu();
const items = this.actionItems.getVisibleItems();
menu.clear();
for (let i = 0; i < items.length; i++) {
let item = <ActionItem>items[i];
let menuItem = menu.add(android.view.Menu.NONE, item._getItemId(), android.view.Menu.NONE, item.text + '');
const item = <ActionItem>items[i];
const menuItem = menu.add(android.view.Menu.NONE, item._getItemId(), android.view.Menu.NONE, item.text + '');
if (item.actionView && item.actionView.android) {
// With custom action view, the menuitem cannot be displayed in a popup menu.
@ -331,7 +331,7 @@ export class ActionBar extends ActionBarBase {
ActionBar._setOnClickListener(item);
} else if (item.android.systemIcon) {
// Try to look in the system resources.
let systemResourceId = getSystemResourceId(item.android.systemIcon);
const systemResourceId = getSystemResourceId(item.android.systemIcon);
if (systemResourceId) {
menuItem.setIcon(systemResourceId);
}
@ -342,7 +342,7 @@ export class ActionBar extends ActionBarBase {
}
}
let showAsAction = getShowAsAction(item);
const showAsAction = getShowAsAction(item);
menuItem.setShowAsAction(showAsAction);
}
}
@ -471,13 +471,13 @@ function getDrawableOrResourceId(icon: string, resources: android.content.res.Re
let result = null;
if (icon.indexOf(RESOURCE_PREFIX) === 0) {
let resourceId: number = resources.getIdentifier(icon.substr(RESOURCE_PREFIX.length), 'drawable', application.android.packageName);
const resourceId: number = resources.getIdentifier(icon.substr(RESOURCE_PREFIX.length), 'drawable', application.android.packageName);
if (resourceId > 0) {
result = resourceId;
}
} else {
let drawable: android.graphics.drawable.BitmapDrawable;
let is = ImageSource.fromFileOrResourceSync(icon);
const is = ImageSource.fromFileOrResourceSync(icon);
if (is) {
drawable = new android.graphics.drawable.BitmapDrawable(appResources, is.android);
}

View File

@ -40,14 +40,14 @@ class TapBarItemHandlerImpl extends NSObject {
private _owner: WeakRef<ActionItemDefinition>;
public static initWithOwner(owner: WeakRef<ActionItemDefinition>): TapBarItemHandlerImpl {
let handler = <TapBarItemHandlerImpl>TapBarItemHandlerImpl.new();
const handler = <TapBarItemHandlerImpl>TapBarItemHandlerImpl.new();
handler._owner = owner;
return handler;
}
public tap(args) {
let owner = this._owner.get();
const owner = this._owner.get();
if (owner) {
owner._raiseTap();
}
@ -184,8 +184,8 @@ export class ActionBar extends ActionBarBase {
// Set back button text
if (previousController) {
if (this.navigationButton) {
let tapHandler = TapBarItemHandlerImpl.initWithOwner(new WeakRef(this.navigationButton));
let barButtonItem = UIBarButtonItem.alloc().initWithTitleStyleTargetAction(this.navigationButton.text + '', UIBarButtonItemStyle.Plain, tapHandler, 'tap');
const tapHandler = TapBarItemHandlerImpl.initWithOwner(new WeakRef(this.navigationButton));
const barButtonItem = UIBarButtonItem.alloc().initWithTitleStyleTargetAction(this.navigationButton.text + '', UIBarButtonItemStyle.Plain, tapHandler, 'tap');
previousController.navigationItem.backBarButtonItem = barButtonItem;
} else {
previousController.navigationItem.backBarButtonItem = null;
@ -202,7 +202,7 @@ export class ActionBar extends ActionBarBase {
// show the one from the old page but the new page will still be visible (because we canceled EdgeBackSwipe gesutre)
// Consider moving this to new method and call it from - navigationControllerDidShowViewControllerAnimated.
if (img) {
let image = img.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
const image = img.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
navigationBar.backIndicatorImage = image;
navigationBar.backIndicatorTransitionMaskImage = image;
} else {
@ -257,7 +257,7 @@ export class ActionBar extends ActionBarBase {
let barButtonItem: UIBarButtonItem;
if (item.actionView && item.actionView.ios) {
let recognizer = UITapGestureRecognizer.alloc().initWithTargetAction(tapHandler, 'tap');
const recognizer = UITapGestureRecognizer.alloc().initWithTargetAction(tapHandler, 'tap');
item.actionView.ios.addGestureRecognizer(recognizer);
barButtonItem = UIBarButtonItem.alloc().initWithCustomView(item.actionView.ios);
} else if (item.ios.systemIcon !== undefined) {
@ -320,7 +320,7 @@ export class ActionBar extends ActionBarBase {
page.frame._updateActionBar();
}
let navigationItem: UINavigationItem = (<UIViewController>page.ios).navigationItem;
const navigationItem: UINavigationItem = (<UIViewController>page.ios).navigationItem;
navigationItem.title = this.title;
}
@ -408,9 +408,9 @@ export class ActionBar extends ActionBarBase {
return null;
}
[backgroundColorProperty.setNative](value: UIColor | Color) {
let navBar = this.navBar;
const navBar = this.navBar;
if (navBar) {
let color = value instanceof Color ? value.ios : value;
const color = value instanceof Color ? value.ios : value;
navBar.barTintColor = color;
}
}

View File

@ -33,7 +33,7 @@ export class ActivityIndicator extends ActivityIndicatorBase {
}
}
[busyProperty.setNative](value: boolean) {
let nativeView = this.nativeViewProtected;
const nativeView = this.nativeViewProtected;
if (value) {
nativeView.startAnimating();
} else {

View File

@ -9,7 +9,7 @@ import { PercentLength } from '../styling/style-properties';
export * from './animation-interfaces';
export module Properties {
export namespace Properties {
export const opacity = 'opacity';
export const backgroundColor = 'backgroundColor';
export const translate = 'translate';
@ -100,15 +100,15 @@ export abstract class AnimationBase implements AnimationBaseDefinition {
_this.cancel();
};
const _then = promise.then;
promise.then = function () {
const r = _then.apply(promise, arguments);
promise.then = function (...args) {
const r = _then(...args);
_this.fixupAnimationPromise(r);
return r;
};
const _catch = promise.catch;
promise.catch = function () {
const r = _catch.apply(promise, arguments);
promise.catch = function (...args) {
const r = _catch(...args);
_this.fixupAnimationPromise(r);
return r;
@ -138,7 +138,7 @@ export abstract class AnimationBase implements AnimationBaseDefinition {
throw new Error('No animation target specified.');
}
for (let item in animationDefinition) {
for (const item in animationDefinition) {
const value = animationDefinition[item];
if (value === undefined) {
continue;

View File

@ -18,7 +18,10 @@ export type TransformFunctionsInfo = {
scale: Pair;
};
export type AnimationPromise = Promise<void> & Cancelable;
export interface AnimationPromise extends Promise<any>, Cancelable {
then(...args):AnimationPromise
catch(...args):AnimationPromise
};
export interface Pair {
x: number;

View File

@ -21,14 +21,14 @@ function ensureArgbEvaluator() {
}
}
let easeIn = lazy(() => new android.view.animation.AccelerateInterpolator(1));
let easeOut = lazy(() => new android.view.animation.DecelerateInterpolator(1));
let easeInOut = lazy(() => new android.view.animation.AccelerateDecelerateInterpolator());
let linear = lazy(() => new android.view.animation.LinearInterpolator());
let bounce = lazy(() => new android.view.animation.BounceInterpolator());
const easeIn = lazy(() => new android.view.animation.AccelerateInterpolator(1));
const easeOut = lazy(() => new android.view.animation.DecelerateInterpolator(1));
const easeInOut = lazy(() => new android.view.animation.AccelerateDecelerateInterpolator());
const linear = lazy(() => new android.view.animation.LinearInterpolator());
const bounce = lazy(() => new android.view.animation.BounceInterpolator());
let keyPrefix = 'ui.animation.';
let propertyKeys = {};
const keyPrefix = 'ui.animation.';
const propertyKeys = {};
propertyKeys[Properties.backgroundColor] = Symbol(keyPrefix + Properties.backgroundColor);
propertyKeys[Properties.opacity] = Symbol(keyPrefix + Properties.opacity);
propertyKeys[Properties.rotate] = Symbol(keyPrefix + Properties.rotate);
@ -92,7 +92,7 @@ function getAndroidRepeatCount(iterations: number): number {
}
function createObjectAnimator(nativeView: android.view.View, propertyName: string, value: number): android.animation.ObjectAnimator {
let arr = Array.create('float', 1);
const arr = Array.create('float', 1);
arr[0] = value;
return android.animation.ObjectAnimator.ofFloat(nativeView, propertyName, arr);
@ -126,7 +126,7 @@ export class Animation extends AnimationBase {
private _propertyResetCallbacks: Array<Function>;
private _valueSource: 'animation' | 'keyframe';
private _target: View;
private _resetOnFinish: boolean = true;
private _resetOnFinish = true;
constructor(animationDefinitions: Array<AnimationDefinitionInternal>, playSequentially?: boolean) {
super(animationDefinitions, playSequentially);
@ -136,7 +136,7 @@ export class Animation extends AnimationBase {
this._valueSource = animationDefinitions[0].valueSource;
}
let that = new WeakRef(this);
const that = new WeakRef(this);
this._animatorListener = new android.animation.Animator.AnimatorListener({
onAnimationStart: function (animator: android.animation.Animator): void {
if (Trace.isEnabled()) {
@ -300,7 +300,7 @@ export class Animation extends AnimationBase {
let originalValue3;
const density = layout.getDisplayDensity();
let key = propertyKeys[propertyAnimation.property];
const key = propertyKeys[propertyAnimation.property];
if (key) {
propertyAnimation.target[key] = propertyAnimation;
}
@ -313,7 +313,7 @@ export class Animation extends AnimationBase {
};
}
let setLocal = this._valueSource === 'animation';
const setLocal = this._valueSource === 'animation';
const style = propertyAnimation.target.style;
switch (propertyAnimation.property) {
case Properties.opacity:
@ -340,7 +340,7 @@ export class Animation extends AnimationBase {
animators.push(createObjectAnimator(nativeView, 'alpha', propertyAnimation.value));
break;
case Properties.backgroundColor:
case Properties.backgroundColor:{
backgroundColorProperty._initDefaultNativeValue(style);
ensureArgbEvaluator();
@ -348,11 +348,11 @@ export class Animation extends AnimationBase {
const nativeArray = Array.create(java.lang.Object, 2);
nativeArray[0] = propertyAnimation.target.backgroundColor ? java.lang.Integer.valueOf((<Color>propertyAnimation.target.backgroundColor).argb) : java.lang.Integer.valueOf(-1);
nativeArray[1] = java.lang.Integer.valueOf((<Color>propertyAnimation.value).argb);
let animator = android.animation.ValueAnimator.ofObject(argbEvaluator, nativeArray);
const animator = android.animation.ValueAnimator.ofObject(argbEvaluator, nativeArray);
animator.addUpdateListener(
new android.animation.ValueAnimator.AnimatorUpdateListener({
onAnimationUpdate(animator: android.animation.ValueAnimator) {
let argb = (<java.lang.Integer>animator.getAnimatedValue()).intValue();
const argb = (<java.lang.Integer>animator.getAnimatedValue()).intValue();
propertyAnimation.target.style[setLocal ? backgroundColorProperty.name : backgroundColorProperty.keyframe] = new Color(argb);
},
})
@ -378,7 +378,7 @@ export class Animation extends AnimationBase {
);
animators.push(animator);
break;
}
case Properties.translate:
translateXProperty._initDefaultNativeValue(style);
translateYProperty._initDefaultNativeValue(style);
@ -494,18 +494,18 @@ export class Animation extends AnimationBase {
extentProperty._initDefaultNativeValue(style);
const nativeArray = Array.create('float', 2);
let toValue = propertyAnimation.value;
let parent = propertyAnimation.target.parent as View;
const parent = propertyAnimation.target.parent as View;
if (!parent) {
throw new Error(`cannot animate ${propertyAnimation.property} on root view`);
}
const parentExtent: number = isVertical ? parent.getMeasuredHeight() : parent.getMeasuredWidth();
toValue = PercentLength.toDevicePixels(toValue, parentExtent, parentExtent) / Screen.mainScreen.scale;
let nativeHeight: number = isVertical ? nativeView.getHeight() : nativeView.getWidth();
const nativeHeight: number = isVertical ? nativeView.getHeight() : nativeView.getWidth();
const targetStyle: string = setLocal ? extentProperty.name : extentProperty.keyframe;
originalValue1 = nativeHeight / Screen.mainScreen.scale;
nativeArray[0] = originalValue1;
nativeArray[1] = toValue;
let extentAnimator = android.animation.ValueAnimator.ofFloat(nativeArray);
const extentAnimator = android.animation.ValueAnimator.ofFloat(nativeArray);
extentAnimator.addUpdateListener(
new android.animation.ValueAnimator.AnimatorUpdateListener({
onAnimationUpdate(animator: android.animation.ValueAnimator) {

View File

@ -14,10 +14,10 @@ import { Screen } from '../../platform';
export * from './animation-common';
export { KeyframeAnimation, KeyframeAnimationInfo, KeyframeDeclaration, KeyframeInfo } from './keyframe-animation';
let _transform = '_transform';
let _skip = '_skip';
const _transform = '_transform';
const _skip = '_skip';
let FLT_MAX = 340282346638528859811704183484516925440.0;
const FLT_MAX = 340282346638528859811704183484516925440.0;
class AnimationInfo {
public propertyNameToAnimate: string;
@ -41,7 +41,7 @@ class AnimationDelegateImpl extends NSObject implements CAAnimationDelegate {
private _valueSource: 'animation' | 'keyframe';
public static initWithFinishedCallback(finishedCallback: Function, propertyAnimation: PropertyAnimationInfo, valueSource: 'animation' | 'keyframe'): AnimationDelegateImpl {
let delegate = <AnimationDelegateImpl>AnimationDelegateImpl.new();
const delegate = <AnimationDelegateImpl>AnimationDelegateImpl.new();
delegate._finishedCallback = finishedCallback;
delegate._propertyAnimation = propertyAnimation;
delegate._valueSource = valueSource;
@ -50,9 +50,9 @@ class AnimationDelegateImpl extends NSObject implements CAAnimationDelegate {
}
animationDidStart(anim: CAAnimation): void {
let value = this._propertyAnimation.value;
let setLocal = this._valueSource === 'animation';
let targetStyle = this._propertyAnimation.target.style;
const value = this._propertyAnimation.value;
const setLocal = this._valueSource === 'animation';
const targetStyle = this._propertyAnimation.target.style;
(<IOSView>this._propertyAnimation.target)._suspendPresentationLayerUpdates();
@ -93,8 +93,8 @@ class AnimationDelegateImpl extends NSObject implements CAAnimationDelegate {
targetStyle[setLocal ? rotateProperty.name : rotateProperty.keyframe] = value[Properties.rotate].z;
}
if (value[Properties.scale] !== undefined) {
let x = value[Properties.scale].x;
let y = value[Properties.scale].y;
const x = value[Properties.scale].x;
const y = value[Properties.scale].y;
targetStyle[setLocal ? scaleXProperty.name : scaleXProperty.keyframe] = x === 0 ? 0.001 : x;
targetStyle[setLocal ? scaleYProperty.name : scaleYProperty.keyframe] = y === 0 ? 0.001 : y;
}
@ -132,7 +132,7 @@ export function _resolveAnimationCurve(curve: string | CubicBezierAnimationCurve
if (curve instanceof CAMediaTimingFunction) {
return curve;
} else if (curve instanceof CubicBezierAnimationCurve) {
let animationCurve = <CubicBezierAnimationCurve>curve;
const animationCurve = <CubicBezierAnimationCurve>curve;
return CAMediaTimingFunction.functionWithControlPoints(animationCurve.x1, animationCurve.y1, animationCurve.x2, animationCurve.y2);
} else {
@ -168,8 +168,8 @@ export class Animation extends AnimationBase {
this._mergedPropertyAnimations = this._propertyAnimations;
}
let that = this;
let animationFinishedCallback = (cancelled: boolean) => {
const that = this;
const animationFinishedCallback = (cancelled: boolean) => {
if (that._playSequentially) {
// This function will be called by the last animation when done or by another animation if the user cancels them halfway through.
if (cancelled) {
@ -207,7 +207,7 @@ export class Animation extends AnimationBase {
return this._rejectAlreadyPlaying();
}
let animationFinishedPromise = super.play();
const animationFinishedPromise = super.play();
this._finishedAnimations = 0;
this._cancelledAnimations = 0;
this._iOSAnimationFunction();
@ -223,9 +223,9 @@ export class Animation extends AnimationBase {
}
let i = 0;
let length = this._mergedPropertyAnimations.length;
const length = this._mergedPropertyAnimations.length;
for (; i < length; i++) {
let propertyAnimation = this._mergedPropertyAnimations[i];
const propertyAnimation = this._mergedPropertyAnimations[i];
propertyAnimation.target.nativeViewProtected.layer.removeAllAnimations();
if (propertyAnimation._propertyResetCallback) {
propertyAnimation._propertyResetCallback(propertyAnimation._originalValue, this._valueSource);
@ -248,8 +248,8 @@ export class Animation extends AnimationBase {
return;
}
let animation = propertyAnimations[index];
let args = Animation._getNativeAnimationArguments(animation, valueSource);
const animation = propertyAnimations[index];
const args = Animation._getNativeAnimationArguments(animation, valueSource);
if (animation.curve === 'spring') {
Animation._createNativeSpringAnimation(propertyAnimations, index, playSequentially, args, animation, valueSource, finishedCallback);
@ -269,7 +269,7 @@ export class Animation extends AnimationBase {
let subPropertyNameToAnimate;
let toValue = animation.value;
let fromValue;
let setLocal = valueSource === 'animation';
const setLocal = valueSource === 'animation';
switch (animation.property) {
case Properties.backgroundColor:
@ -380,7 +380,7 @@ export class Animation extends AnimationBase {
toValue = NSValue.valueWithCATransform3D(Animation._createNativeAffineTransform(animation));
break;
case Properties.width:
case Properties.height:
case Properties.height:{
const direction: string = animation.property;
const isHeight: boolean = direction === 'height';
propertyNameToAnimate = 'bounds';
@ -389,9 +389,9 @@ export class Animation extends AnimationBase {
}
const parentExtent: number = isHeight ? parent.getMeasuredHeight() : parent.getMeasuredWidth();
const asNumber = PercentLength.toDevicePixels(PercentLength.parse(toValue), parentExtent, parentExtent) / Screen.mainScreen.scale;
let currentBounds = nativeView.layer.bounds;
let extentX = isHeight ? currentBounds.size.width : asNumber;
let extentY = isHeight ? asNumber : currentBounds.size.height;
const currentBounds = nativeView.layer.bounds;
const extentX = isHeight ? currentBounds.size.width : asNumber;
const extentY = isHeight ? asNumber : currentBounds.size.height;
fromValue = NSValue.valueWithCGRect(currentBounds);
toValue = NSValue.valueWithCGRect(CGRectMake(currentBounds.origin.x, currentBounds.origin.y, extentX, extentY));
animation._originalValue = view.height;
@ -400,6 +400,7 @@ export class Animation extends AnimationBase {
style[setLocal ? prop.name : prop.keyframe] = value;
};
break;
}
default:
throw new Error(`Animating property '${animation.property}' is unsupported`);
}
@ -435,7 +436,7 @@ export class Animation extends AnimationBase {
}
private static _createNativeAnimation(propertyAnimations: Array<PropertyAnimation>, index: number, playSequentially: boolean, args: AnimationInfo, animation: PropertyAnimation, valueSource: 'animation' | 'keyframe', finishedCallback: (cancelled?: boolean) => void) {
let nativeView = <UIView>animation.target.nativeViewProtected;
const nativeView = <UIView>animation.target.nativeViewProtected;
let nativeAnimation;
if (args.subPropertiesToAnimate) {
@ -444,7 +445,7 @@ export class Animation extends AnimationBase {
nativeAnimation = this._createBasicAnimation(args, animation);
}
let animationDelegate = AnimationDelegateImpl.initWithFinishedCallback(finishedCallback, animation, valueSource);
const animationDelegate = AnimationDelegateImpl.initWithFinishedCallback(finishedCallback, animation, valueSource);
nativeAnimation.setValueForKey(animationDelegate, 'delegate');
nativeView.layer.addAnimationForKey(nativeAnimation, args.propertyNameToAnimate);
@ -461,7 +462,7 @@ export class Animation extends AnimationBase {
}
private static _createGroupAnimation(args: AnimationInfo, animation: PropertyAnimation) {
let groupAnimation = CAAnimationGroup.new();
const groupAnimation = CAAnimationGroup.new();
groupAnimation.duration = args.duration;
const animations = NSMutableArray.alloc<CAAnimation>().initWithCapacity(3);
@ -481,7 +482,7 @@ export class Animation extends AnimationBase {
}
private static _createBasicAnimation(args: AnimationInfo, animation: PropertyAnimation) {
let basicAnimation = CABasicAnimation.animationWithKeyPath(args.propertyNameToAnimate);
const basicAnimation = CABasicAnimation.animationWithKeyPath(args.propertyNameToAnimate);
basicAnimation.fromValue = args.fromValue;
basicAnimation.toValue = args.toValue;
basicAnimation.duration = args.duration;
@ -499,7 +500,7 @@ export class Animation extends AnimationBase {
}
private static _createNativeSpringAnimation(propertyAnimations: Array<PropertyAnimationInfo>, index: number, playSequentially: boolean, args: AnimationInfo, animation: PropertyAnimationInfo, valueSource: 'animation' | 'keyframe', finishedCallback: (cancelled?: boolean) => void) {
let nativeView = <UIView>animation.target.nativeViewProtected;
const nativeView = <UIView>animation.target.nativeViewProtected;
let callback = undefined;
let nextAnimation;
@ -575,7 +576,7 @@ export class Animation extends AnimationBase {
}
}
if (finishedCallback) {
let cancelled = !animationDidFinish;
const cancelled = !animationDidFinish;
finishedCallback(cancelled);
}
if (animationDidFinish && nextAnimation) {
@ -586,18 +587,18 @@ export class Animation extends AnimationBase {
}
private static _createNativeAffineTransform(animation: PropertyAnimation): CATransform3D {
let value = animation.value;
const value = animation.value;
let result: CATransform3D = CATransform3DIdentity;
if (value[Properties.translate] !== undefined) {
let x = value[Properties.translate].x;
let y = value[Properties.translate].y;
const x = value[Properties.translate].x;
const y = value[Properties.translate].y;
result = CATransform3DTranslate(result, x, y, 0);
}
if (value[Properties.scale] !== undefined) {
let x = value[Properties.scale].x;
let y = value[Properties.scale].y;
const x = value[Properties.scale].x;
const y = value[Properties.scale].y;
result = CATransform3DScale(result, x === 0 ? 0.001 : x, y === 0 ? 0.001 : y, 1);
}
@ -609,17 +610,17 @@ export class Animation extends AnimationBase {
}
private static _canBeMerged(animation1: PropertyAnimation, animation2: PropertyAnimation) {
let result = Animation._isAffineTransform(animation1.property) && Animation._isAffineTransform(animation2.property) && animation1.target === animation2.target && animation1.duration === animation2.duration && animation1.delay === animation2.delay && animation1.iterations === animation2.iterations && animation1.curve === animation2.curve;
const result = Animation._isAffineTransform(animation1.property) && Animation._isAffineTransform(animation2.property) && animation1.target === animation2.target && animation1.duration === animation2.duration && animation1.delay === animation2.delay && animation1.iterations === animation2.iterations && animation1.curve === animation2.curve;
return result;
}
private static _mergeAffineTransformAnimations(propertyAnimations: Array<PropertyAnimation>): Array<PropertyAnimation> {
let result = new Array<PropertyAnimation>();
const result = new Array<PropertyAnimation>();
let i = 0;
let j;
let length = propertyAnimations.length;
const length = propertyAnimations.length;
for (; i < length; i++) {
if (propertyAnimations[i][_skip]) {
continue;
@ -636,7 +637,7 @@ export class Animation extends AnimationBase {
// rotate: 90,
// scale: {x: 2, y: 2 }
// }
let newTransformAnimation: PropertyAnimation = {
const newTransformAnimation: PropertyAnimation = {
target: propertyAnimations[i].target,
property: _transform,
value: {},

View File

@ -58,8 +58,8 @@ interface Keyframe {
export class KeyframeAnimation {
public animations: Array<Keyframe>;
public delay: number = 0;
public iterations: number = 1;
public delay = 0;
public iterations = 1;
private _resolve;
private _isPlaying: boolean;
@ -69,22 +69,22 @@ export class KeyframeAnimation {
public static keyframeAnimationFromInfo(info: KeyframeAnimationInfo): KeyframeAnimation {
const length = info.keyframes.length;
let animations = new Array<Keyframe>();
const animations = new Array<Keyframe>();
let startDuration = 0;
if (info.isReverse) {
for (let index = length - 1; index >= 0; index--) {
let keyframe = info.keyframes[index];
const keyframe = info.keyframes[index];
startDuration = KeyframeAnimation.parseKeyframe(info, keyframe, animations, startDuration);
}
} else {
for (let index = 0; index < length; index++) {
let keyframe = info.keyframes[index];
const keyframe = info.keyframes[index];
startDuration = KeyframeAnimation.parseKeyframe(info, keyframe, animations, startDuration);
}
for (let index = length - 1; index > 0; index--) {
let a1 = animations[index];
let a2 = animations[index - 1];
const a1 = animations[index];
const a2 = animations[index - 1];
if (a2['curve'] !== undefined) {
a1['curve'] = a2['curve'];
a2['curve'] = undefined;
@ -104,8 +104,8 @@ export class KeyframeAnimation {
}
private static parseKeyframe(info: KeyframeAnimationInfo, keyframe: KeyframeInfo, animations: Array<Object>, startDuration: number): number {
let animation: Keyframe = {};
for (let declaration of keyframe.declarations) {
const animation: Keyframe = {};
for (const declaration of keyframe.declarations) {
animation[declaration.property] = declaration.value;
}
@ -138,13 +138,13 @@ export class KeyframeAnimation {
this._isPlaying = false;
for (let i = this._nativeAnimations.length - 1; i >= 0; i--) {
let animation = this._nativeAnimations[i];
const animation = this._nativeAnimations[i];
if (animation.isPlaying) {
animation.cancel();
}
}
if (this._nativeAnimations.length > 0) {
let animation = this._nativeAnimations[0];
const animation = this._nativeAnimations[0];
this._resetAnimationValues(this._target, animation);
}
this._resetAnimations();
@ -159,7 +159,7 @@ export class KeyframeAnimation {
});
}
let animationFinishedPromise = new Promise<void>((resolve) => {
const animationFinishedPromise = new Promise<void>((resolve) => {
this._resolve = resolve;
});
@ -181,7 +181,7 @@ export class KeyframeAnimation {
return;
}
if (index === 0) {
let animation = this.animations[0];
const animation = this.animations[0];
if ('backgroundColor' in animation) {
view.style[backgroundColorProperty.keyframe] = animation.backgroundColor;
@ -216,7 +216,7 @@ export class KeyframeAnimation {
this.animate(view, 0, iterations);
} else {
if (this._isForwards === false) {
let animation = this.animations[this.animations.length - 1];
const animation = this.animations[this.animations.length - 1];
this._resetAnimationValues(view, animation);
}
this._resolveAnimationFinishedPromise();
@ -228,7 +228,7 @@ export class KeyframeAnimation {
if (cachedAnimation) {
animation = cachedAnimation;
} else {
let animationDef = this.animations[index];
const animationDef = this.animations[index];
(<any>animationDef).target = view;
animation = new Animation([animationDef]);
this._nativeAnimations.push(animation);

View File

@ -400,7 +400,7 @@ export class BottomNavigation extends TabNavigationBase {
}
}
private setIconColor(tabStripItem: TabStripItem, forceReload: boolean = false): void {
private setIconColor(tabStripItem: TabStripItem, forceReload = false): void {
if (forceReload || (!this._unSelectedItemColor && !this._selectedItemColor)) {
// if selectedItemColor or unSelectedItemColor is set we don't respect the color from the style
const tabStripColor = this.selectedIndex === tabStripItem._index ? this._selectedItemColor : this._unSelectedItemColor;

View File

@ -1,7 +1,7 @@
// regex that contains all symbols applicable for expression used to AI detect an expression.
const expressionSymbolsRegex = /[\+\-\*\/%\?:<>=!\|&\(\)^~]/;
const expressionSymbolsRegex = /[+-*/%?:<>=!|&()^~]/;
export module bindingConstants {
export namespace bindingConstants {
export const sourceProperty = 'sourceProperty';
export const targetProperty = 'targetProperty';
export const expression = 'expression';
@ -185,7 +185,7 @@ export function getBindingOptions(name: string, value: string): any {
targetProperty: name,
};
for (let prop in bindingOptionsParameters) {
for (const prop in bindingOptionsParameters) {
if (bindingOptionsParameters.hasOwnProperty(prop)) {
bindOptions[prop] = bindingOptionsParameters[prop];
}

View File

@ -100,6 +100,7 @@ const createComponentInstance = profile('createComponentInstance', (elementName:
// Create instance of the component.
instance = new instanceType();
} catch (ex) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const debug: typeof debugModule = require('../../../utils/debug');
throw new debug.ScopeError(ex, "Module '" + (resolvedModuleName || elementName) + "' not found for element '" + (namespace ? namespace + ':' : '') + elementName + "'.");
}
@ -131,7 +132,7 @@ const applyComponentCss = profile('applyComponentCss', (instance: View, moduleNa
let cssApplied = false;
if (attributes && attributes[CSS_FILE]) {
let resolvedCssModuleName = resolveModuleName(sanitizeModuleName(attributes[CSS_FILE]), 'css');
const resolvedCssModuleName = resolveModuleName(sanitizeModuleName(attributes[CSS_FILE]), 'css');
if (resolvedCssModuleName) {
instance.addCssFile(resolvedCssModuleName);
@ -142,7 +143,7 @@ const applyComponentCss = profile('applyComponentCss', (instance: View, moduleNa
}
if (moduleName && !cssApplied) {
let resolvedCssModuleName = resolveModuleName(moduleName, 'css');
const resolvedCssModuleName = resolveModuleName(moduleName, 'css');
if (resolvedCssModuleName) {
instance.addCssFile(resolvedCssModuleName);
}
@ -252,7 +253,7 @@ function isBinding(value: any): boolean {
}
// For example, ListView.itemTemplateSelector
let KNOWN_FUNCTIONS = 'knownFunctions';
const KNOWN_FUNCTIONS = 'knownFunctions';
function isKnownFunction(name: string, instance: View): boolean {
return instance.constructor && KNOWN_FUNCTIONS in instance.constructor && instance.constructor[KNOWN_FUNCTIONS].indexOf(name) !== -1;
}

View File

@ -44,7 +44,7 @@ export class Builder {
} else if (entry.moduleName) {
const moduleName = sanitizeModuleName(entry.moduleName);
const resolvedCodeModuleName = resolveModuleName(moduleName, ''); //`${moduleName}.xml`;
let moduleExports = resolvedCodeModuleName ? global.loadModule(resolvedCodeModuleName, true) : null;
const moduleExports = resolvedCodeModuleName ? global.loadModule(resolvedCodeModuleName, true) : null;
if (moduleExports && moduleExports.createPage) {
// Exports has a createPage() method
@ -147,7 +147,7 @@ function loadInternal(moduleName: string, moduleExports: any): ComponentModule {
return componentModule;
}
function loadCustomComponent(componentNamespace: string, componentName?: string, attributes?: Object, context?: Object, parentPage?: View, isRootComponent: boolean = true, moduleNamePath?: string): ComponentModule {
function loadCustomComponent(componentNamespace: string, componentName?: string, attributes?: Object, context?: Object, parentPage?: View, isRootComponent = true, moduleNamePath?: string): ComponentModule {
if (!parentPage && context) {
// Read the parent page that was passed down below
// https://github.com/NativeScript/NativeScript/issues/1639
@ -183,7 +183,7 @@ function loadCustomComponent(componentNamespace: string, componentName?: string,
// Attributes will be transferred to the custom component
if (isDefined(result) && isDefined(result.component) && isDefined(attributes)) {
for (let attr in attributes) {
for (const attr in attributes) {
setPropertyValue(result.component, subExports, context, attr, attributes[attr]);
}
}
@ -489,7 +489,7 @@ namespace xml2ui {
this._state = TemplateParser.State.FINISHED;
if (this._setTemplateProperty && this._templateProperty.name in this._templateProperty.parent.component) {
let template = this.buildTemplate();
const template = this.buildTemplate();
this._templateProperty.parent.component[this._templateProperty.name] = template;
}
}
@ -528,7 +528,7 @@ namespace xml2ui {
public parse(args: xml.ParserEvent): XmlStateConsumer {
if (args.eventType === xml.ParserEventType.StartElement && args.elementName === 'template') {
let childParser = new TemplateParser(this, this.templateProperty, false);
const childParser = new TemplateParser(this, this.templateProperty, false);
childParser['key'] = args.attributes['key'];
this._childParsers.push(childParser);
@ -536,9 +536,9 @@ namespace xml2ui {
}
if (args.eventType === xml.ParserEventType.EndElement) {
let name = ComponentParser.getComplexPropertyName(args.elementName);
const name = ComponentParser.getComplexPropertyName(args.elementName);
if (name === this.templateProperty.name) {
let templates = new Array<KeyedTemplate>();
const templates = new Array<KeyedTemplate>();
for (let i = 0; i < this._childParsers.length; i++) {
templates.push({
key: this._childParsers[i]['key'],

View File

@ -3,7 +3,7 @@
* @param moduleName the name
* @param removeExtension whether to remove extension
*/
export function sanitizeModuleName(moduleName: string, removeExtension: boolean = true): string {
export function sanitizeModuleName(moduleName: string, removeExtension = true): string {
moduleName = moduleName.trim();
if (moduleName.startsWith('~/')) {

View File

@ -66,8 +66,8 @@ export class Button extends ButtonBase {
};
}
[borderTopWidthProperty.setNative](value: Length) {
let inset = this.nativeViewProtected.contentEdgeInsets;
let top = layout.toDeviceIndependentPixels(this.effectivePaddingTop + this.effectiveBorderTopWidth);
const inset = this.nativeViewProtected.contentEdgeInsets;
const top = layout.toDeviceIndependentPixels(this.effectivePaddingTop + this.effectiveBorderTopWidth);
this.nativeViewProtected.contentEdgeInsets = {
top: top,
left: inset.left,
@ -83,8 +83,8 @@ export class Button extends ButtonBase {
};
}
[borderRightWidthProperty.setNative](value: Length) {
let inset = this.nativeViewProtected.contentEdgeInsets;
let right = layout.toDeviceIndependentPixels(this.effectivePaddingRight + this.effectiveBorderRightWidth);
const inset = this.nativeViewProtected.contentEdgeInsets;
const right = layout.toDeviceIndependentPixels(this.effectivePaddingRight + this.effectiveBorderRightWidth);
this.nativeViewProtected.contentEdgeInsets = {
top: inset.top,
left: inset.left,
@ -100,8 +100,8 @@ export class Button extends ButtonBase {
};
}
[borderBottomWidthProperty.setNative](value: Length) {
let inset = this.nativeViewProtected.contentEdgeInsets;
let bottom = layout.toDeviceIndependentPixels(this.effectivePaddingBottom + this.effectiveBorderBottomWidth);
const inset = this.nativeViewProtected.contentEdgeInsets;
const bottom = layout.toDeviceIndependentPixels(this.effectivePaddingBottom + this.effectiveBorderBottomWidth);
this.nativeViewProtected.contentEdgeInsets = {
top: inset.top,
left: inset.left,
@ -117,8 +117,8 @@ export class Button extends ButtonBase {
};
}
[borderLeftWidthProperty.setNative](value: Length) {
let inset = this.nativeViewProtected.contentEdgeInsets;
let left = layout.toDeviceIndependentPixels(this.effectivePaddingLeft + this.effectiveBorderLeftWidth);
const inset = this.nativeViewProtected.contentEdgeInsets;
const left = layout.toDeviceIndependentPixels(this.effectivePaddingLeft + this.effectiveBorderLeftWidth);
this.nativeViewProtected.contentEdgeInsets = {
top: inset.top,
left: left,
@ -134,8 +134,8 @@ export class Button extends ButtonBase {
};
}
[paddingTopProperty.setNative](value: Length) {
let inset = this.nativeViewProtected.contentEdgeInsets;
let top = layout.toDeviceIndependentPixels(this.effectivePaddingTop + this.effectiveBorderTopWidth);
const inset = this.nativeViewProtected.contentEdgeInsets;
const top = layout.toDeviceIndependentPixels(this.effectivePaddingTop + this.effectiveBorderTopWidth);
this.nativeViewProtected.contentEdgeInsets = {
top: top,
left: inset.left,
@ -151,8 +151,8 @@ export class Button extends ButtonBase {
};
}
[paddingRightProperty.setNative](value: Length) {
let inset = this.nativeViewProtected.contentEdgeInsets;
let right = layout.toDeviceIndependentPixels(this.effectivePaddingRight + this.effectiveBorderRightWidth);
const inset = this.nativeViewProtected.contentEdgeInsets;
const right = layout.toDeviceIndependentPixels(this.effectivePaddingRight + this.effectiveBorderRightWidth);
this.nativeViewProtected.contentEdgeInsets = {
top: inset.top,
left: inset.left,
@ -168,8 +168,8 @@ export class Button extends ButtonBase {
};
}
[paddingBottomProperty.setNative](value: Length) {
let inset = this.nativeViewProtected.contentEdgeInsets;
let bottom = layout.toDeviceIndependentPixels(this.effectivePaddingBottom + this.effectiveBorderBottomWidth);
const inset = this.nativeViewProtected.contentEdgeInsets;
const bottom = layout.toDeviceIndependentPixels(this.effectivePaddingBottom + this.effectiveBorderBottomWidth);
this.nativeViewProtected.contentEdgeInsets = {
top: inset.top,
left: inset.left,
@ -185,8 +185,8 @@ export class Button extends ButtonBase {
};
}
[paddingLeftProperty.setNative](value: Length) {
let inset = this.nativeViewProtected.contentEdgeInsets;
let left = layout.toDeviceIndependentPixels(this.effectivePaddingLeft + this.effectiveBorderLeftWidth);
const inset = this.nativeViewProtected.contentEdgeInsets;
const left = layout.toDeviceIndependentPixels(this.effectivePaddingLeft + this.effectiveBorderLeftWidth);
this.nativeViewProtected.contentEdgeInsets = {
top: inset.top,
left: left,
@ -235,7 +235,7 @@ export class Button extends ButtonBase {
return super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
let nativeView = this.nativeViewProtected;
const nativeView = this.nativeViewProtected;
if (nativeView) {
const width = layout.getMeasureSpecSize(widthMeasureSpec);
const widthMode = layout.getMeasureSpecMode(widthMeasureSpec);
@ -271,7 +271,7 @@ class TapHandlerImpl extends NSObject {
private _owner: WeakRef<Button>;
public static initWithOwner(owner: WeakRef<Button>): TapHandlerImpl {
let handler = <TapHandlerImpl>TapHandlerImpl.new();
const handler = <TapHandlerImpl>TapHandlerImpl.new();
handler._owner = owner;
return handler;
}
@ -279,7 +279,7 @@ class TapHandlerImpl extends NSObject {
public tap(args) {
// _owner is a {N} view which could get destroyed when a tap initiates (protect!)
if (this._owner) {
let owner = this._owner.get();
const owner = this._owner.get();
if (owner) {
owner._emit(ButtonBase.tapEvent);
}

View File

@ -15,7 +15,7 @@ export class ContentView extends CustomLayoutView implements AddChildFromBuilder
return this._content;
}
set content(value: View) {
let oldView = this._content;
const oldView = this._content;
if (this._content) {
this._removeView(this._content);
}

View File

@ -3,13 +3,14 @@ import { ViewBase } from '../view-base';
// Requires
import { unsetValue } from '../properties';
import { Observable, WrappedValue, PropertyChangeData, EventData } from '../../../data/observable';
import { Observable, PropertyChangeData } from '../../../data/observable';
import { addWeakEventListener, removeWeakEventListener } from '../weak-event-listener';
import { bindingConstants, parentsRegex } from '../../builder/binding-builder';
import { escapeRegexSymbols } from '../../../utils';
import { Trace } from '../../../trace';
import * as types from '../../../utils/types';
import * as bindableResources from './bindable-resources';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const polymerExpressions = require('../../../js-libs/polymer-expressions');
import { PolymerExpressions } from '../../../js-libs/polymer-expressions';
@ -94,7 +95,7 @@ export function getEventOrGestureName(name: string): string {
// NOTE: method fromString from "ui/gestures";
export function isGesture(eventOrGestureName: string): boolean {
let t = eventOrGestureName.trim().toLowerCase();
const t = eventOrGestureName.trim().toLowerCase();
return t === 'tap' || t === 'doubletap' || t === 'pinch' || t === 'pan' || t === 'swipe' || t === 'rotation' || t === 'longpress' || t === 'touch';
}
@ -103,8 +104,8 @@ export function isGesture(eventOrGestureName: string): boolean {
// in controls. They will just override this one and provide their own event support.
export function isEventOrGesture(name: string, view: ViewBase): boolean {
if (typeof name === 'string') {
let eventOrGestureName = getEventOrGestureName(name);
let evt = `${eventOrGestureName}Event`;
const eventOrGestureName = getEventOrGestureName(name);
const evt = `${eventOrGestureName}Event`;
return (view.constructor && evt in view.constructor) || isGesture(eventOrGestureName.toLowerCase());
}
@ -149,7 +150,7 @@ export class Binding {
}
public loadedHandlerVisualTreeBinding(args) {
let target = args.object;
const target = args.object;
target.off('loaded', this.loadedHandlerVisualTreeBinding, this);
const context = target.bindingContext;
if (context !== undefined && context !== null) {
@ -176,7 +177,7 @@ export class Binding {
private sourceAsObject(source: any): any {
/* tslint:disable */
let objectType = typeof source;
const objectType = typeof source;
if (objectType === 'number') {
source = new Number(source);
} else if (objectType === 'boolean') {
@ -228,12 +229,12 @@ export class Binding {
this.source = new WeakRef(source);
this.sourceOptions = this.resolveOptions(source, this.sourceProperties);
let sourceValue = this.getSourcePropertyValue();
const sourceValue = this.getSourcePropertyValue();
this.updateTarget(sourceValue);
this.addPropertyChangeListeners(this.source, this.sourceProperties);
} else if (!this.sourceIsBindingContext) {
// TODO: if oneWay - call target.unbind();
let sourceValue = this.getSourcePropertyValue();
const sourceValue = this.getSourcePropertyValue();
this.updateTarget(sourceValue ? sourceValue : source);
}
}
@ -264,21 +265,21 @@ export class Binding {
// Consider returning single {} instead of array for performance.
private resolveObjectsAndProperties(source: Object, properties: Array<string>): Array<{ instance: Object; property: string }> {
let result = [];
const result = [];
let currentObject = source;
let currentObjectChanged = false;
for (let i = 0, propsArrayLength = properties.length; i < propsArrayLength; i++) {
let property = properties[i];
const property = properties[i];
if (property === bc.bindingValueKey) {
currentObjectChanged = true;
}
if (property === bc.parentValueKey || property.indexOf(bc.parentsValueKey) === 0) {
let parentView = this.getParentView(this.target.get(), property).view;
const parentView = this.getParentView(this.target.get(), property).view;
if (parentView) {
currentObject = parentView.bindingContext;
} else {
let targetInstance = this.target.get();
const targetInstance = this.target.get();
targetInstance.off('loaded', this.loadedHandlerVisualTreeBinding, this);
targetInstance.on('loaded', this.loadedHandlerVisualTreeBinding, this);
}
@ -304,13 +305,13 @@ export class Binding {
}
private addPropertyChangeListeners(source: WeakRef<Object>, sourceProperty: Array<string>, parentProperies?: string) {
let objectsAndProperties = this.resolveObjectsAndProperties(source.get(), sourceProperty);
const objectsAndProperties = this.resolveObjectsAndProperties(source.get(), sourceProperty);
let prop = parentProperies || '';
for (let i = 0, length = objectsAndProperties.length; i < length; i++) {
const propName = objectsAndProperties[i].property;
prop += '$' + propName;
let currentObject = objectsAndProperties[i].instance;
const currentObject = objectsAndProperties[i].instance;
if (!this.propertyChangeListeners.has(prop) && currentObject instanceof Observable && currentObject._isViewBase) {
// Add listener for properties created with after 3.0 version
addWeakEventListener(currentObject, `${propName}Change`, this.onSourcePropertyChanged, this);
@ -330,9 +331,9 @@ export class Binding {
// text="{{ sourceProperty = $parents['ListView'].test, expression = $parents['ListView'].test + 2}}"
// update expression will be '$newPropertyValue + 2'
// then on expression execution the new value will be taken and target property will be updated with the value of the expression.
let escapedSourceProperty = escapeRegexSymbols(this.options.sourceProperty);
let expRegex = new RegExp(escapedSourceProperty, 'g');
let resultExp = this.options.expression.replace(expRegex, bc.newPropertyValueKey);
const escapedSourceProperty = escapeRegexSymbols(this.options.sourceProperty);
const expRegex = new RegExp(escapedSourceProperty, 'g');
const resultExp = this.options.expression.replace(expRegex, bc.newPropertyValueKey);
return resultExp;
}
@ -344,7 +345,7 @@ export class Binding {
let newValue = value;
if (this.options.expression) {
let changedModel = {};
const changedModel = {};
changedModel[bc.bindingValueKey] = value;
changedModel[bc.newPropertyValueKey] = value;
let sourcePropertyName = '';
@ -358,10 +359,10 @@ export class Binding {
changedModel[sourcePropertyName] = value;
}
let updateExpression = this.prepareExpressionForUpdate();
const updateExpression = this.prepareExpressionForUpdate();
this.prepareContextForExpression(changedModel, updateExpression, undefined);
let expressionValue = this._getExpressionValue(updateExpression, true, changedModel);
const expressionValue = this._getExpressionValue(updateExpression, true, changedModel);
if (expressionValue instanceof Error) {
Trace.write((<Error>expressionValue).message, Trace.categories.Binding, Trace.messageType.error);
}
@ -374,13 +375,13 @@ export class Binding {
private _getExpressionValue(expression: string, isBackConvert: boolean, changedModel: any): any {
try {
let exp = PolymerExpressions.getExpression(expression);
const exp = PolymerExpressions.getExpression(expression);
if (exp) {
let context = (this.source && this.source.get && this.source.get()) || global;
let model = {};
let addedProps = [];
const context = (this.source && this.source.get && this.source.get()) || global;
const model = {};
const addedProps = [];
const resources = bindableResources.get();
for (let prop in resources) {
for (const prop in resources) {
if (resources.hasOwnProperty(prop) && !context.hasOwnProperty(prop)) {
context[prop] = resources[prop];
addedProps.push(prop);
@ -389,9 +390,9 @@ export class Binding {
this.prepareContextForExpression(context, expression, addedProps);
model[contextKey] = context;
let result = exp.getValue(model, isBackConvert, changedModel ? changedModel : model);
const result = exp.getValue(model, isBackConvert, changedModel ? changedModel : model);
// clear added props
let addedPropsLength = addedProps.length;
const addedPropsLength = addedProps.length;
for (let i = 0; i < addedPropsLength; i++) {
delete context[addedProps[i]];
}
@ -402,7 +403,7 @@ export class Binding {
return new Error(expression + ' is not a valid expression.');
} catch (e) {
let errorMessage = 'Run-time error occured in file: ' + e.sourceURL + ' at line: ' + e.line + ' and column: ' + e.column;
const errorMessage = 'Run-time error occured in file: ' + e.sourceURL + ' at line: ' + e.line + ' and column: ' + e.column;
return new Error(errorMessage);
}
@ -472,16 +473,16 @@ export class Binding {
private prepareContextForExpression(model: Object, expression: string, newProps: Array<string>) {
let parentViewAndIndex: { view: ViewBase; index: number };
let parentView;
let addedProps = newProps || [];
const addedProps = newProps || [];
let expressionCP = expression;
if (expressionCP.indexOf(bc.bindingValueKey) > -1) {
model[bc.bindingValueKey] = model;
addedProps.push(bc.bindingValueKey);
}
let success: boolean = true;
let success = true;
let parentsArray = expressionCP.match(parentsRegex);
const parentsArray = expressionCP.match(parentsRegex);
if (parentsArray) {
for (let i = 0; i < parentsArray.length; i++) {
// This prevents later checks to mistake $parents[] for $parent
@ -509,7 +510,7 @@ export class Binding {
// For expressions, there are also cases when binding must be updated after component is loaded (e.g. ListView)
if (!success) {
let targetInstance = this.target.get();
const targetInstance = this.target.get();
targetInstance.off('loaded', this.loadedHandlerVisualTreeBinding, this);
targetInstance.on('loaded', this.loadedHandlerVisualTreeBinding, this);
}
@ -517,9 +518,9 @@ export class Binding {
private getSourcePropertyValue() {
if (this.options.expression) {
let changedModel = {};
const changedModel = {};
changedModel[bc.bindingValueKey] = this.source ? this.source.get() : undefined;
let expressionValue = this._getExpressionValue(this.options.expression, false, changedModel);
const expressionValue = this._getExpressionValue(this.options.expression, false, changedModel);
if (expressionValue instanceof Error) {
Trace.write((<Error>expressionValue).message, Trace.categories.Binding, Trace.messageType.error);
} else {
@ -528,7 +529,7 @@ export class Binding {
}
if (this.sourceOptions) {
let sourceOptionsInstance = this.sourceOptions.instance.get();
const sourceOptionsInstance = this.sourceOptions.instance.get();
if (this.sourceOptions.property === bc.bindingValueKey) {
return sourceOptionsInstance;
} else if (sourceOptionsInstance instanceof Observable && this.sourceOptions.property && this.sourceOptions.property !== '') {
@ -577,7 +578,7 @@ export class Binding {
let index = null;
if (property.indexOf(bc.parentsValueKey) === 0) {
result = target.parent;
let indexParams = paramsRegex.exec(property);
const indexParams = paramsRegex.exec(property);
if (indexParams && indexParams.length > 1) {
index = indexParams[2];
}
@ -599,10 +600,10 @@ export class Binding {
}
private resolveOptions(obj: Object, properties: Array<string>): { instance: WeakRef<Object>; property: any } {
let objectsAndProperties = this.resolveObjectsAndProperties(obj, properties);
const objectsAndProperties = this.resolveObjectsAndProperties(obj, properties);
if (objectsAndProperties.length > 0) {
let resolvedObj = objectsAndProperties[objectsAndProperties.length - 1].instance;
let prop = objectsAndProperties[objectsAndProperties.length - 1].property;
const resolvedObj = objectsAndProperties[objectsAndProperties.length - 1].instance;
const prop = objectsAndProperties[objectsAndProperties.length - 1].property;
return {
instance: new WeakRef(this.sourceAsObject(resolvedObj)),

View File

@ -18,7 +18,7 @@ class ObserverClass extends NSObject {
export class ControlStateChangeListener implements ControlStateChangeListenerDefinition {
private _observer: NSObject;
private _control: UIControl;
private _observing: boolean = false;
private _observing = false;
private _callback: (state: string) => void;

View File

@ -48,16 +48,16 @@ export interface CssAnimationPropertyOptions<T, U> {
readonly valueConverter?: (value: string) => U;
}
let cssPropertyNames: string[] = [];
let symbolPropertyMap = {};
let cssSymbolPropertyMap = {};
const cssPropertyNames: string[] = [];
const symbolPropertyMap = {};
const cssSymbolPropertyMap = {};
let inheritableProperties = new Array<InheritedProperty<any, any>>();
let inheritableCssProperties = new Array<InheritedCssProperty<any, any>>();
const inheritableProperties = new Array<InheritedProperty<any, any>>();
const inheritableCssProperties = new Array<InheritedCssProperty<any, any>>();
function print(map) {
let symbols = Object.getOwnPropertySymbols(map);
for (let symbol of symbols) {
const symbols = Object.getOwnPropertySymbols(map);
for (const symbol of symbols) {
const prop = map[symbol];
if (!prop.registered) {
console.log(`Property ${prop.name} not Registered!!!!!`);
@ -183,8 +183,8 @@ export class Property<T extends ViewBase, U> implements TypedPropertyDescriptor<
public get: () => U;
public set: (value: U) => void;
public enumerable: boolean = true;
public configurable: boolean = true;
public enumerable = true;
public configurable = true;
constructor(options: PropertyOptions<T, U>) {
const propertyName = options.name;
@ -193,10 +193,10 @@ export class Property<T extends ViewBase, U> implements TypedPropertyDescriptor<
const key = Symbol(propertyName + ':propertyKey');
this.key = key;
const getDefault: symbol = Symbol(propertyName + ':getDefault');
const getDefault = Symbol(propertyName + ':getDefault');
this.getDefault = getDefault;
const setNative: symbol = Symbol(propertyName + ':setNative');
const setNative = Symbol(propertyName + ':setNative');
this.setNative = setNative;
const defaultValueKey = Symbol(propertyName + ':nativeDefaultValue');
@ -1062,8 +1062,8 @@ export class InheritedCssProperty<T extends Style, U> extends CssProperty<T, U>
let unsetNativeValue = false;
if (reset) {
// If unsetValue - we want to reset this property.
let parent = view.parent;
let style = parent ? parent.style : null;
const parent = view.parent;
const style = parent ? parent.style : null;
// If we have parent and it has non-default value we use as our inherited value.
if (style && style[sourceKey] > ValueSource.Default) {
value = style[propertyName];
@ -1192,7 +1192,7 @@ export class ShorthandProperty<T extends Style, P> implements ShorthandProperty<
}
view._batchUpdate(() => {
for (let [p, v] of converter(value)) {
for (const [p, v] of converter(value)) {
this[p.name] = v;
}
});
@ -1207,7 +1207,7 @@ export class ShorthandProperty<T extends Style, P> implements ShorthandProperty<
}
view._batchUpdate(() => {
for (let [p, v] of converter(value)) {
for (const [p, v] of converter(value)) {
this[p.cssName] = v;
}
});
@ -1261,7 +1261,7 @@ function inheritablePropertyValuesOn(view: ViewBase): Array<{ property: Inherite
property: InheritedProperty<any, any>;
value: any;
}>();
for (let prop of inheritableProperties) {
for (const prop of inheritableProperties) {
const sourceKey = prop.sourceKey;
const valueSource: number = view[sourceKey] || ValueSource.Default;
if (valueSource !== ValueSource.Default) {
@ -1279,7 +1279,7 @@ function inheritableCssPropertyValuesOn(style: Style): Array<{ property: Inherit
property: InheritedCssProperty<any, any>;
value: any;
}>();
for (let prop of inheritableCssProperties) {
for (const prop of inheritableCssProperties) {
const sourceKey = prop.sourceKey;
const valueSource: number = style[sourceKey] || ValueSource.Default;
if (valueSource !== ValueSource.Default) {
@ -1307,7 +1307,7 @@ export const initNativeView = profile('"properties".initNativeView', function in
export function applyPendingNativeSetters(view: ViewBase): void {
// TODO: Check what happens if a view was suspended and its value was reset, or set back to default!
const suspendedUpdates = view._suspendedUpdates;
for (let propertyName in suspendedUpdates) {
for (const propertyName in suspendedUpdates) {
const property = <PropertyInterface>suspendedUpdates[propertyName];
const setNative = property.setNative;
if (view[setNative]) {
@ -1341,7 +1341,7 @@ export function applyPendingNativeSetters(view: ViewBase): void {
export function applyAllNativeSetters(view: ViewBase): void {
let symbols = Object.getOwnPropertySymbols(view);
for (let symbol of symbols) {
for (const symbol of symbols) {
const property: Property<any, any> = symbolPropertyMap[symbol];
if (!property) {
continue;
@ -1362,7 +1362,7 @@ export function applyAllNativeSetters(view: ViewBase): void {
const style = view.style;
symbols = Object.getOwnPropertySymbols(style);
for (let symbol of symbols) {
for (const symbol of symbols) {
const property: CssProperty<any, any> = cssSymbolPropertyMap[symbol];
if (!property) {
continue;
@ -1382,7 +1382,7 @@ export function applyAllNativeSetters(view: ViewBase): void {
export function resetNativeView(view: ViewBase): void {
let symbols = Object.getOwnPropertySymbols(view);
for (let symbol of symbols) {
for (const symbol of symbols) {
const property: Property<any, any> = symbolPropertyMap[symbol];
if (!property) {
continue;
@ -1401,7 +1401,7 @@ export function resetNativeView(view: ViewBase): void {
const style = view.style;
symbols = Object.getOwnPropertySymbols(style);
for (let symbol of symbols) {
for (const symbol of symbols) {
const property: CssProperty<any, any> = cssSymbolPropertyMap[symbol];
if (!property) {
continue;
@ -1419,7 +1419,7 @@ export function resetNativeView(view: ViewBase): void {
}
export function clearInheritedProperties(view: ViewBase): void {
for (let prop of inheritableProperties) {
for (const prop of inheritableProperties) {
const sourceKey = prop.sourceKey;
if (view[sourceKey] === ValueSource.Inherited) {
prop.set.call(view, unsetValue);
@ -1427,7 +1427,7 @@ export function clearInheritedProperties(view: ViewBase): void {
}
const style = view.style;
for (let prop of inheritableCssProperties) {
for (const prop of inheritableCssProperties) {
const sourceKey = prop.sourceKey;
if (style[sourceKey] === ValueSource.Inherited) {
prop.setInheritedValue.call(style, unsetValue);
@ -1436,8 +1436,8 @@ export function clearInheritedProperties(view: ViewBase): void {
}
export function resetCSSProperties(style: Style): void {
let symbols = Object.getOwnPropertySymbols(style);
for (let symbol of symbols) {
const symbols = Object.getOwnPropertySymbols(style);
for (const symbol of symbols) {
let cssProperty;
if ((cssProperty = cssSymbolPropertyMap[symbol])) {
style[cssProperty.cssName] = unsetValue;
@ -1450,7 +1450,7 @@ export function resetCSSProperties(style: Style): void {
export function propagateInheritableProperties(view: ViewBase, child: ViewBase): void {
const inheritablePropertyValues = inheritablePropertyValuesOn(view);
for (let pair of inheritablePropertyValues) {
for (const pair of inheritablePropertyValues) {
const prop = pair.property;
const sourceKey = prop.sourceKey;
const currentValueSource: number = child[sourceKey] || ValueSource.Default;
@ -1462,7 +1462,7 @@ export function propagateInheritableProperties(view: ViewBase, child: ViewBase):
export function propagateInheritableCssProperties(parentStyle: Style, childStyle: Style): void {
const inheritableCssPropertyValues = inheritableCssPropertyValuesOn(parentStyle);
for (let pair of inheritableCssPropertyValues) {
for (const pair of inheritableCssPropertyValues) {
const prop = pair.property;
const sourceKey = prop.sourceKey;
const currentValueSource: number = childStyle[sourceKey] || ValueSource.Default;
@ -1496,8 +1496,8 @@ export function getSetProperties(view: ViewBase): [string, any][] {
result.push([prop, view[prop]]);
});
let symbols = Object.getOwnPropertySymbols(view);
for (let symbol of symbols) {
const symbols = Object.getOwnPropertySymbols(view);
for (const symbol of symbols) {
const property = symbolPropertyMap[symbol];
if (!property) {
continue;
@ -1513,7 +1513,7 @@ export function getSetProperties(view: ViewBase): [string, any][] {
export function getComputedCssValues(view: ViewBase): [string, any][] {
const result = [];
const style = view.style;
for (let prop of cssPropertyNames) {
for (const prop of cssPropertyNames) {
result.push([prop, style[prop]]);
}

View File

@ -36,7 +36,7 @@ function ensureStyleScopeModule() {
}
}
let defaultBindingSource = {};
const defaultBindingSource = {};
export interface ShowModalOptions {
/**
@ -47,7 +47,7 @@ export interface ShowModalOptions {
/**
* A function that will be called when the view is closed. Any arguments provided when calling ShownModallyData.closeCallback will be available here.
*/
closeCallback: Function;
closeCallback: (...args)=>void;
/**
* An optional parameter specifying whether to show the modal view in full-screen mode.
@ -94,7 +94,7 @@ export interface ShowModalOptions {
cancelable?: boolean;
}
export function getAncestor(view: ViewBaseDefinition, criterion: string | Function): ViewBaseDefinition {
export function getAncestor(view: ViewBaseDefinition, criterion: string | { new() }): ViewBaseDefinition {
let matcher: (view: ViewBaseDefinition) => boolean = null;
if (typeof criterion === 'string') {
matcher = (view: ViewBaseDefinition) => view.typeName === criterion;
@ -143,7 +143,7 @@ export function eachDescendant(view: ViewBaseDefinition, callback: (child: ViewB
}
let continueIteration: boolean;
let localCallback = function (child: ViewBaseDefinition): boolean {
const localCallback = function (child: ViewBaseDefinition): boolean {
continueIteration = callback(child);
if (continueIteration) {
child.eachChild(localCallback);
@ -216,8 +216,8 @@ export abstract class ViewBase extends Observable implements ViewBaseDefinition
public static unloadedEvent = 'unloaded';
public static createdEvent = 'created';
private _onLoadedCalled: boolean = false;
private _onUnloadedCalled: boolean = false;
private _onLoadedCalled = false;
private _onUnloadedCalled = false;
private _iosView: Object;
private _androidView: Object;
private _style: Style;
@ -532,7 +532,7 @@ export abstract class ViewBase extends Observable implements ViewBaseDefinition
@profile
public addPseudoClass(name: string): void {
let allStates = this.getAllAliasedStates(name);
const allStates = this.getAllAliasedStates(name);
for (let i = 0; i < allStates.length; i++) {
if (!this.cssPseudoClasses.has(allStates[i])) {
this.cssPseudoClasses.add(allStates[i]);
@ -543,7 +543,7 @@ export abstract class ViewBase extends Observable implements ViewBaseDefinition
@profile
public deletePseudoClass(name: string): void {
let allStates = this.getAllAliasedStates(name);
const allStates = this.getAllAliasedStates(name);
for (let i = 0; i < allStates.length; i++) {
if (this.cssPseudoClasses.has(allStates[i])) {
this.cssPseudoClasses.delete(allStates[i]);
@ -1004,7 +1004,7 @@ export abstract class ViewBase extends Observable implements ViewBaseDefinition
} else {
str += `(${this._domId})`;
}
let source = Source.get(this);
const source = Source.get(this);
if (source) {
str += `@${source};`;
}

View File

@ -510,14 +510,6 @@ export abstract class View extends ViewBase {
public getGestureObservers(type: GestureTypes): Array<GesturesObserver>;
/**
* 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") or you can use gesture types.
* @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 | GestureTypes, callback: (args: EventData) => void, thisArg?: any);
/**
* Removes listener(s) for the specified event name.
* @param eventNames Comma delimited names of the events or gesture types the specified listener is associated with.
@ -526,6 +518,14 @@ export abstract class View extends ViewBase {
*/
off(eventNames: string | GestureTypes, callback?: (args: EventData) => 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") or you can use gesture types.
* @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 | GestureTypes, callback: (args: EventData) => void, thisArg?: any);
/**
* Raised when a loaded event occurs.
*/

View File

@ -69,8 +69,8 @@ export class View extends ViewCommon implements ViewDefinition {
}
public measure(widthMeasureSpec: number, heightMeasureSpec: number): void {
let measureSpecsChanged = this._setCurrentMeasureSpecs(widthMeasureSpec, heightMeasureSpec);
let forceLayout = (this._privateFlags & PFLAG_FORCE_LAYOUT) === PFLAG_FORCE_LAYOUT;
const measureSpecsChanged = this._setCurrentMeasureSpecs(widthMeasureSpec, heightMeasureSpec);
const forceLayout = (this._privateFlags & PFLAG_FORCE_LAYOUT) === PFLAG_FORCE_LAYOUT;
if (forceLayout || measureSpecsChanged) {
// first clears the measured dimension flag
this._privateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
@ -156,7 +156,7 @@ export class View extends ViewCommon implements ViewDefinition {
}
public _setNativeViewFrame(nativeView: UIView, frame: CGRect): void {
let oldFrame = this._cachedFrame || nativeView.frame;
const oldFrame = this._cachedFrame || nativeView.frame;
if (!CGRectEqualToRect(oldFrame, frame)) {
if (Trace.isEnabled()) {
Trace.write(this + ' :_setNativeViewFrame: ' + JSON.stringify(IOSHelper.getPositionFromFrame(frame)), Trace.categories.Layout);
@ -274,7 +274,7 @@ export class View extends ViewCommon implements ViewDefinition {
public getSafeAreaInsets(): { left; top; right; bottom } {
const safeAreaInsets = this.nativeViewProtected && this.nativeViewProtected.safeAreaInsets;
let insets = { left: 0, top: 0, right: 0, bottom: 0 };
const insets = { left: 0, top: 0, right: 0, bottom: 0 };
if (safeAreaInsets) {
insets.left = layout.round(layout.toDevicePixels(safeAreaInsets.left));
@ -443,9 +443,9 @@ export class View extends ViewCommon implements ViewDefinition {
controller.preferredContentSize = CGSizeMake(options.ios.width, options.ios.height);
} else {
//use CSS & attribute width & height if option is not provided
let handler = () => {
let w = <number>(this.width || this.style.width);
let h = <number>(this.height || this.style.height);
const handler = () => {
const w = <number>(this.width || this.style.width);
const h = <number>(this.height || this.style.height);
//TODO: only numeric value is supported, percentage value is not supported like Android
if (w > 0 && h > 0) {
@ -585,8 +585,8 @@ export class View extends ViewCommon implements ViewDefinition {
return this.nativeViewProtected.alpha;
}
[opacityProperty.setNative](value: number) {
let nativeView = this.nativeViewProtected;
let updateSuspended = this._isPresentationLayerUpdateSuspeneded();
const nativeView = this.nativeViewProtected;
const updateSuspended = this._isPresentationLayerUpdateSuspeneded();
if (!updateSuspended) {
CATransaction.begin();
}
@ -693,7 +693,7 @@ export class View extends ViewCommon implements ViewDefinition {
}
_redrawNativeBackground(value: UIColor | Background): void {
let updateSuspended = this._isPresentationLayerUpdateSuspeneded();
const updateSuspended = this._isPresentationLayerUpdateSuspeneded();
if (!updateSuspended) {
CATransaction.begin();
}

View File

@ -49,8 +49,8 @@ export function PseudoClassHandler(...pseudoClasses: string[]): MethodDecorator
return <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => {
function update(change: number) {
let prev = this[listeners] || 0;
let next = prev + change;
const prev = this[listeners] || 0;
const next = prev + change;
if (prev <= 0 && next > 0) {
this[propertyKey](true);
} else if (prev > 0 && next <= 0) {
@ -242,15 +242,15 @@ export abstract class ViewCommon extends ViewBase implements ViewDefinition {
if (typeof arg === 'string') {
arg = getEventOrGestureName(arg);
let gesture = gestureFromString(arg);
const gesture = gestureFromString(arg);
if (gesture && !this._isEvent(arg)) {
this._observe(gesture, callback, thisArg);
} else {
let events = arg.split(',');
const events = arg.split(',');
if (events.length > 0) {
for (let i = 0; i < events.length; i++) {
let evt = events[i].trim();
let gst = gestureFromString(evt);
const evt = events[i].trim();
const gst = gestureFromString(evt);
if (gst && !this._isEvent(arg)) {
this._observe(gst, callback, thisArg);
} else {
@ -268,15 +268,15 @@ export abstract class ViewCommon extends ViewBase implements ViewDefinition {
public removeEventListener(arg: string | GestureTypes, callback?: any, thisArg?: any) {
if (typeof arg === 'string') {
let gesture = gestureFromString(arg);
const gesture = gestureFromString(arg);
if (gesture && !this._isEvent(arg)) {
this._disconnectGestureObservers(gesture);
} else {
let events = arg.split(',');
const events = arg.split(',');
if (events.length > 0) {
for (let i = 0; i < events.length; i++) {
let evt = events[i].trim();
let gst = gestureFromString(evt);
const evt = events[i].trim();
const gst = gestureFromString(evt);
if (gst && !this._isEvent(arg)) {
this._disconnectGestureObservers(gst);
} else {
@ -300,7 +300,7 @@ export abstract class ViewCommon extends ViewBase implements ViewDefinition {
return undefined;
}
private getModalOptions(args: IArguments): { view: ViewCommon; options: ShowModalOptions } {
private getModalOptions(args: any[]): { view: ViewCommon; options: ShowModalOptions } {
if (args.length === 0) {
throw new Error('showModal without parameters is deprecated. Please call showModal on a view instance instead.');
} else {
@ -333,8 +333,8 @@ export abstract class ViewCommon extends ViewBase implements ViewDefinition {
}
}
public showModal(): ViewDefinition {
const { view, options } = this.getModalOptions(arguments);
public showModal(...args): ViewDefinition {
const { view, options } = this.getModalOptions(args);
view._showNativeModalView(this, options);
@ -342,11 +342,11 @@ export abstract class ViewCommon extends ViewBase implements ViewDefinition {
}
public closeModal(...args) {
let closeCallback = this._closeModalCallback;
const closeCallback = this._closeModalCallback;
if (closeCallback) {
closeCallback.apply(undefined, arguments);
closeCallback(...args);
} else {
let parent = this.parent;
const parent = this.parent;
if (parent) {
parent.closeModal(...args);
}
@ -424,7 +424,7 @@ export abstract class ViewCommon extends ViewBase implements ViewDefinition {
}
private _disconnectGestureObservers(type: GestureTypes): void {
let observers = this.getGestureObservers(type);
const observers = this.getGestureObservers(type);
if (observers) {
for (let i = 0; i < observers.length; i++) {
observers[i].disconnect();
@ -829,7 +829,7 @@ export abstract class ViewCommon extends ViewBase implements ViewDefinition {
return ViewHelper.combineMeasuredStates(curState, newState);
}
public static layoutChild(parent: ViewDefinition, child: ViewDefinition, left: number, top: number, right: number, bottom: number, setFrame: boolean = true): void {
public static layoutChild(parent: ViewDefinition, child: ViewDefinition, left: number, top: number, right: number, bottom: number, setFrame = true): void {
ViewHelper.layoutChild(parent, child, left, top, right, bottom);
}
@ -838,7 +838,7 @@ export abstract class ViewCommon extends ViewBase implements ViewDefinition {
}
_setCurrentMeasureSpecs(widthMeasureSpec: number, heightMeasureSpec: number): boolean {
let changed: boolean = this._currentWidthMeasureSpec !== widthMeasureSpec || this._currentHeightMeasureSpec !== heightMeasureSpec;
const changed: boolean = this._currentWidthMeasureSpec !== widthMeasureSpec || this._currentHeightMeasureSpec !== heightMeasureSpec;
this._currentWidthMeasureSpec = widthMeasureSpec;
this._currentHeightMeasureSpec = heightMeasureSpec;
@ -859,8 +859,8 @@ export abstract class ViewCommon extends ViewBase implements ViewDefinition {
*/
_setCurrentLayoutBounds(left: number, top: number, right: number, bottom: number): { boundsChanged: boolean; sizeChanged: boolean } {
this._isLayoutValid = true;
let boundsChanged: boolean = this._oldLeft !== left || this._oldTop !== top || this._oldRight !== right || this._oldBottom !== bottom;
let sizeChanged: boolean = this._oldRight - this._oldLeft !== right - left || this._oldBottom - this._oldTop !== bottom - top;
const boundsChanged: boolean = this._oldLeft !== left || this._oldTop !== top || this._oldRight !== right || this._oldBottom !== bottom;
const sizeChanged: boolean = this._oldRight - this._oldLeft !== right - left || this._oldBottom - this._oldTop !== bottom - top;
this._oldLeft = left;
this._oldTop = top;
this._oldRight = right;
@ -906,7 +906,7 @@ export abstract class ViewCommon extends ViewBase implements ViewDefinition {
}
public getActualSize(): Size {
let currentBounds = this._getCurrentLayoutBounds();
const currentBounds = this._getCurrentLayoutBounds();
if (!currentBounds) {
return undefined;
}
@ -1000,7 +1000,7 @@ export abstract class ViewCommon extends ViewBase implements ViewDefinition {
}
_hasAncestorView(ancestorView: ViewDefinition): boolean {
let matcher = (view: ViewDefinition) => view === ancestorView;
const matcher = (view: ViewDefinition) => view === ancestorView;
for (let parent = this.parent; parent != null; parent = parent.parent) {
if (matcher(<ViewDefinition>parent)) {

View File

@ -42,12 +42,12 @@ export class ViewHelper {
return { measuredWidth: measureWidth, measuredHeight: measureHeight };
}
public static layoutChild(parent: ViewDefinition, child: ViewDefinition, left: number, top: number, right: number, bottom: number, setFrame: boolean = true): void {
public static layoutChild(parent: ViewDefinition, child: ViewDefinition, left: number, top: number, right: number, bottom: number, setFrame = true): void {
if (!child || child.isCollapsed) {
return;
}
let childStyle = child.style;
const childStyle = child.style;
let childTop: number;
let childLeft: number;
@ -55,8 +55,8 @@ export class ViewHelper {
let childWidth = child.getMeasuredWidth();
let childHeight = child.getMeasuredHeight();
let effectiveMarginTop = child.effectiveMarginTop;
let effectiveMarginBottom = child.effectiveMarginBottom;
const effectiveMarginTop = child.effectiveMarginTop;
const effectiveMarginBottom = child.effectiveMarginBottom;
let vAlignment: VerticalAlignmentDefinition;
if (child.effectiveHeight >= 0 && childStyle.verticalAlignment === 'stretch') {
@ -85,8 +85,8 @@ export class ViewHelper {
break;
}
let effectiveMarginLeft = child.effectiveMarginLeft;
let effectiveMarginRight = child.effectiveMarginRight;
const effectiveMarginLeft = child.effectiveMarginLeft;
const effectiveMarginRight = child.effectiveMarginRight;
let hAlignment: HorizontalAlignmentDefinition;
// if (child.effectiveWidth >= 0 && childStyle.horizontalAlignment === 'stretch') {
@ -115,8 +115,8 @@ export class ViewHelper {
break;
}
let childRight = Math.round(childLeft + childWidth);
let childBottom = Math.round(childTop + childHeight);
const childRight = Math.round(childLeft + childWidth);
const childBottom = Math.round(childTop + childHeight);
childLeft = Math.round(childLeft);
childTop = Math.round(childTop);

View File

@ -81,7 +81,7 @@ function validateArgs(source: Observable, eventName: string, handler: (eventData
export function addWeakEventListener(source: Observable, eventName: string, handler: (eventData: EventData) => void, target: any) {
validateArgs(source, eventName, handler, target);
let shouldAttach: boolean = false;
let shouldAttach = false;
let sourceEventMap = sourcesMap.get(source);
if (!sourceEventMap) {

View File

@ -178,65 +178,65 @@ export interface LoginOptions extends ConfirmOptions {
/**
* Defines the input type for prompt dialog.
*/
export module inputType {
export namespace inputType {
/**
* Plain text input type.
*/
export const text: string = 'text';
export const text = 'text';
/**
* Password input type.
*/
export const password: string = 'password';
export const password = 'password';
/**
* Email input type.
*/
export const email: string = 'email';
export const email = 'email';
/**
* Number input type
*/
export const number: string = 'number';
export const number = 'number';
/**
* Decimal input type
*/
export const decimal: string = 'decimal';
export const decimal = 'decimal';
/**
* Phone input type
*/
export const phone: string = 'phone';
export const phone = 'phone';
}
/**
* Defines the capitalization type for prompt dialog.
*/
export module capitalizationType {
export namespace capitalizationType {
/**
* No automatic capitalization.
*/
export const none: string = 'none';
export const none = 'none';
/**
* Capitalizes every character.
*/
export const all: string = 'all';
export const all = 'all';
/**
* Capitalize the first word of each sentence.
*/
export const sentences: string = 'sentences';
export const sentences = 'sentences';
/**
* Capitalize the first letter of every word.
*/
export const words: string = 'words';
export const words = 'words';
}
export function getCurrentPage(): Page {
let topmostFrame = Frame.topmost();
const topmostFrame = Frame.topmost();
if (topmostFrame) {
return topmostFrame.currentPage;
}
@ -245,9 +245,9 @@ export function getCurrentPage(): Page {
}
function applySelectors<T extends View>(view: T, callback: (view: T) => void) {
let currentPage = getCurrentPage();
const currentPage = getCurrentPage();
if (currentPage) {
let styleScope = currentPage._styleScope;
const styleScope = currentPage._styleScope;
if (styleScope) {
view._inheritStyleScope(styleScope);
view.onLoaded();
@ -263,6 +263,7 @@ let textField: View;
export function getButtonColors(): { color: Color; backgroundColor: Color } {
if (!button) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const Button = require('../button').Button;
button = new Button();
if (global.isIOS) {
@ -282,6 +283,7 @@ export function getButtonColors(): { color: Color; backgroundColor: Color } {
export function getLabelColor(): Color {
if (!label) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const Label = require('../label').Label;
label = new Label();
if (global.isIOS) {
@ -299,6 +301,7 @@ export function getLabelColor(): Color {
export function getTextFieldColor(): Color {
if (!textField) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const TextField = require('../text-field').TextField;
textField = new TextField();
if (global.isIOS) {
@ -324,7 +327,7 @@ export function parseLoginOptions(args: any[]): LoginOptions {
return args[0];
}
let options: LoginOptions = {
const options: LoginOptions = {
title: DialogStrings.LOGIN,
okButtonText: DialogStrings.OK,
cancelButtonText: DialogStrings.CANCEL,

View File

@ -44,12 +44,12 @@ function showDialog(builder: android.app.AlertDialog.Builder) {
}
}
let { color, backgroundColor } = getButtonColors();
const { color, backgroundColor } = getButtonColors();
if (color) {
let buttons: android.widget.Button[] = [];
const buttons: android.widget.Button[] = [];
for (let i = 0; i < 3; i++) {
let id = dlg
const id = dlg
.getContext()
.getResources()
.getIdentifier('android:id/button' + i, null, null);
@ -173,7 +173,7 @@ export function confirm(arg: any): Promise<boolean> {
});
}
export function prompt(arg: any): Promise<PromptResult> {
export function prompt(...args): Promise<PromptResult> {
let options: PromptOptions;
const defaultOptions = {
@ -182,19 +182,19 @@ export function prompt(arg: any): Promise<PromptResult> {
cancelButtonText: DialogStrings.CANCEL,
inputType: inputType.text,
};
if (arguments.length === 1) {
const arg = args[0];
if (args.length === 1) {
if (isString(arg)) {
options = defaultOptions;
options.message = arg;
} else {
options = arg;
}
} else if (arguments.length === 2) {
if (isString(arguments[0]) && isString(arguments[1])) {
} else if (args.length === 2) {
if (isString(arg) && isString(args[1])) {
options = defaultOptions;
options.message = arguments[0];
options.defaultText = arguments[1];
options.message = arg;
options.defaultText = args[1];
}
}
@ -253,7 +253,7 @@ export function prompt(arg: any): Promise<PromptResult> {
}
export function login(...args: any[]): Promise<LoginResult> {
let options: LoginOptions = parseLoginOptions(args);
const options: LoginOptions = parseLoginOptions(args);
return new Promise<LoginResult>((resolve, reject) => {
try {
@ -295,30 +295,30 @@ export function login(...args: any[]): Promise<LoginResult> {
});
}
export function action(arg: any): Promise<string> {
export function action(...args): Promise<string> {
let options: ActionOptions;
const defaultOptions = { title: null, cancelButtonText: DialogStrings.CANCEL };
if (arguments.length === 1) {
if (isString(arguments[0])) {
if (args.length === 1) {
if (isString(args[0])) {
options = defaultOptions;
options.message = arguments[0];
options.message = args[0];
} else {
options = arguments[0];
options = args[0];
}
} else if (arguments.length === 2) {
if (isString(arguments[0]) && isString(arguments[1])) {
} else if (args.length === 2) {
if (isString(args[0]) && isString(args[1])) {
options = defaultOptions;
options.message = arguments[0];
options.cancelButtonText = arguments[1];
options.message = args[0];
options.cancelButtonText = args[1];
}
} else if (arguments.length === 3) {
if (isString(arguments[0]) && isString(arguments[1]) && typeof arguments[2] !== 'undefined') {
} else if (args.length === 3) {
if (isString(args[0]) && isString(args[1]) && typeof args[2] !== 'undefined') {
options = defaultOptions;
options.message = arguments[0];
options.cancelButtonText = arguments[1];
options.actions = arguments[2];
options.message = args[0];
options.cancelButtonText = args[1];
options.actions = args[2];
}
}

View File

@ -2,7 +2,7 @@
/**
* Defines the input type for prompt dialog.
*/
export module inputType {
export namespace inputType {
/**
* Plain text input type.
*/
@ -37,7 +37,7 @@ export module inputType {
/**
* Defines the capitalization type for prompt dialog.
*/
export module capitalizationType {
export namespace capitalizationType {
/**
* No automatic capitalization.
*/

View File

@ -63,19 +63,19 @@ function showUIAlertController(alertController: UIAlertController) {
alertController.popoverPresentationController.permittedArrowDirections = 0;
}
let color = getButtonColors().color;
const color = getButtonColors().color;
if (color) {
alertController.view.tintColor = color.ios;
}
let lblColor = getLabelColor();
const lblColor = getLabelColor();
if (lblColor) {
if (alertController.title) {
let title = NSAttributedString.alloc().initWithStringAttributes(alertController.title, <any>{ [NSForegroundColorAttributeName]: lblColor.ios });
const title = NSAttributedString.alloc().initWithStringAttributes(alertController.title, <any>{ [NSForegroundColorAttributeName]: lblColor.ios });
alertController.setValueForKey(title, 'attributedTitle');
}
if (alertController.message) {
let message = NSAttributedString.alloc().initWithStringAttributes(alertController.message, <any>{ [NSForegroundColorAttributeName]: lblColor.ios });
const message = NSAttributedString.alloc().initWithStringAttributes(alertController.message, <any>{ [NSForegroundColorAttributeName]: lblColor.ios });
alertController.setValueForKey(message, 'attributedMessage');
}
}
@ -86,8 +86,8 @@ function showUIAlertController(alertController: UIAlertController) {
export function alert(arg: any): Promise<void> {
return new Promise<void>((resolve, reject) => {
try {
let options = !isDialogOptions(arg) ? { title: DialogStrings.ALERT, okButtonText: DialogStrings.OK, message: arg + '' } : arg;
let alertController = UIAlertController.alertControllerWithTitleMessagePreferredStyle(options.title, options.message, UIAlertControllerStyle.Alert);
const options = !isDialogOptions(arg) ? { title: DialogStrings.ALERT, okButtonText: DialogStrings.OK, message: arg + '' } : arg;
const alertController = UIAlertController.alertControllerWithTitleMessagePreferredStyle(options.title, options.message, UIAlertControllerStyle.Alert);
addButtonsToAlertController(alertController, options, () => {
resolve();
@ -103,7 +103,7 @@ export function alert(arg: any): Promise<void> {
export function confirm(arg: any): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
try {
let options = !isDialogOptions(arg)
const options = !isDialogOptions(arg)
? {
title: DialogStrings.CONFIRM,
okButtonText: DialogStrings.OK,
@ -111,7 +111,7 @@ export function confirm(arg: any): Promise<boolean> {
message: arg + '',
}
: arg;
let alertController = UIAlertController.alertControllerWithTitleMessagePreferredStyle(options.title, options.message, UIAlertControllerStyle.Alert);
const alertController = UIAlertController.alertControllerWithTitleMessagePreferredStyle(options.title, options.message, UIAlertControllerStyle.Alert);
addButtonsToAlertController(alertController, options, (r) => {
resolve(r);
@ -124,35 +124,34 @@ export function confirm(arg: any): Promise<boolean> {
});
}
export function prompt(arg: any): Promise<PromptResult> {
export function prompt(...args): Promise<PromptResult> {
let options: PromptOptions;
let defaultOptions = {
const defaultOptions = {
title: DialogStrings.PROMPT,
okButtonText: DialogStrings.OK,
cancelButtonText: DialogStrings.CANCEL,
inputType: inputType.text,
};
if (arguments.length === 1) {
const arg = args[0];
if (args.length === 1) {
if (isString(arg)) {
options = defaultOptions;
options.message = arg;
} else {
options = arg;
}
} else if (arguments.length === 2) {
if (isString(arguments[0]) && isString(arguments[1])) {
} else if (args.length === 2) {
if (isString(arg) && isString(args[1])) {
options = defaultOptions;
options.message = arguments[0];
options.defaultText = arguments[1];
options.message = arg;
options.defaultText = args[1];
}
}
return new Promise<PromptResult>((resolve, reject) => {
try {
let textField: UITextField;
let alertController = UIAlertController.alertControllerWithTitleMessagePreferredStyle(options.title, options.message, UIAlertControllerStyle.Alert);
const alertController = UIAlertController.alertControllerWithTitleMessagePreferredStyle(options.title, options.message, UIAlertControllerStyle.Alert);
alertController.addTextFieldWithConfigurationHandler((arg: UITextField) => {
arg.text = isString(options.defaultText) ? options.defaultText : '';
@ -168,13 +167,13 @@ export function prompt(arg: any): Promise<PromptResult> {
arg.keyboardType = UIKeyboardType.PhonePad;
}
let color = getTextFieldColor();
const color = getTextFieldColor();
if (color) {
arg.textColor = arg.tintColor = color.ios;
}
});
textField = alertController.textFields.firstObject;
const textField: UITextField = alertController.textFields.firstObject;
if (options) {
switch (options.capitalizationType) {
@ -208,15 +207,13 @@ export function prompt(arg: any): Promise<PromptResult> {
}
export function login(...args: any[]): Promise<LoginResult> {
let options: LoginOptions = parseLoginOptions(args);
const options: LoginOptions = parseLoginOptions(args);
return new Promise<LoginResult>((resolve, reject) => {
try {
let userNameTextField: UITextField;
let passwordTextField: UITextField;
let alertController = UIAlertController.alertControllerWithTitleMessagePreferredStyle(options.title, options.message, UIAlertControllerStyle.Alert);
const alertController = UIAlertController.alertControllerWithTitleMessagePreferredStyle(options.title, options.message, UIAlertControllerStyle.Alert);
let textFieldColor = getTextFieldColor();
const textFieldColor = getTextFieldColor();
alertController.addTextFieldWithConfigurationHandler((arg: UITextField) => {
arg.placeholder = 'Login';
@ -238,9 +235,8 @@ export function login(...args: any[]): Promise<LoginResult> {
arg.textColor = arg.tintColor = textFieldColor.ios;
}
});
userNameTextField = alertController.textFields.firstObject;
passwordTextField = alertController.textFields.lastObject;
const userNameTextField: UITextField = alertController.textFields.firstObject;
const passwordTextField: UITextField = alertController.textFields.lastObject;
addButtonsToAlertController(alertController, options, (r) => {
resolve({
@ -257,30 +253,30 @@ export function login(...args: any[]): Promise<LoginResult> {
});
}
export function action(): Promise<string> {
export function action(...args): Promise<string> {
let options: ActionOptions;
let defaultOptions = { title: null, cancelButtonText: DialogStrings.CANCEL };
const defaultOptions = { title: null, cancelButtonText: DialogStrings.CANCEL };
if (arguments.length === 1) {
if (isString(arguments[0])) {
if (args.length === 1) {
if (isString(args[0])) {
options = defaultOptions;
options.message = arguments[0];
options.message = args[0];
} else {
options = arguments[0];
options = args[0];
}
} else if (arguments.length === 2) {
if (isString(arguments[0]) && isString(arguments[1])) {
} else if (args.length === 2) {
if (isString(args[0]) && isString(args[1])) {
options = defaultOptions;
options.message = arguments[0];
options.cancelButtonText = arguments[1];
options.message = args[0];
options.cancelButtonText = args[1];
}
} else if (arguments.length === 3) {
if (isString(arguments[0]) && isString(arguments[1]) && isDefined(arguments[2])) {
} else if (args.length === 3) {
if (isString(args[0]) && isString(args[1]) && isDefined(args[2])) {
options = defaultOptions;
options.message = arguments[0];
options.cancelButtonText = arguments[1];
options.actions = arguments[2];
options.message = args[0];
options.cancelButtonText = args[1];
options.actions = args[2];
}
}
@ -288,7 +284,7 @@ export function action(): Promise<string> {
try {
let i: number;
let action: string;
let alertController = UIAlertController.alertControllerWithTitleMessagePreferredStyle(options.title, options.message, UIAlertControllerStyle.ActionSheet);
const alertController = UIAlertController.alertControllerWithTitleMessagePreferredStyle(options.title, options.message, UIAlertControllerStyle.ActionSheet);
if (options.actions) {
for (i = 0; i < options.actions.length; i++) {

View File

@ -288,7 +288,7 @@ export abstract class EditableTextBase extends EditableTextBaseCommon {
}
[returnKeyTypeProperty.getDefault](): 'done' | 'next' | 'go' | 'search' | 'send' | string {
let ime = this.nativeTextViewProtected.getImeOptions();
const ime = this.nativeTextViewProtected.getImeOptions();
switch (ime) {
case android.view.inputmethod.EditorInfo.IME_ACTION_DONE:
return 'done';
@ -327,8 +327,8 @@ export abstract class EditableTextBase extends EditableTextBaseCommon {
case 'send':
newImeOptions = android.view.inputmethod.EditorInfo.IME_ACTION_SEND;
break;
default:
let ime = +value;
default:{
const ime = +value;
if (!isNaN(ime)) {
newImeOptions = ime;
} else {
@ -336,6 +336,7 @@ export abstract class EditableTextBase extends EditableTextBaseCommon {
}
break;
}
}
this.nativeTextViewProtected.setImeOptions(newImeOptions);
}
@ -353,7 +354,7 @@ export abstract class EditableTextBase extends EditableTextBaseCommon {
}
[autocapitalizationTypeProperty.getDefault](): 'none' | 'words' | 'sentences' | 'allcharacters' | string {
let inputType = this.nativeTextViewProtected.getInputType();
const inputType = this.nativeTextViewProtected.getInputType();
if ((inputType & android.text.InputType.TYPE_TEXT_FLAG_CAP_WORDS) === android.text.InputType.TYPE_TEXT_FLAG_CAP_WORDS) {
return 'words';
} else if ((inputType & android.text.InputType.TYPE_TEXT_FLAG_CAP_SENTENCES) === android.text.InputType.TYPE_TEXT_FLAG_CAP_SENTENCES) {
@ -381,8 +382,8 @@ export abstract class EditableTextBase extends EditableTextBaseCommon {
case 'allcharacters':
inputType = inputType | android.text.InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS; //4096 (0x00010000) 13th bit
break;
default:
let number = +value;
default:{
const number = +value;
// We set the default value.
if (!isNaN(number)) {
inputType = number;
@ -391,12 +392,13 @@ export abstract class EditableTextBase extends EditableTextBaseCommon {
}
break;
}
}
this._setInputType(inputType);
}
[autocorrectProperty.getDefault](): boolean {
let autocorrect = this.nativeTextViewProtected.getInputType();
const autocorrect = this.nativeTextViewProtected.getInputType();
if ((autocorrect & android.text.InputType.TYPE_TEXT_FLAG_AUTO_CORRECT) === android.text.InputType.TYPE_TEXT_FLAG_AUTO_CORRECT) {
return true;
}

View File

@ -11,7 +11,7 @@ export abstract class EditableTextBase extends EditableTextBaseCommon {
}
[keyboardTypeProperty.getDefault](): 'datetime' | 'phone' | 'number' | 'url' | 'email' | 'integer' | string {
let keyboardType = this.nativeTextViewProtected.keyboardType;
const keyboardType = this.nativeTextViewProtected.keyboardType;
switch (keyboardType) {
case UIKeyboardType.NumbersAndPunctuation:
return 'number';
@ -59,7 +59,7 @@ export abstract class EditableTextBase extends EditableTextBaseCommon {
break;
default:
let kt = +value;
const kt = +value;
if (!isNaN(kt)) {
newKeyboardType = <UIKeyboardType>kt;
} else {
@ -72,7 +72,7 @@ export abstract class EditableTextBase extends EditableTextBaseCommon {
}
[returnKeyTypeProperty.getDefault](): 'done' | 'next' | 'go' | 'search' | 'send' | string {
let returnKeyType = this.nativeTextViewProtected.returnKeyType;
const returnKeyType = this.nativeTextViewProtected.returnKeyType;
switch (returnKeyType) {
case UIReturnKeyType.Done:
return 'done';
@ -112,7 +112,7 @@ export abstract class EditableTextBase extends EditableTextBaseCommon {
newValue = UIReturnKeyType.Send;
break;
default:
let rkt = +value;
const rkt = +value;
if (!isNaN(rkt)) {
newValue = <UIKeyboardType>rkt;
} else {
@ -125,7 +125,7 @@ export abstract class EditableTextBase extends EditableTextBaseCommon {
}
[autocapitalizationTypeProperty.getDefault](): 'none' | 'words' | 'sentences' | 'allcharacters' {
let autocapitalizationType = this.nativeTextViewProtected.autocapitalizationType;
const autocapitalizationType = this.nativeTextViewProtected.autocapitalizationType;
switch (autocapitalizationType) {
case UITextAutocapitalizationType.None:
return 'none';
@ -167,7 +167,7 @@ export abstract class EditableTextBase extends EditableTextBaseCommon {
}
[autocorrectProperty.getDefault](): boolean | number {
let autocorrectionType = this.nativeTextViewProtected.autocorrectionType;
const autocorrectionType = this.nativeTextViewProtected.autocorrectionType;
switch (autocorrectionType) {
case UITextAutocorrectionType.Yes:
return true;
@ -192,12 +192,12 @@ export abstract class EditableTextBase extends EditableTextBaseCommon {
}
export function _updateCharactersInRangeReplacementString(formattedText: FormattedString, rangeLocation: number, rangeLength: number, replacementString: string): void {
let deletingText = !replacementString;
const deletingText = !replacementString;
let currentLocation = 0;
for (let i = 0, length = formattedText.spans.length; i < length; i++) {
let span = formattedText.spans.getItem(i);
const span = formattedText.spans.getItem(i);
if (currentLocation <= rangeLocation && rangeLocation < currentLocation + span.text.length) {
let newText = splice(span.text, rangeLocation - currentLocation, deletingText ? rangeLength : 0, replacementString);
const newText = splice(span.text, rangeLocation - currentLocation, deletingText ? rangeLength : 0, replacementString);
span._setTextInternal(newText);
return;

View File

@ -2,7 +2,7 @@
import * as animationModule from '../../ui/animation';
export type KeyboardType = 'datetime' | 'phone' | 'number' | 'url' | 'email' | 'integer';
export module KeyboardType {
export namespace KeyboardType {
export const datetime = 'datetime';
export const phone = 'phone';
export const number = 'number';
@ -11,7 +11,7 @@ export module KeyboardType {
export const integer = 'integer';
}
export module ReturnKeyType {
export namespace ReturnKeyType {
export const done = 'done';
export const next = 'next';
export const go = 'go';
@ -25,154 +25,154 @@ export class TextAlignment {
static right = 'right';
}
export module TextDecoration {
export namespace TextDecoration {
export const none = 'none';
export const underline = 'underline';
export const lineThrough = 'line-through';
}
export module TextTransform {
export namespace TextTransform {
export const none = 'none';
export const capitalize = 'capitalize';
export const uppercase = 'uppercase';
export const lowercase = 'lowercase';
}
export module WhiteSpace {
export namespace WhiteSpace {
export const normal = 'normal';
export const nowrap = 'nowrap';
}
export module Orientation {
export namespace Orientation {
export const horizontal = 'horizontal';
export const vertical = 'vertical';
}
export module DeviceOrientation {
export namespace DeviceOrientation {
export const portrait = 'portrait';
export const landscape = 'landscape';
export const unknown = 'unknown';
}
export module HorizontalAlignment {
export namespace HorizontalAlignment {
export const left = 'left';
export const center = 'center';
export const right = 'right';
export const stretch = 'stretch';
}
export module VerticalAlignment {
export namespace VerticalAlignment {
export const top = 'top';
export const middle = 'middle';
export const bottom = 'bottom';
export const stretch = 'stretch';
}
export module Stretch {
export const none: string = 'none';
export const aspectFill: string = 'aspectFill';
export const aspectFit: string = 'aspectFit';
export const fill: string = 'fill';
export namespace Stretch {
export const none = 'none';
export const aspectFill = 'aspectFill';
export const aspectFit = 'aspectFit';
export const fill = 'fill';
}
export module Visibility {
export const visible: string = 'visible';
export const collapse: string = 'collapse';
export const collapsed: string = 'collapsed';
export const hidden: string = 'hidden';
export namespace Visibility {
export const visible = 'visible';
export const collapse = 'collapse';
export const collapsed = 'collapsed';
export const hidden = 'hidden';
}
export module FontAttributes {
export namespace FontAttributes {
export const Normal = 0;
export const Bold = 1;
export const Italic = 1 << 1;
}
export module DeviceType {
export const Phone: string = 'Phone';
export const Tablet: string = 'Tablet';
export namespace DeviceType {
export const Phone = 'Phone';
export const Tablet = 'Tablet';
}
export module UpdateTextTrigger {
export const focusLost: string = 'focusLost';
export const textChanged: string = 'textChanged';
export namespace UpdateTextTrigger {
export const focusLost = 'focusLost';
export const textChanged = 'textChanged';
}
export module Accuracy {
export const any: number = 300;
export const high: number = 3;
export namespace Accuracy {
export const any = 300;
export const high = 3;
}
export module Dock {
export const left: string = 'left';
export const top: string = 'top';
export const right: string = 'right';
export const bottom: string = 'bottom';
export namespace Dock {
export const left = 'left';
export const top = 'top';
export const right = 'right';
export const bottom = 'bottom';
}
export module AutocapitalizationType {
export const none: string = 'none';
export const words: string = 'words';
export const sentences: string = 'sentences';
export const allCharacters: string = 'allcharacters';
export namespace AutocapitalizationType {
export const none = 'none';
export const words = 'words';
export const sentences = 'sentences';
export const allCharacters = 'allcharacters';
}
export module NavigationBarVisibility {
export const auto: string = 'auto';
export const never: string = 'never';
export const always: string = 'always';
export namespace NavigationBarVisibility {
export const auto = 'auto';
export const never = 'never';
export const always = 'always';
}
export module AndroidActionBarIconVisibility {
export const auto: string = 'auto';
export const never: string = 'never';
export const always: string = 'always';
export namespace AndroidActionBarIconVisibility {
export const auto = 'auto';
export const never = 'never';
export const always = 'always';
}
export module AndroidActionItemPosition {
export const actionBar: string = 'actionBar';
export const actionBarIfRoom: string = 'actionBarIfRoom';
export const popup: string = 'popup';
export namespace AndroidActionItemPosition {
export const actionBar = 'actionBar';
export const actionBarIfRoom = 'actionBarIfRoom';
export const popup = 'popup';
}
export module IOSActionItemPosition {
export const left: string = 'left';
export const right: string = 'right';
export namespace IOSActionItemPosition {
export const left = 'left';
export const right = 'right';
}
export module ImageFormat {
export const png: string = 'png';
export const jpeg: string = 'jpeg';
export const jpg: string = 'jpg';
export namespace ImageFormat {
export const png = 'png';
export const jpeg = 'jpeg';
export const jpg = 'jpg';
}
export module FontStyle {
export const normal: string = 'normal';
export const italic: string = 'italic';
export namespace FontStyle {
export const normal = 'normal';
export const italic = 'italic';
}
export module FontWeight {
export const thin: string = '100';
export const extraLight: string = '200';
export const light: string = '300';
export const normal: string = 'normal'; // 400
export const medium: string = '500';
export const semiBold: string = '600';
export const bold: string = 'bold'; // 700
export const extraBold: string = '800';
export const black: string = '900';
export namespace FontWeight {
export const thin = '100';
export const extraLight = '200';
export const light = '300';
export const normal = 'normal'; // 400
export const medium = '500';
export const semiBold = '600';
export const bold = 'bold'; // 700
export const extraBold = '800';
export const black = '900';
}
export module BackgroundRepeat {
export const repeat: string = 'repeat';
export const repeatX: string = 'repeat-x';
export const repeatY: string = 'repeat-y';
export const noRepeat: string = 'no-repeat';
export namespace BackgroundRepeat {
export const repeat = 'repeat';
export const repeatX = 'repeat-x';
export const repeatY = 'repeat-y';
export const noRepeat = 'no-repeat';
}
let animation: typeof animationModule;
export module AnimationCurve {
export namespace AnimationCurve {
export const ease = 'ease';
export const easeIn = 'easeIn';
export const easeOut = 'easeOut';
@ -186,12 +186,12 @@ export module AnimationCurve {
}
}
export module StatusBarStyle {
export namespace StatusBarStyle {
export const light = 'light';
export const dark = 'dark';
}
export module SystemAppearance {
export namespace SystemAppearance {
export const light = 'light';
export const dark = 'dark';
}

View File

@ -1,5 +1,6 @@
import '../../globals';
import { setActivityCallbacks, AndroidActivityCallbacks } from '.';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const appModule = require('../../application');
/**

View File

@ -29,7 +29,7 @@ const FragmentClass = (<any>org.nativescript.widgets.FragmentBase).extend('com.t
},
onCreateView(inflater: android.view.LayoutInflater, container: android.view.ViewGroup, savedInstanceState: android.os.Bundle) {
let result = this._callbacks.onCreateView(this, inflater, container, savedInstanceState, superProto.onCreateView);
const result = this._callbacks.onCreateView(this, inflater, container, savedInstanceState, superProto.onCreateView);
return result;
},

View File

@ -5,7 +5,7 @@ import { FadeTransition } from '../transition/fade-transition';
import { Trace } from '../../trace';
module UIViewControllerAnimatedTransitioningMethods {
namespace UIViewControllerAnimatedTransitioningMethods {
const methodSignature = NSMethodSignature.signatureWithObjCTypes('v@:c');
const invocation = NSInvocation.invocationWithMethodSignature(methodSignature);
invocation.selector = 'completeTransition:';

View File

@ -249,6 +249,12 @@ export class FrameBase extends CustomLayoutView {
}
newPage.onNavigatedTo(isBack);
this.notify({
eventName: Page.navigatedToEvent,
object: this,
isBack,
entry,
});
// Reset executing context after NavigatedTo is raised;
// we do not want to execute two navigations in parallel in case
@ -282,6 +288,7 @@ export class FrameBase extends CustomLayoutView {
}
private isNestedWithin(parentFrameCandidate: FrameBase): boolean {
// eslint-disable-next-line @typescript-eslint/no-this-alias
let frameAncestor: FrameBase = this;
while (frameAncestor) {
frameAncestor = <FrameBase>getAncestor(frameAncestor, FrameBase);
@ -412,6 +419,13 @@ export class FrameBase extends CustomLayoutView {
}
backstackEntry.resolvedPage.onNavigatingTo(backstackEntry.entry.context, isBack, backstackEntry.entry.bindingContext);
this.notify({
eventName: Page.navigatingToEvent,
object: this,
isBack,
entry: backstackEntry.entry,
fromEntry:this.currentEntry
});
}
public get animated(): boolean {
@ -561,7 +575,7 @@ export class FrameBase extends CustomLayoutView {
let i = length - 1;
console.log(`Frame Back Stack: `);
while (i >= 0) {
let backstackEntry = <BackstackEntry>this.backStack[i--];
const backstackEntry = <BackstackEntry>this.backStack[i--];
console.log(`\t${backstackEntry.resolvedPage}`);
}
}

View File

@ -80,7 +80,7 @@ export interface AndroidActivityCallbacks {
onPostResume(activity: any, superFunc: Function): void;
onDestroy(activity: any, superFunc: Function): void;
onBackPressed(activity: any, superFunc: Function): void;
onRequestPermissionsResult(activity: any, requestCode: number, permissions: Array<String>, grantResults: Array<number>, superFunc: Function): void;
onRequestPermissionsResult(activity: any, requestCode: number, permissions: Array<string>, grantResults: Array<number>, superFunc: Function): void;
onActivityResult(activity: any, requestCode: number, resultCode: number, data: any, superFunc: Function);
onNewIntent(activity: any, intent: any, superSetIntentFunc: Function, superFunc: Function): void;
}

View File

@ -1,7 +1,7 @@
// Types.
import { FrameBase } from './frame-common';
export let frameStack: Array<FrameBase> = [];
export const frameStack: Array<FrameBase> = [];
export function topmost(): FrameBase {
if (frameStack.length > 0) {

View File

@ -40,6 +40,7 @@ let fragmentId = -1;
export let moduleLoaded: boolean;
if (global && global.__inspector) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const devtools = require('../../debugger/devtools-elements');
devtools.attachDOMInspectorEventCallbacks(global.__inspector);
devtools.attachDOMInspectorCommandCallbacks(global.__inspector);

View File

@ -1,11 +1,17 @@
import { NavigationType, FrameBase } from './frame-common';
import { Page } from '../page';
import { NavigatedData, Page } from '../page';
import { Observable, EventData } from '../../data/observable';
import { View } from '../core/view';
import { Transition } from '../transition';
export * from './frame-interfaces';
export interface NavigationData extends EventData {
entry?: NavigationEntry;
fromEntry?: NavigationEntry;
isBack?: boolean;
}
/**
* Represents the logical View unit that is responsible for navigation within an application.
* Nested frames are supported, enabling hierarchical navigation scenarios.
@ -210,6 +216,16 @@ export class Frame extends FrameBase {
* @param thisArg - An optional parameter which will be used as `this` context for callback execution.
*/
on(eventNames: string, callback: (args: EventData) => void, thisArg?: any);
/**
* Raised when navigation to the page has started.
*/
public on(event: 'navigatingTo', callback: (args: NavigationData) => void, thisArg?: any);
/**
* Raised when navigation to the page has finished.
*/
public on(event: 'navigatedTo', callback: (args: NavigationData) => void, thisArg?: any);
}
/**
@ -440,7 +456,7 @@ export interface AndroidActivityCallbacks {
onPostResume(activity: any, superFunc: Function): void;
onDestroy(activity: any, superFunc: Function): void;
onBackPressed(activity: any, superFunc: Function): void;
onRequestPermissionsResult(activity: any, requestCode: number, permissions: Array<String>, grantResults: Array<number>, superFunc: Function): void;
onRequestPermissionsResult(activity: any, requestCode: number, permissions: Array<string>, grantResults: Array<number>, superFunc: Function): void;
onActivityResult(activity: any, requestCode: number, resultCode: number, data: any, superFunc: Function);
onNewIntent(activity: any, intent: any, superSetIntentFunc: Function, superFunc: Function): void;
}

View File

@ -67,12 +67,12 @@ export class Frame extends FrameBase {
public _navigateCore(backstackEntry: any) {
super._navigateCore(backstackEntry);
let viewController: UIViewController = backstackEntry.resolvedPage.ios;
const viewController: UIViewController = backstackEntry.resolvedPage.ios;
if (!viewController) {
throw new Error('Required page does not have a viewController created.');
}
let clearHistory = backstackEntry.entry.clearHistory;
const clearHistory = backstackEntry.entry.clearHistory;
if (clearHistory) {
navDepth = -1;
}
@ -101,7 +101,7 @@ export class Frame extends FrameBase {
viewController[TRANSITION] = { name: NON_ANIMATED_TRANSITION };
}
let nativeTransition = _getNativeTransition(navigationTransition, true);
const nativeTransition = _getNativeTransition(navigationTransition, true);
if (!nativeTransition && navigationTransition) {
this._ios.controller.delegate = this._animatedDelegate;
viewController[DELEGATE] = this._animatedDelegate;
@ -116,7 +116,7 @@ export class Frame extends FrameBase {
if (!animated && majorVersion > 10) {
// Reset back button title before pushing view controller to prevent
// displaying default 'back' title (when NavigaitonButton custom title is set).
let barButtonItem = UIBarButtonItem.alloc().initWithTitleStyleTargetAction('', UIBarButtonItemStyle.Plain, null, null);
const barButtonItem = UIBarButtonItem.alloc().initWithTitleStyleTargetAction('', UIBarButtonItemStyle.Plain, null, null);
viewController.navigationItem.backBarButtonItem = barButtonItem;
}
@ -155,7 +155,7 @@ export class Frame extends FrameBase {
// We should hide the current entry from the back stack.
// This is the case for HMR when NavigationType.replace.
if (!Frame._isEntryBackstackVisible(this._currentEntry) || isReplace) {
let newControllers = NSMutableArray.alloc<UIViewController>().initWithArray(this._ios.controller.viewControllers);
const newControllers = NSMutableArray.alloc<UIViewController>().initWithArray(this._ios.controller.viewControllers);
if (newControllers.count === 0) {
throw new Error('Wrong controllers count.');
}
@ -190,8 +190,8 @@ export class Frame extends FrameBase {
super._goBackCore(backstackEntry);
navDepth = backstackEntry[NAV_DEPTH];
let controller = backstackEntry.resolvedPage.ios;
let animated = this._currentEntry ? this._getIsAnimatedNavigation(this._currentEntry.entry) : false;
const controller = backstackEntry.resolvedPage.ios;
const animated = this._currentEntry ? this._getIsAnimatedNavigation(this._currentEntry.entry) : false;
this._updateActionBar(backstackEntry.resolvedPage);
if (Trace.isEnabled()) {
@ -201,7 +201,7 @@ export class Frame extends FrameBase {
this._ios.controller.popToViewControllerAnimated(controller, animated);
}
public _updateActionBar(page?: Page, disableNavBarAnimation: boolean = false): void {
public _updateActionBar(page?: Page, disableNavBarAnimation = false): void {
super._updateActionBar(page);
if (page && this.currentPage && this.currentPage.modal === page) {
@ -209,8 +209,8 @@ export class Frame extends FrameBase {
}
page = page || this.currentPage;
let newValue = this._getNavBarVisible(page);
let disableNavBarAnimationCache = this._ios._disableNavBarAnimation;
const newValue = this._getNavBarVisible(page);
const disableNavBarAnimationCache = this._ios._disableNavBarAnimation;
if (disableNavBarAnimation) {
this._ios._disableNavBarAnimation = true;
@ -249,7 +249,7 @@ export class Frame extends FrameBase {
case 'never':
return false;
case 'auto':
case 'auto':{
let newValue: boolean;
if (page && page.actionBarHidden !== undefined) {
@ -264,6 +264,7 @@ export class Frame extends FrameBase {
}
}
}
}
public static get defaultAnimatedNavigation(): boolean {
return FrameBase.defaultAnimatedNavigation;
@ -305,14 +306,14 @@ export class Frame extends FrameBase {
}
}
let transitionDelegates = new Array<TransitionDelegate>();
const transitionDelegates = new Array<TransitionDelegate>();
@NativeClass
class TransitionDelegate extends NSObject {
private _id: string;
public static initWithOwnerId(id: string): TransitionDelegate {
let delegate = <TransitionDelegate>TransitionDelegate.new();
const delegate = <TransitionDelegate>TransitionDelegate.new();
delegate._id = id;
transitionDelegates.push(delegate);
@ -336,7 +337,7 @@ class TransitionDelegate extends NSObject {
}
}
let index = transitionDelegates.indexOf(this);
const index = transitionDelegates.indexOf(this);
if (index > -1) {
transitionDelegates.splice(index, 1);
}
@ -375,7 +376,7 @@ class UINavigationControllerAnimatedDelegate extends NSObject implements UINavig
return null;
}
let navigationTransition = <NavigationTransition>viewController[TRANSITION];
const navigationTransition = <NavigationTransition>viewController[TRANSITION];
if (!navigationTransition) {
return null;
}
@ -384,8 +385,8 @@ class UINavigationControllerAnimatedDelegate extends NSObject implements UINavig
Trace.write(`UINavigationControllerImpl.navigationControllerAnimationControllerForOperationFromViewControllerToViewController(${operation}, ${fromVC}, ${toVC}), transition: ${JSON.stringify(navigationTransition)}`, Trace.categories.NativeLifecycle);
}
let curve = _getNativeCurve(navigationTransition);
let animationController = _createIOSAnimatedTransitioning(navigationTransition, curve, operation, fromVC, toVC);
const curve = _getNativeCurve(navigationTransition);
const animationController = _createIOSAnimatedTransitioning(navigationTransition, curve, operation, fromVC, toVC);
return animationController;
}
@ -396,7 +397,7 @@ class UINavigationControllerImpl extends UINavigationController {
private _owner: WeakRef<Frame>;
public static initWithOwner(owner: WeakRef<Frame>): UINavigationControllerImpl {
let controller = <UINavigationControllerImpl>UINavigationControllerImpl.new();
const controller = <UINavigationControllerImpl>UINavigationControllerImpl.new();
controller._owner = owner;
return controller;
@ -426,13 +427,13 @@ class UINavigationControllerImpl extends UINavigationController {
}
private animateWithDuration(navigationTransition: NavigationTransition, nativeTransition: UIViewAnimationTransition, transitionType: string, baseCallback: Function): void {
let duration = navigationTransition.duration ? navigationTransition.duration / 1000 : _defaultTransitionDuration;
let curve = _getNativeCurve(navigationTransition);
const duration = navigationTransition.duration ? navigationTransition.duration / 1000 : _defaultTransitionDuration;
const curve = _getNativeCurve(navigationTransition);
let transitionTraced = Trace.isCategorySet(Trace.categories.Transition);
const transitionTraced = Trace.isCategorySet(Trace.categories.Transition);
let transitionDelegate: TransitionDelegate;
if (transitionTraced) {
let id = _getTransitionId(nativeTransition, transitionType);
const id = _getTransitionId(nativeTransition, transitionType);
transitionDelegate = TransitionDelegate.initWithOwnerId(id);
}
@ -451,12 +452,12 @@ class UINavigationControllerImpl extends UINavigationController {
@profile
public pushViewControllerAnimated(viewController: UIViewController, animated: boolean): void {
let navigationTransition = <NavigationTransition>viewController[TRANSITION];
const navigationTransition = <NavigationTransition>viewController[TRANSITION];
if (Trace.isEnabled()) {
Trace.write(`UINavigationControllerImpl.pushViewControllerAnimated(${viewController}, ${animated}); transition: ${JSON.stringify(navigationTransition)}`, Trace.categories.NativeLifecycle);
}
let nativeTransition = _getNativeTransition(navigationTransition, true);
const nativeTransition = _getNativeTransition(navigationTransition, true);
if (!animated || !navigationTransition || !nativeTransition) {
super.pushViewControllerAnimated(viewController, animated);
@ -470,14 +471,14 @@ class UINavigationControllerImpl extends UINavigationController {
@profile
public setViewControllersAnimated(viewControllers: NSArray<any>, animated: boolean): void {
let viewController = viewControllers.lastObject;
let navigationTransition = <NavigationTransition>viewController[TRANSITION];
const viewController = viewControllers.lastObject;
const navigationTransition = <NavigationTransition>viewController[TRANSITION];
if (Trace.isEnabled()) {
Trace.write(`UINavigationControllerImpl.setViewControllersAnimated(${viewControllers}, ${animated}); transition: ${JSON.stringify(navigationTransition)}`, Trace.categories.NativeLifecycle);
}
let nativeTransition = _getNativeTransition(navigationTransition, true);
const nativeTransition = _getNativeTransition(navigationTransition, true);
if (!animated || !navigationTransition || !nativeTransition) {
super.setViewControllersAnimated(viewControllers, animated);
@ -490,8 +491,8 @@ class UINavigationControllerImpl extends UINavigationController {
}
public popViewControllerAnimated(animated: boolean): UIViewController {
let lastViewController = this.viewControllers.lastObject;
let navigationTransition = <NavigationTransition>lastViewController[TRANSITION];
const lastViewController = this.viewControllers.lastObject;
const navigationTransition = <NavigationTransition>lastViewController[TRANSITION];
if (Trace.isEnabled()) {
Trace.write(`UINavigationControllerImpl.popViewControllerAnimated(${animated}); transition: ${JSON.stringify(navigationTransition)}`, Trace.categories.NativeLifecycle);
}
@ -501,7 +502,7 @@ class UINavigationControllerImpl extends UINavigationController {
return super.popViewControllerAnimated(false);
}
let nativeTransition = _getNativeTransition(navigationTransition, false);
const nativeTransition = _getNativeTransition(navigationTransition, false);
if (!animated || !navigationTransition || !nativeTransition) {
return super.popViewControllerAnimated(animated);
}
@ -514,8 +515,8 @@ class UINavigationControllerImpl extends UINavigationController {
}
public popToViewControllerAnimated(viewController: UIViewController, animated: boolean): NSArray<UIViewController> {
let lastViewController = this.viewControllers.lastObject;
let navigationTransition = <NavigationTransition>lastViewController[TRANSITION];
const lastViewController = this.viewControllers.lastObject;
const navigationTransition = <NavigationTransition>lastViewController[TRANSITION];
if (Trace.isEnabled()) {
Trace.write(`UINavigationControllerImpl.popToViewControllerAnimated(${viewController}, ${animated}); transition: ${JSON.stringify(navigationTransition)}`, Trace.categories.NativeLifecycle);
}
@ -525,7 +526,7 @@ class UINavigationControllerImpl extends UINavigationController {
return super.popToViewControllerAnimated(viewController, false);
}
let nativeTransition = _getNativeTransition(navigationTransition, false);
const nativeTransition = _getNativeTransition(navigationTransition, false);
if (!animated || !navigationTransition || !nativeTransition) {
return super.popToViewControllerAnimated(viewController, animated);
}

View File

@ -1,6 +1,6 @@
// Definitions for Android API lvl 21 transitions
declare module android {
export module transition {
declare namespace android {
export namespace transition {
export abstract class Transition extends java.lang.Object {
addListener(transition: Transition.TransitionListener): Transition;
removeListener(transition: Transition.TransitionListener): Transition;
@ -26,7 +26,7 @@ declare module android {
constructor();
}
export module Transition {
export namespace Transition {
export interface TransitionListener {
onTransitionStart(transition: android.transition.Transition): void;
onTransitionEnd(transition: android.transition.Transition): void;
@ -37,7 +37,7 @@ declare module android {
}
}
export module app {
export namespace app {
export interface Fragment {
getEnterTransition(): android.transition.Transition;
getExitTransition(): android.transition.Transition;

View File

@ -26,7 +26,7 @@ export enum SwipeDirection {
down = 1 << 3,
}
export module TouchAction {
export namespace TouchAction {
export const down = 'down';
export const up = 'up';
export const move = 'move';
@ -34,7 +34,7 @@ export module TouchAction {
}
export function toString(type: GestureTypes, separator?: string): string {
let types = new Array<string>();
const types = new Array<string>();
if (type & GestureTypes.tap) {
types.push('tap');
@ -74,7 +74,7 @@ export function toString(type: GestureTypes, separator?: string): string {
// NOTE: toString could return the text of multiple GestureTypes.
// Souldn't fromString do split on separator and return multiple GestureTypes?
export function fromString(type: string): GestureTypes {
let t = type.trim().toLowerCase();
const t = type.trim().toLowerCase();
if (t === 'tap') {
return GestureTypes.tap;
@ -128,7 +128,7 @@ export abstract class GesturesObserverBase implements GesturesObserverDefinition
public disconnect() {
// remove gesture observer from map
if (this.target) {
let list = this.target.getGestureObservers(this.type);
const list = this.target.getGestureObservers(this.type);
if (list && list.length > 0) {
for (let i = 0; i < list.length; i++) {
if (list[i].callback === this.callback) {

View File

@ -29,7 +29,7 @@ function initializeTapAndDoubleTapGestureListener() {
private _target: View;
private _type: number;
private _lastUpTime: number = 0;
private _lastUpTime = 0;
private _tapTimeoutId: number;
private static DoubleTapTimeout = android.view.ViewConfiguration.getDoubleTapTimeout();
@ -187,8 +187,8 @@ function initializeSwipeGestureListener() {
let result = false;
let args: SwipeGestureEventData;
try {
let deltaY = currentEvent.getY() - initialEvent.getY();
let deltaX = currentEvent.getX() - initialEvent.getX();
const deltaY = currentEvent.getY() - initialEvent.getY();
const deltaX = currentEvent.getX() - initialEvent.getX();
if (Math.abs(deltaX) > Math.abs(deltaY)) {
if (Math.abs(deltaX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
@ -479,7 +479,7 @@ class CustomPanGestureDetector {
private trackStop(currentEvent: android.view.MotionEvent, cacheEvent: boolean) {
if (this.isTracking) {
let args = _getPanArgs(this.deltaX, this.deltaY, this.target, GestureStateTypes.ended, null, currentEvent);
const args = _getPanArgs(this.deltaX, this.deltaY, this.target, GestureStateTypes.ended, null, currentEvent);
_executeCallback(this.observer, args);
this.deltaX = undefined;
@ -495,21 +495,21 @@ class CustomPanGestureDetector {
}
private trackStart(currentEvent: android.view.MotionEvent) {
let inital = this.getEventCoordinates(this.lastEventCache ? this.lastEventCache : currentEvent);
const inital = this.getEventCoordinates(this.lastEventCache ? this.lastEventCache : currentEvent);
this.initialX = inital.x;
this.initialY = inital.y;
this.isTracking = true;
let args = _getPanArgs(0, 0, this.target, GestureStateTypes.began, null, currentEvent);
const args = _getPanArgs(0, 0, this.target, GestureStateTypes.began, null, currentEvent);
_executeCallback(this.observer, args);
}
private trackChange(currentEvent: android.view.MotionEvent) {
let current = this.getEventCoordinates(currentEvent);
const current = this.getEventCoordinates(currentEvent);
this.deltaX = current.x - this.initialX;
this.deltaY = current.y - this.initialY;
let args = _getPanArgs(this.deltaX, this.deltaY, this.target, GestureStateTypes.changed, null, currentEvent);
const args = _getPanArgs(this.deltaX, this.deltaY, this.target, GestureStateTypes.changed, null, currentEvent);
_executeCallback(this.observer, args);
}
@ -523,7 +523,7 @@ class CustomPanGestureDetector {
} else {
const offX = event.getRawX() - event.getX();
const offY = event.getRawY() - event.getY();
let res = { x: 0, y: 0 };
const res = { x: 0, y: 0 };
for (let i = 0; i < count; i++) {
res.x += event.getX(i) + offX;
@ -560,12 +560,12 @@ class CustomRotateGestureDetector {
}
public onTouchEvent(event: android.view.MotionEvent) {
let pointerID = event.getPointerId(event.getActionIndex());
let wasTracking = this.isTracking;
const pointerID = event.getPointerId(event.getActionIndex());
const wasTracking = this.isTracking;
switch (event.getActionMasked()) {
case android.view.MotionEvent.ACTION_DOWN:
case android.view.MotionEvent.ACTION_POINTER_DOWN:
case android.view.MotionEvent.ACTION_POINTER_DOWN:{
let assigned = false;
if (this.trackedPtrId1 === INVALID_POINTER_ID && pointerID !== this.trackedPtrId2) {
this.trackedPtrId1 = pointerID;
@ -582,7 +582,7 @@ class CustomRotateGestureDetector {
this.executeCallback(event, GestureStateTypes.began);
}
break;
}
case android.view.MotionEvent.ACTION_MOVE:
if (this.isTracking) {
this.updateAngle(event);
@ -617,7 +617,7 @@ class CustomRotateGestureDetector {
}
private executeCallback(event: android.view.MotionEvent, state: GestureStateTypes) {
let args = <RotationGestureEventData>{
const args = <RotationGestureEventData>{
type: GestureTypes.rotation,
view: this.target,
android: event,
@ -632,7 +632,7 @@ class CustomRotateGestureDetector {
}
private updateAngle(event: android.view.MotionEvent) {
let newPointersAngle = this.getPointersAngle(event);
const newPointersAngle = this.getPointersAngle(event);
let result = ((newPointersAngle - this.initalPointersAngle) * TO_DEGREES) % 360;
if (result < -180) {
@ -646,10 +646,10 @@ class CustomRotateGestureDetector {
}
private getPointersAngle(event: android.view.MotionEvent) {
let firstX = event.getX(event.findPointerIndex(this.trackedPtrId1));
let firstY = event.getY(event.findPointerIndex(this.trackedPtrId1));
let secondX = event.getX(event.findPointerIndex(this.trackedPtrId2));
let secondY = event.getY(event.findPointerIndex(this.trackedPtrId2));
const firstX = event.getX(event.findPointerIndex(this.trackedPtrId1));
const firstY = event.getY(event.findPointerIndex(this.trackedPtrId1));
const secondX = event.getX(event.findPointerIndex(this.trackedPtrId2));
const secondY = event.getY(event.findPointerIndex(this.trackedPtrId2));
return Math.atan2(secondY - firstY, secondX - firstX);
}

View File

@ -86,7 +86,7 @@ export enum SwipeDirection {
/**
* Defines a touch action
*/
export module TouchAction {
export namespace TouchAction {
/**
* Down action.
*/

View File

@ -37,7 +37,7 @@ class UIGestureRecognizerDelegateImpl extends NSObject implements UIGestureRecog
return false;
}
}
let recognizerDelegateInstance: UIGestureRecognizerDelegateImpl = <UIGestureRecognizerDelegateImpl>UIGestureRecognizerDelegateImpl.new();
const recognizerDelegateInstance: UIGestureRecognizerDelegateImpl = <UIGestureRecognizerDelegateImpl>UIGestureRecognizerDelegateImpl.new();
@NativeClass
class UIGestureRecognizerImpl extends NSObject {
@ -248,9 +248,9 @@ export class GesturesObserver extends GesturesObserverBase {
private _detach() {
if (this.target && this.target.nativeViewProtected) {
for (let name in this._recognizers) {
for (const name in this._recognizers) {
if (this._recognizers.hasOwnProperty(name)) {
let item = <RecognizerCache>this._recognizers[name];
const item = <RecognizerCache>this._recognizers[name];
this.target.nativeViewProtected.removeGestureRecognizer(item.recognizer);
item.recognizer = null;
@ -591,7 +591,7 @@ class TouchGestureEventData implements TouchGestureEventData {
if (!this._allPointers) {
this._allPointers = [];
let nsArr = this.ios.event.allTouches.allObjects;
const nsArr = this.ios.event.allTouches.allObjects;
for (let i = 0; i < nsArr.count; i++) {
this._allPointers.push(new Pointer(nsArr.objectAtIndex(i), this.view));
}

View File

@ -41,7 +41,7 @@ export abstract class ImageBase extends View implements ImageDefinition {
this.isLoading = true;
const imageLoaded = (source: ImageSource) => {
let currentValue = this.src;
const currentValue = this.src;
if (currentValue !== originalValue) {
return;
}

View File

@ -8,7 +8,7 @@ export * from './image-common';
export class Image extends ImageBase {
nativeViewProtected: UIImageView;
private _imageSourceAffectsLayout: boolean = true;
private _imageSourceAffectsLayout = true;
private _templateImageWasCreated: boolean;
public createNativeView() {

View File

@ -55,7 +55,7 @@ export class Label extends TextBase implements LabelDefinition {
}
public onMeasure(widthMeasureSpec: number, heightMeasureSpec: number): void {
let nativeView = this.nativeTextViewProtected;
const nativeView = this.nativeTextViewProtected;
if (nativeView) {
const width = layout.getMeasureSpecSize(widthMeasureSpec);
const widthMode = layout.getMeasureSpecMode(widthMeasureSpec);

Some files were not shown because too many files have changed in this diff Show More