From c1f231d88ea00ef23161b50f9a183bda2a912ab2 Mon Sep 17 00:00:00 2001 From: Martin Guillon Date: Wed, 11 Nov 2020 17:46:36 +0100 Subject: [PATCH] chore: fix eslint issues (#9017) --- .eslintrc.json | 16 +- packages/core/__tests__/css/parser.ts | 8 +- .../core/__tests__/observable/observable.ts | 2 +- .../core/__tests__/ui/styling/css-selector.ts | 70 ++--- .../application-settings/index.android.ts | 2 +- .../core/application/application-common.ts | 7 +- packages/core/application/index.android.ts | 3 + packages/core/application/index.d.ts | 50 ++-- packages/core/application/index.ios.ts | 8 +- packages/core/color/color-common.ts | 10 +- packages/core/css/css-tree-parser.ts | 12 +- packages/core/css/parser.ts | 34 ++- packages/core/data/observable-array/index.ts | 18 +- .../debugger/InspectorBackendCommands.ios.ts | 4 +- .../core/debugger/devtools-elements.common.ts | 12 +- packages/core/debugger/dom-node.ts | 5 +- packages/core/debugger/index.ts | 2 +- .../core/debugger/webinspector-css.ios.ts | 1 + .../core/debugger/webinspector-dom.ios.ts | 1 + .../core/debugger/webinspector-network.ios.ts | 21 +- .../file-system/file-system-access.android.ts | 2 +- packages/core/file-system/index.ts | 22 +- packages/core/fps-meter/fps-native.ios.ts | 4 +- packages/core/fps-meter/index.ts | 2 +- packages/core/global-types.d.ts | 13 +- packages/core/globals/index.ts | 13 +- .../core/http/http-request/index.android.ts | 2 +- packages/core/http/http-request/index.ios.ts | 2 +- .../core/image-asset/image-asset-common.ts | 8 +- packages/core/image-asset/index.android.ts | 10 +- packages/core/image-asset/index.ios.ts | 16 +- packages/core/js-libs/esprima/esprima.d.ts | 20 +- packages/core/module-name-resolver/index.ts | 2 +- .../non-bundle-workflow-compat.ts | 7 +- .../qualifier-matcher/index.ts | 16 +- packages/core/platform/index.android.ts | 2 +- .../ios/typings/objc!MaterialComponents.d.ts | 52 ++-- packages/core/profiling/index.ts | 21 +- packages/core/text/index.android.ts | 2 +- packages/core/text/index.d.ts | 2 +- packages/core/text/index.ios.ts | 2 +- packages/core/text/text-common.ts | 18 +- packages/core/timer/index.android.ts | 2 +- packages/core/timer/index.ios.ts | 18 +- packages/core/trace/index.ts | 18 +- .../core/ui/action-bar/action-bar-common.ts | 2 +- packages/core/ui/action-bar/index.android.ts | 40 +-- packages/core/ui/action-bar/index.ios.ts | 18 +- .../core/ui/activity-indicator/index.ios.ts | 2 +- .../core/ui/animation/animation-common.ts | 12 +- .../core/ui/animation/animation-interfaces.ts | 5 +- packages/core/ui/animation/index.android.ts | 38 +-- packages/core/ui/animation/index.ios.ts | 75 ++--- .../core/ui/animation/keyframe-animation.ts | 30 +- .../ui/bottom-navigation/index.android.ts | 18 +- .../core/ui/bottom-navigation/index.ios.ts | 2 +- packages/core/ui/builder/binding-builder.ts | 6 +- .../ui/builder/component-builder/index.ts | 7 +- packages/core/ui/builder/index.ts | 14 +- .../core/ui/builder/module-name-sanitizer.ts | 2 +- packages/core/ui/button/index.ios.ts | 38 +-- packages/core/ui/content-view/index.ts | 2 +- packages/core/ui/core/bindable/index.ts | 79 +++--- .../ui/core/control-state-change/index.ios.ts | 2 +- packages/core/ui/core/properties/index.ts | 62 ++--- packages/core/ui/core/view-base/index.ts | 18 +- packages/core/ui/core/view/index.android.ts | 22 +- packages/core/ui/core/view/index.d.ts | 16 +- packages/core/ui/core/view/index.ios.ts | 20 +- packages/core/ui/core/view/view-common.ts | 46 ++-- .../view/view-helper/view-helper-common.ts | 16 +- .../core/ui/core/weak-event-listener/index.ts | 2 +- packages/core/ui/dialogs/dialogs-common.ts | 35 +-- packages/core/ui/dialogs/index.android.ts | 50 ++-- packages/core/ui/dialogs/index.d.ts | 4 +- packages/core/ui/dialogs/index.ios.ts | 84 +++--- .../ui/editable-text-base/index.android.ts | 16 +- .../core/ui/editable-text-base/index.ios.ts | 18 +- packages/core/ui/enums/index.ts | 158 +++++------ packages/core/ui/frame/activity.android.ts | 1 + packages/core/ui/frame/fragment.android.ts | 2 +- .../core/ui/frame/fragment.transitions.ios.ts | 2 +- packages/core/ui/frame/frame-common.ts | 3 +- packages/core/ui/frame/frame-interfaces.ts | 2 +- packages/core/ui/frame/frame-stack.ts | 2 +- packages/core/ui/frame/index.android.ts | 23 +- packages/core/ui/frame/index.d.ts | 2 +- packages/core/ui/frame/index.ios.ts | 67 ++--- .../frame/transition-definitions.android.d.ts | 8 +- packages/core/ui/gestures/gestures-common.ts | 8 +- packages/core/ui/gestures/index.android.ts | 38 +-- packages/core/ui/gestures/index.d.ts | 2 +- packages/core/ui/gestures/index.ios.ts | 8 +- packages/core/ui/image/image-common.ts | 2 +- packages/core/ui/image/index.ios.ts | 2 +- packages/core/ui/label/index.ios.ts | 2 +- .../ui/layouts/absolute-layout/index.ios.ts | 2 +- .../core/ui/layouts/dock-layout/index.ios.ts | 8 +- .../flexbox-layout/flexbox-layout-common.ts | 60 ++-- .../ui/layouts/flexbox-layout/index.ios.ts | 222 +++++++-------- .../layouts/grid-layout/grid-layout-common.ts | 4 +- .../core/ui/layouts/grid-layout/index.ios.ts | 256 +++++++++--------- .../core/ui/layouts/stack-layout/index.ios.ts | 14 +- .../core/ui/layouts/wrap-layout/index.ios.ts | 24 +- packages/core/ui/list-picker/index.android.ts | 4 +- packages/core/ui/list-picker/index.ios.ts | 12 +- .../core/ui/list-picker/list-picker-common.ts | 10 +- packages/core/ui/list-view/index.android.ts | 24 +- packages/core/ui/list-view/index.ios.ts | 46 ++-- .../core/ui/list-view/list-view-common.ts | 6 +- packages/core/ui/page/index.ios.ts | 4 +- packages/core/ui/progress/index.android.ts | 6 +- packages/core/ui/progress/index.ios.ts | 2 +- packages/core/ui/repeater/index.ts | 2 +- packages/core/ui/scroll-view/index.android.ts | 10 +- packages/core/ui/scroll-view/index.ios.ts | 8 +- .../core/ui/scroll-view/scroll-view-common.ts | 2 +- packages/core/ui/search-bar/index.android.ts | 6 +- packages/core/ui/search-bar/index.ios.ts | 20 +- packages/core/ui/segmented-bar/index.ios.ts | 24 +- .../ui/segmented-bar/segmented-bar-common.ts | 8 +- packages/core/ui/slider/index.ios.ts | 8 +- packages/core/ui/slider/slider-common.ts | 2 +- packages/core/ui/styling/background-common.ts | 16 +- .../core/ui/styling/background.android.ts | 6 +- packages/core/ui/styling/background.d.ts | 4 +- packages/core/ui/styling/background.ios.ts | 4 +- packages/core/ui/styling/converters.ts | 2 +- .../core/ui/styling/css-animation-parser.ts | 22 +- .../core/ui/styling/css-selector/index.ts | 30 +- packages/core/ui/styling/font-common.ts | 30 +- packages/core/ui/styling/font.d.ts | 2 +- packages/core/ui/styling/font.ios.ts | 10 +- packages/core/ui/styling/style-properties.ts | 134 ++++----- packages/core/ui/styling/style-scope.d.ts | 3 +- packages/core/ui/styling/style-scope.ts | 70 ++--- packages/core/ui/switch/index.ios.ts | 6 +- packages/core/ui/tab-view/index.android.ts | 10 +- packages/core/ui/tab-view/index.ios.ts | 20 +- packages/core/ui/tab-view/tab-view-common.ts | 8 +- packages/core/ui/tabs/index.android.ts | 14 +- packages/core/ui/tabs/index.ios.ts | 32 +-- packages/core/ui/text-base/index.android.ts | 12 +- packages/core/ui/text-base/index.ios.ts | 34 +-- packages/core/ui/text-base/span.ts | 2 +- .../core/ui/text-base/text-base-common.ts | 4 +- packages/core/ui/text-field/index.ios.ts | 2 +- packages/core/ui/text-view/index.ios.ts | 32 +-- packages/core/ui/time-picker/index.ios.ts | 10 +- .../core/ui/time-picker/time-picker-common.ts | 2 +- .../core/ui/transition/fade-transition.ios.ts | 8 +- packages/core/ui/transition/index.android.ts | 2 +- packages/core/ui/transition/index.d.ts | 2 +- .../ui/transition/slide-transition.ios.ts | 18 +- packages/core/ui/utils.android.ts | 2 +- packages/core/ui/utils.d.ts | 2 +- packages/core/ui/utils.ios.ts | 2 +- packages/core/ui/web-view/index.android.ts | 14 +- packages/core/ui/web-view/web-view-common.ts | 4 +- packages/core/utils/debug.ts | 4 +- packages/core/utils/index.d.ts | 4 +- packages/core/utils/index.ios.ts | 2 +- .../core/utils/mainthread-helper.android.ts | 2 +- packages/core/utils/mainthread-helper.ios.ts | 2 +- packages/core/utils/module-merge.ts | 2 +- packages/core/utils/native-helper.android.ts | 6 +- packages/core/utils/native-helper.d.ts | 4 +- packages/core/utils/native-helper.ios.ts | 6 +- packages/core/utils/utils-common.ts | 10 +- packages/core/xhr/index.ts | 42 +-- packages/core/xml/index.ts | 9 +- 171 files changed, 1607 insertions(+), 1550 deletions(-) diff --git a/.eslintrc.json b/.eslintrc.json index 74d9d35a6..a2495852f 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -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", { diff --git a/packages/core/__tests__/css/parser.ts b/packages/core/__tests__/css/parser.ts index c7fae1e9d..edc6786eb 100644 --- a/packages/core/__tests__/css/parser.ts +++ b/packages/core/__tests__/css/parser.ts @@ -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); } diff --git a/packages/core/__tests__/observable/observable.ts b/packages/core/__tests__/observable/observable.ts index 3379bcca8..00fd4a116 100644 --- a/packages/core/__tests__/observable/observable.ts +++ b/packages/core/__tests__/observable/observable.ts @@ -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 () { diff --git a/packages/core/__tests__/ui/styling/css-selector.ts b/packages/core/__tests__/ui/styling/css-selector.ts index e38fc16fe..131751125 100644 --- a/packages/core/__tests__/ui/styling/css-selector.ts +++ b/packages/core/__tests__/ui/styling/css-selector.ts @@ -21,30 +21,30 @@ describe('ui', () => { ); }); - function create(css: string, source: string = 'css-selectors.ts@test'): { rules: selector.RuleSet[]; map: selector.SelectorsMap } { - 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 } { + 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().set(grid, { attributes: new Set(['promotion']) }).set(button, { pseudoClasses: new Set(['highlighted']) }); + const expected = new Map().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().set(prod, { attributes: new Set(['special']) }); + const expected = new Map().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().set(disabledButton, { pseudoClasses: new Set(['disabled']) }).set(button, { pseudoClasses: new Set(['highlighted']) }); + const expected = new Map().set(disabledButton, { pseudoClasses: new Set(['disabled']) }).set(button, { pseudoClasses: new Set(['highlighted']) }); assert.deepEqual(match.changeMap, expected); }); diff --git a/packages/core/application-settings/index.android.ts b/packages/core/application-settings/index.android.ts index 1323bc7c0..b5a14a155 100644 --- a/packages/core/application-settings/index.android.ts +++ b/packages/core/application-settings/index.android.ts @@ -96,7 +96,7 @@ export function getAllKeys(): Array { const iterator = mappedPreferences.keySet().iterator(); const result = []; while (iterator.hasNext()) { - let key = iterator.next(); + const key = iterator.next(); result.push(key); } diff --git a/packages/core/application/application-common.ts b/packages/core/application/application-common.ts index 208fbfd6d..5cf6cabdb 100644 --- a/packages/core/application/application-common.ts +++ b/packages/core/application/application-common.ts @@ -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); diff --git a/packages/core/application/index.android.ts b/packages/core/application/index.android.ts index aadc3ff5d..c3dbacd38 100644 --- a/packages/core/application/index.android.ts +++ b/packages/core/application/index.android.ts @@ -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'; diff --git a/packages/core/application/index.d.ts b/packages/core/application/index.d.ts index fff9e1760..d2cb041a4 100644 --- a/packages/core/application/index.d.ts +++ b/packages/core/application/index.d.ts @@ -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. */ diff --git a/packages/core/application/index.ios.ts b/packages/core/application/index.ios.ts index 2ad1bb4b4..e502b4758 100644 --- a/packages/core/application/index.ios.ts +++ b/packages/core/application/index.ios.ts @@ -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); } diff --git a/packages/core/color/color-common.ts b/packages/core/color/color-common.ts index 7aa4e474b..6c6bd72e9 100644 --- a/packages/core/color/color-common.ts +++ b/packages/core/color/color-common.ts @@ -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.'); } diff --git a/packages/core/css/css-tree-parser.ts b/packages/core/css/css-tree-parser.ts index 25b5661c1..287c1c9d4 100644 --- a/packages/core/css/css-tree-parser.ts +++ b/packages/core/css/css-tree-parser.ts @@ -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, diff --git a/packages/core/css/parser.ts b/packages/core/css/parser.ts index 5d66dc542..c6725ca5d 100644 --- a/packages/core/css/parser.ts +++ b/packages/core/css/parser.ts @@ -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 { 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 { 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> { unitRegEx.lastIndex = start; const result = unitRegEx.exec(text); @@ -743,7 +743,7 @@ export function parseSimpleIdentifierSelector(text: string, start = 0): Parsed { 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 | /* */ InputTokenObject | FunctionInputToken | FunctionToken | SimpleBlock | AtKeywordToken; @@ -1334,7 +1335,7 @@ export class CSS3Parser { case ' ': continue; case '': + case '-->':{ if (this.topLevelFlag) { continue; } @@ -1345,6 +1346,7 @@ export class CSS3Parser { } continue; } + } if ((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); diff --git a/packages/core/data/observable-array/index.ts b/packages/core/data/observable-array/index.ts index 1ad212a9c..beba6eeee 100644 --- a/packages/core/data/observable-array/index.ts +++ b/packages/core/data/observable-array/index.ts @@ -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 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 extends Observable { object: this, action: ChangeType.Add, index: null, - removed: new Array(), + removed: [], addedCount: 1, }; @@ -92,7 +94,7 @@ export class ObservableArray 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(>{ @@ -114,7 +116,7 @@ export class ObservableArray 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 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 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 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(>{ eventName: CHANGE, @@ -276,7 +278,7 @@ export class ObservableArray 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; diff --git a/packages/core/debugger/InspectorBackendCommands.ios.ts b/packages/core/debugger/InspectorBackendCommands.ios.ts index 6fde5b794..1bdecf631 100644 --- a/packages/core/debugger/InspectorBackendCommands.ios.ts +++ b/packages/core/debugger/InspectorBackendCommands.ios.ts @@ -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); } diff --git a/packages/core/debugger/devtools-elements.common.ts b/packages/core/debugger/devtools-elements.common.ts index c1e9f00b7..91171ff38 100644 --- a/packages/core/debugger/devtools-elements.common.ts +++ b/packages/core/debugger/devtools-elements.common.ts @@ -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 = view.parent; + const parent = 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) { diff --git a/packages/core/debugger/dom-node.ts b/packages/core/debugger/dom-node.ts index 6c167c775..d77d693b5 100644 --- a/packages/core/debugger/dom-node.ts +++ b/packages/core/debugger/dom-node.ts @@ -14,8 +14,11 @@ function lazy(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); diff --git a/packages/core/debugger/index.ts b/packages/core/debugger/index.ts index 734ad7367..37980820e 100644 --- a/packages/core/debugger/index.ts +++ b/packages/core/debugger/index.ts @@ -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) { diff --git a/packages/core/debugger/webinspector-css.ios.ts b/packages/core/debugger/webinspector-css.ios.ts index bd02bde6b..623cb8e2e 100644 --- a/packages/core/debugger/webinspector-css.ios.ts +++ b/packages/core/debugger/webinspector-css.ios.ts @@ -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 '.'; diff --git a/packages/core/debugger/webinspector-dom.ios.ts b/packages/core/debugger/webinspector-dom.ios.ts index 302d67a3b..7becd39d4 100644 --- a/packages/core/debugger/webinspector-dom.ios.ts +++ b/packages/core/debugger/webinspector-dom.ios.ts @@ -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 '.'; diff --git a/packages/core/debugger/webinspector-network.ios.ts b/packages/core/debugger/webinspector-network.ios.ts index 21d27bce9..4cbf14932 100644 --- a/packages/core/debugger/webinspector-network.ios.ts +++ b/packages/core/debugger/webinspector-network.ios.ts @@ -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; diff --git a/packages/core/file-system/file-system-access.android.ts b/packages/core/file-system/file-system-access.android.ts index 17ae1fc68..18a213f9e 100644 --- a/packages/core/file-system/file-system-access.android.ts +++ b/packages/core/file-system/file-system-access.android.ts @@ -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]; diff --git a/packages/core/file-system/index.ts b/packages/core/file-system/index.ts index c499abb43..487ec4e8c 100644 --- a/packages/core/file-system/index.ts +++ b/packages/core/file-system/index.ts @@ -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); } diff --git a/packages/core/fps-meter/fps-native.ios.ts b/packages/core/fps-meter/fps-native.ios.ts index 0d37d7275..56e54a4c3 100644 --- a/packages/core/fps-meter/fps-native.ios.ts +++ b/packages/core/fps-meter/fps-native.ios.ts @@ -5,14 +5,14 @@ class FrameHandlerImpl extends NSObject { private _owner: WeakRef; public static initWithOwner(owner: WeakRef): FrameHandlerImpl { - let handler = FrameHandlerImpl.new(); + const handler = 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); } diff --git a/packages/core/fps-meter/index.ts b/packages/core/fps-meter/index.ts index 7b4f2553f..497edbc1f 100644 --- a/packages/core/fps-meter/index.ts +++ b/packages/core/fps-meter/index.ts @@ -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); } diff --git a/packages/core/global-types.d.ts b/packages/core/global-types.d.ts index 7bb924592..6703d7663 100644 --- a/packages/core/global-types.d.ts +++ b/packages/core/global-types.d.ts @@ -1,3 +1,4 @@ +/* eslint-disable no-var */ declare var global: NodeJS.Global & typeof globalThis; interface ModuleResolver { @@ -252,12 +253,6 @@ declare function NativeClass(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 @@ -265,6 +260,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. diff --git a/packages/core/globals/index.ts b/packages/core/globals/index.ts index 8e419af92..cdc7645dd 100644 --- a/packages/core/globals/index.ts +++ b/packages/core/globals/index.ts @@ -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 (!(global).__extends) { (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 (global).moduleResolvers) { + for (const resolver of (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]; } }; diff --git a/packages/core/http/http-request/index.android.ts b/packages/core/http/http-request/index.android.ts index 8ebbd8f75..6959415c2 100644 --- a/packages/core/http/http-request/index.android.ts +++ b/packages/core/http/http-request/index.android.ts @@ -191,7 +191,7 @@ function buildJavaOptions(options: httpModule.HttpRequestOptions) { const arrayList = new java.util.ArrayList(); 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] + '')); } diff --git a/packages/core/http/http-request/index.ios.ts b/packages/core/http/http-request/index.ios.ts index fd802de31..6121b188f 100644 --- a/packages/core/http/http-request/index.ios.ts +++ b/packages/core/http/http-request/index.ios.ts @@ -87,7 +87,7 @@ export function request(options: httpModule.HttpRequestOptions): Promise 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; diff --git a/packages/core/image-asset/index.ios.ts b/packages/core/image-asset/index.ios.ts index 32ec30583..67b0b912b 100644 --- a/packages/core/image-asset/index.ios.ts +++ b/packages/core/image-asset/index.ios.ts @@ -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; diff --git a/packages/core/js-libs/esprima/esprima.d.ts b/packages/core/js-libs/esprima/esprima.d.ts index 519a73a9c..69dffe728 100644 --- a/packages/core/js-libs/esprima/esprima.d.ts +++ b/packages/core/js-libs/esprima/esprima.d.ts @@ -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 ] } diff --git a/packages/core/module-name-resolver/index.ts b/packages/core/module-name-resolver/index.ts index abbb423f1..5e9af42c1 100644 --- a/packages/core/module-name-resolver/index.ts +++ b/packages/core/module-name-resolver/index.ts @@ -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; diff --git a/packages/core/module-name-resolver/non-bundle-workflow-compat.ts b/packages/core/module-name-resolver/non-bundle-workflow-compat.ts index 91aa9dbd9..1c205f84a 100644 --- a/packages/core/module-name-resolver/non-bundle-workflow-compat.ts +++ b/packages/core/module-name-resolver/non-bundle-workflow-compat.ts @@ -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)); } diff --git a/packages/core/module-name-resolver/qualifier-matcher/index.ts b/packages/core/module-name-resolver/qualifier-matcher/index.ts index 7758dd79f..917a22024 100644 --- a/packages/core/module-name-resolver/qualifier-matcher/index.ts +++ b/packages/core/module-name-resolver/qualifier-matcher/index.ts @@ -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 = [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, context: PlatformContext): string { - let fullPath: string = ext ? path + ext : path; + const fullPath: string = ext ? path + ext : path; let bestValue = -1; let result: string = null; diff --git a/packages/core/platform/index.android.ts b/packages/core/platform/index.android.ts index f414bf909..56db49cec 100644 --- a/packages/core/platform/index.android.ts +++ b/packages/core/platform/index.android.ts @@ -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; diff --git a/packages/core/platforms/ios/typings/objc!MaterialComponents.d.ts b/packages/core/platforms/ios/typings/objc!MaterialComponents.d.ts index 71b6b1478..d44da6869 100644 --- a/packages/core/platforms/ios/typings/objc!MaterialComponents.d.ts +++ b/packages/core/platforms/ios/typings/objc!MaterialComponents.d.ts @@ -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; +declare let MaterialComponentsVersionString: interop.Reference; diff --git a/packages/core/profiling/index.ts b/packages/core/profiling/index.ts index ae8386cb0..91cb4c04e 100644 --- a/packages/core/profiling/index.ts +++ b/packages/core/profiling/index.ts @@ -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 ? (org).nativescript.Process.getUpTime() : (global).__tns_uptime(); @@ -98,10 +98,10 @@ export function isRunning(name: string): boolean { function countersProfileFunctionFactory(fn: F, name: string, type: MemberType = MemberType.Instance): F { profileNames.push(name); - return function () { + return function (...args) { start(name); try { - return fn.apply(this, arguments); + return fn(...args); } finally { stop(name); } @@ -110,19 +110,19 @@ function countersProfileFunctionFactory(fn: F, name: string, function timelineProfileFunctionFactory(fn: F, name: string, type: MemberType = MemberType.Instance): F { return type === MemberType.Instance - ? function () { + ? 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); diff --git a/packages/core/text/index.android.ts b/packages/core/text/index.android.ts index e2ba647b4..f89081da9 100644 --- a/packages/core/text/index.android.ts +++ b/packages/core/text/index.android.ts @@ -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'; diff --git a/packages/core/text/index.d.ts b/packages/core/text/index.d.ts index 6aff21ac7..256b29998 100644 --- a/packages/core/text/index.d.ts +++ b/packages/core/text/index.d.ts @@ -3,7 +3,7 @@ /** * Defines the supported character encodings. */ -export module encoding { +export namespace encoding { /** * Denotes ISO-8859-1 character encoding. */ diff --git a/packages/core/text/index.ios.ts b/packages/core/text/index.ios.ts index dabd5cf92..d3a853452 100644 --- a/packages/core/text/index.ios.ts +++ b/packages/core/text/index.ios.ts @@ -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 diff --git a/packages/core/text/text-common.ts b/packages/core/text/text-common.ts index 2bd99a8c9..765502da9 100644 --- a/packages/core/text/text-common.ts +++ b/packages/core/text/text-common.ts @@ -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); diff --git a/packages/core/timer/index.android.ts b/packages/core/timer/index.android.ts index c6128fc62..06d42d958 100644 --- a/packages/core/timer/index.android.ts +++ b/packages/core/timer/index.android.ts @@ -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]; diff --git a/packages/core/timer/index.ios.ts b/packages/core/timer/index.ios.ts index bc1fa4999..457c81640 100644 --- a/packages/core/timer/index.ios.ts +++ b/packages/core/timer/index.ios.ts @@ -15,7 +15,7 @@ class TimerTargetImpl extends NSObject { private shouldRepeat: boolean; public static initWithCallback(callback: Function, id: number, shouldRepeat: boolean): TimerTargetImpl { - let handler = TimerTargetImpl.new(); + const handler = 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 = { + const pair: KeyValuePair = { 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((id)); + const pair = timeoutCallbacks.get((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); } diff --git a/packages/core/trace/index.ts b/packages/core/trace/index.ts index a72ef3f97..2c3bfa7f7 100644 --- a/packages/core/trace/index.ts +++ b/packages/core/trace/index.ts @@ -22,8 +22,8 @@ export interface TraceErrorHandler { let enabled = false; let _categories = {}; -let _writers: Array = []; -let _eventListeners: Array = []; +const _writers: Array = []; +const _eventListeners: Array = []; 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; diff --git a/packages/core/ui/action-bar/action-bar-common.ts b/packages/core/ui/action-bar/action-bar-common.ts index 8d0c84a68..84fb55753 100644 --- a/packages/core/ui/action-bar/action-bar-common.ts +++ b/packages/core/ui/action-bar/action-bar-common.ts @@ -365,7 +365,7 @@ export function traceMissingIcon(icon: string) { function convertToContentInset(this: void, value: string | Length): [CssProperty, any][] { if (typeof value === 'string' && value !== 'auto') { - let insets = value.split(/[ ,]+/); + const insets = value.split(/[ ,]+/); return [ [androidContentInsetLeftProperty, Length.parse(insets[0])], diff --git a/packages/core/ui/action-bar/index.android.ts b/packages/core/ui/action-bar/index.android.ts index a5e57ccb5..3fe45f003 100644 --- a/packages/core/ui/action-bar/index.android.ts +++ b/packages/core/ui/action-bar/index.android.ts @@ -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 ((items[i])._getItemId() === itemId) { menuItem = 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 = items[i]; - let menuItem = menu.add(android.view.Menu.NONE, item._getItemId(), android.view.Menu.NONE, item.text + ''); + const item = 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); } diff --git a/packages/core/ui/action-bar/index.ios.ts b/packages/core/ui/action-bar/index.ios.ts index 66da39270..831710e6e 100644 --- a/packages/core/ui/action-bar/index.ios.ts +++ b/packages/core/ui/action-bar/index.ios.ts @@ -40,14 +40,14 @@ class TapBarItemHandlerImpl extends NSObject { private _owner: WeakRef; public static initWithOwner(owner: WeakRef): TapBarItemHandlerImpl { - let handler = TapBarItemHandlerImpl.new(); + const handler = 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 = (page.ios).navigationItem; + const navigationItem: UINavigationItem = (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; } } diff --git a/packages/core/ui/activity-indicator/index.ios.ts b/packages/core/ui/activity-indicator/index.ios.ts index cc93d4eef..bf40f9a91 100644 --- a/packages/core/ui/activity-indicator/index.ios.ts +++ b/packages/core/ui/activity-indicator/index.ios.ts @@ -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 { diff --git a/packages/core/ui/animation/animation-common.ts b/packages/core/ui/animation/animation-common.ts index f993e2e5b..ae8b08e27 100644 --- a/packages/core/ui/animation/animation-common.ts +++ b/packages/core/ui/animation/animation-common.ts @@ -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; diff --git a/packages/core/ui/animation/animation-interfaces.ts b/packages/core/ui/animation/animation-interfaces.ts index 59a80387c..e4e7a7bc9 100644 --- a/packages/core/ui/animation/animation-interfaces.ts +++ b/packages/core/ui/animation/animation-interfaces.ts @@ -18,7 +18,10 @@ export type TransformFunctionsInfo = { scale: Pair; }; -export type AnimationPromise = Promise & Cancelable; +export interface AnimationPromise extends Promise, Cancelable { + then(...args):AnimationPromise + catch(...args):AnimationPromise +}; export interface Pair { x: number; diff --git a/packages/core/ui/animation/index.android.ts b/packages/core/ui/animation/index.android.ts index 699fb3f5b..73a5ec2cf 100644 --- a/packages/core/ui/animation/index.android.ts +++ b/packages/core/ui/animation/index.android.ts @@ -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; private _valueSource: 'animation' | 'keyframe'; private _target: View; - private _resetOnFinish: boolean = true; + private _resetOnFinish = true; constructor(animationDefinitions: Array, 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((propertyAnimation.target.backgroundColor).argb) : java.lang.Integer.valueOf(-1); nativeArray[1] = java.lang.Integer.valueOf((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 = (animator.getAnimatedValue()).intValue(); + const argb = (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) { diff --git a/packages/core/ui/animation/index.ios.ts b/packages/core/ui/animation/index.ios.ts index 5c3ca9fd8..3873bd990 100644 --- a/packages/core/ui/animation/index.ios.ts +++ b/packages/core/ui/animation/index.ios.ts @@ -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.new(); + const delegate = 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; (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 = curve; + const animationCurve = 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, index: number, playSequentially: boolean, args: AnimationInfo, animation: PropertyAnimation, valueSource: 'animation' | 'keyframe', finishedCallback: (cancelled?: boolean) => void) { - let nativeView = animation.target.nativeViewProtected; + const nativeView = 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().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, index: number, playSequentially: boolean, args: AnimationInfo, animation: PropertyAnimationInfo, valueSource: 'animation' | 'keyframe', finishedCallback: (cancelled?: boolean) => void) { - let nativeView = animation.target.nativeViewProtected; + const nativeView = 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): Array { - let result = new Array(); + const result = new Array(); 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: {}, diff --git a/packages/core/ui/animation/keyframe-animation.ts b/packages/core/ui/animation/keyframe-animation.ts index c18ac5f29..638cef895 100644 --- a/packages/core/ui/animation/keyframe-animation.ts +++ b/packages/core/ui/animation/keyframe-animation.ts @@ -58,8 +58,8 @@ interface Keyframe { export class KeyframeAnimation { public animations: Array; - 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(); + const animations = new Array(); 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, 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((resolve) => { + const animationFinishedPromise = new Promise((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]; (animationDef).target = view; animation = new Animation([animationDef]); this._nativeAnimations.push(animation); diff --git a/packages/core/ui/bottom-navigation/index.android.ts b/packages/core/ui/bottom-navigation/index.android.ts index 3334d36a2..6485a847d 100644 --- a/packages/core/ui/bottom-navigation/index.android.ts +++ b/packages/core/ui/bottom-navigation/index.android.ts @@ -103,9 +103,9 @@ function initializeNativeClasses() { this.owner.nativeViewProtected.setBackgroundDrawable(bitmapDrawable); this.backgroundBitmap = null; - let thisView = this.getView(); + const thisView = this.getView(); if (thisView) { - let thisViewParent = thisView.getParent(); + const thisViewParent = thisView.getParent(); if (thisViewParent && thisViewParent instanceof android.view.ViewGroup) { thisViewParent.removeView(thisView); } @@ -250,7 +250,7 @@ function iterateIndexRange(index: number, eps: number, lastIndex: number, callba @CSSType('BottomNavigation') export class BottomNavigation extends TabNavigationBase { private _contentView: org.nativescript.widgets.ContentLayout; - private _contentViewId: number = -1; + private _contentViewId = -1; private _bottomNavigationBar: org.nativescript.widgets.BottomNavigationBar; private _currentFragment: androidx.fragment.app.Fragment; private _currentTransaction: androidx.fragment.app.FragmentTransaction; @@ -347,8 +347,8 @@ export class BottomNavigation extends TabNavigationBase { const lastIndex = this.items.length - 1; const offsideItems = 0; - let toUnload = []; - let toLoad = []; + const toUnload = []; + const toLoad = []; iterateIndexRange(newIndex, offsideItems, lastIndex, (i) => toLoad.push(i)); @@ -610,7 +610,7 @@ export class BottomNavigation extends TabNavigationBase { tabItemSpec.backgroundColor = backgroundColor ? backgroundColor.android : this.getTabBarBackgroundArgbColor(); // COLOR - let itemColor = this.selectedIndex === tabStripItem._index ? this._selectedItemColor : this._unSelectedItemColor; + const itemColor = this.selectedIndex === tabStripItem._index ? this._selectedItemColor : this._unSelectedItemColor; const color = itemColor || titleLabel.style.color; tabItemSpec.color = color && color.android; @@ -669,7 +669,7 @@ export class BottomNavigation extends TabNavigationBase { image = this.getFixedSizeIcon(image); } - let imageDrawable = new android.graphics.drawable.BitmapDrawable(application.android.context.getResources(), image); + const imageDrawable = new android.graphics.drawable.BitmapDrawable(application.android.context.getResources(), image); return { drawable: imageDrawable, @@ -681,7 +681,7 @@ export class BottomNavigation extends TabNavigationBase { } private getIconInfo(tabStripItem: TabStripItem, color?: Color): IconInfo { - let originalIcon = this.getOriginalIcon(tabStripItem, color); + const originalIcon = this.getOriginalIcon(tabStripItem, color); return this.getDrawableInfo(originalIcon); } @@ -841,7 +841,7 @@ export class BottomNavigation extends TabNavigationBase { } public setTabBarTextTransform(value: TextTransform): void { - let items = this.tabStrip && this.tabStrip.items; + const items = this.tabStrip && this.tabStrip.items; if (items) { items.forEach((tabStripItem) => { if (tabStripItem.label && tabStripItem.nativeViewProtected) { diff --git a/packages/core/ui/bottom-navigation/index.ios.ts b/packages/core/ui/bottom-navigation/index.ios.ts index 43ddc14bc..6f6b30138 100644 --- a/packages/core/ui/bottom-navigation/index.ios.ts +++ b/packages/core/ui/bottom-navigation/index.ios.ts @@ -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; diff --git a/packages/core/ui/builder/binding-builder.ts b/packages/core/ui/builder/binding-builder.ts index e10e37bb9..404df5682 100644 --- a/packages/core/ui/builder/binding-builder.ts +++ b/packages/core/ui/builder/binding-builder.ts @@ -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]; } diff --git a/packages/core/ui/builder/component-builder/index.ts b/packages/core/ui/builder/component-builder/index.ts index 27e0c930d..330c527ed 100644 --- a/packages/core/ui/builder/component-builder/index.ts +++ b/packages/core/ui/builder/component-builder/index.ts @@ -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; } diff --git a/packages/core/ui/builder/index.ts b/packages/core/ui/builder/index.ts index 769267bf6..e1b077017 100644 --- a/packages/core/ui/builder/index.ts +++ b/packages/core/ui/builder/index.ts @@ -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(); + const templates = new Array(); for (let i = 0; i < this._childParsers.length; i++) { templates.push({ key: this._childParsers[i]['key'], diff --git a/packages/core/ui/builder/module-name-sanitizer.ts b/packages/core/ui/builder/module-name-sanitizer.ts index 93f01b061..ba34dd000 100644 --- a/packages/core/ui/builder/module-name-sanitizer.ts +++ b/packages/core/ui/builder/module-name-sanitizer.ts @@ -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('~/')) { diff --git a/packages/core/ui/button/index.ios.ts b/packages/core/ui/button/index.ios.ts index f57842155..0ffaa3485 100644 --- a/packages/core/ui/button/index.ios.ts +++ b/packages/core/ui/button/index.ios.ts @@ -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