MOBILE-3303 lint: Fix linting errors in first implementation

main
Noel De Martin 2020-10-07 10:11:20 +02:00 committed by Dani Palou
parent e1c37437a2
commit 1617c30cc3
12 changed files with 165 additions and 133 deletions

View File

@ -71,9 +71,26 @@ module.exports = {
},
],
'@typescript-eslint/member-ordering': 'error',
'@typescript-eslint/naming-convention': 'error',
'@typescript-eslint/naming-convention': [
'error',
{
selector: 'property',
modifiers: ['readonly'],
format: ['UPPER_CASE'],
},
{
selector: 'property',
format: ['camelCase'],
},
],
'@typescript-eslint/no-empty-function': 'error',
'@typescript-eslint/no-empty-interface': 'error',
'@typescript-eslint/no-empty-interface': 'off',
'@typescript-eslint/no-explicit-any': [
'warn',
{
fixToUnknown: true,
},
],
'@typescript-eslint/no-inferrable-types': [
'error',
{
@ -113,15 +130,8 @@ module.exports = {
],
1,
],
'one-var': ['error', 'never'],
'arrow-body-style': ['error', 'as-needed'],
'comma-dangle': ['error', 'always-multiline'],
'capitalized-comments': [
'error',
'always',
{
ignoreConsecutiveComments: true,
},
],
'constructor-super': 'error',
'curly': 'error',
'default-case': 'error',
@ -171,6 +181,7 @@ module.exports = {
'no-underscore-dangle': 'error',
'no-unused-labels': 'error',
'no-var': 'error',
'one-var': ['error', 'never'],
'padding-line-between-statements': [
'error',
{
@ -181,9 +192,13 @@ module.exports = {
],
'prefer-arrow/prefer-arrow-functions': [
'error',
{ allowStandaloneDeclarations: true },
{
singleReturnOnly: true,
allowStandaloneDeclarations: true,
},
],
'prefer-const': 'error',
'prefer-spread': 'off',
'quote-props': [
'error',
'consistent-as-needed',

View File

@ -22,7 +22,7 @@ class CoreSingleton {}
/**
* Token that can be used to resolve instances from the injector.
*/
export type CoreInjectionToken<Service> = Type<Service> | Type<any> | string;
export type CoreInjectionToken<Service> = Type<Service> | Type<unknown> | string;
/**
* Singleton class created using the factory.
@ -55,20 +55,20 @@ export class CoreSingletonsFactory {
* provider was defined using a class or the string used in the `provide` key if it was defined using an object.
*/
makeSingleton<Service>(injectionToken: CoreInjectionToken<Service>): CoreSingletonClass<Service> {
// tslint:disable: no-this-assignment
// eslint-disable-next-line @typescript-eslint/no-this-alias
const factory = this;
return class {
private static _instance: Service;
private static serviceInstance: Service;
static get instance(): Service {
// Initialize instances lazily.
if (!this._instance) {
this._instance = factory.injector.get(injectionToken);
if (!this.serviceInstance) {
this.serviceInstance = factory.injector.get(injectionToken);
}
return this._instance;
return this.serviceInstance;
}
};

View File

@ -28,79 +28,81 @@ export const enum ContextLevel {
* Static class to contain all the core constants.
*/
export class CoreConstants {
static SECONDS_YEAR = 31536000;
static SECONDS_WEEK = 604800;
static SECONDS_DAY = 86400;
static SECONDS_HOUR = 3600;
static SECONDS_MINUTE = 60;
static WIFI_DOWNLOAD_THRESHOLD = 104857600; // 100MB.
static DOWNLOAD_THRESHOLD = 10485760; // 10MB.
static MINIMUM_FREE_SPACE = 10485760; // 10MB.
static IOS_FREE_SPACE_THRESHOLD = 524288000; // 500MB.
static DONT_SHOW_ERROR = 'CoreDontShowError';
static NO_SITE_ID = 'NoSite';
/* eslint-disable max-len */
static readonly SECONDS_YEAR = 31536000;
static readonly SECONDS_WEEK = 604800;
static readonly SECONDS_DAY = 86400;
static readonly SECONDS_HOUR = 3600;
static readonly SECONDS_MINUTE = 60;
static readonly WIFI_DOWNLOAD_THRESHOLD = 104857600; // 100MB.
static readonly DOWNLOAD_THRESHOLD = 10485760; // 10MB.
static readonly MINIMUM_FREE_SPACE = 10485760; // 10MB.
static readonly IOS_FREE_SPACE_THRESHOLD = 524288000; // 500MB.
static readonly DONT_SHOW_ERROR = 'CoreDontShowError';
static readonly NO_SITE_ID = 'NoSite';
// Settings constants.
static SETTINGS_RICH_TEXT_EDITOR = 'CoreSettingsRichTextEditor';
static SETTINGS_NOTIFICATION_SOUND = 'CoreSettingsNotificationSound';
static SETTINGS_SYNC_ONLY_ON_WIFI = 'CoreSettingsSyncOnlyOnWifi';
static SETTINGS_DEBUG_DISPLAY = 'CoreSettingsDebugDisplay';
static SETTINGS_REPORT_IN_BACKGROUND = 'CoreSettingsReportInBackground'; // @deprecated since 3.5.0
static SETTINGS_SEND_ON_ENTER = 'CoreSettingsSendOnEnter';
static SETTINGS_FONT_SIZE = 'CoreSettingsFontSize';
static SETTINGS_COLOR_SCHEME = 'CoreSettingsColorScheme';
static SETTINGS_ANALYTICS_ENABLED = 'CoreSettingsAnalyticsEnabled';
static readonly SETTINGS_RICH_TEXT_EDITOR = 'CoreSettingsRichTextEditor';
static readonly SETTINGS_NOTIFICATION_SOUND = 'CoreSettingsNotificationSound';
static readonly SETTINGS_SYNC_ONLY_ON_WIFI = 'CoreSettingsSyncOnlyOnWifi';
static readonly SETTINGS_DEBUG_DISPLAY = 'CoreSettingsDebugDisplay';
static readonly SETTINGS_REPORT_IN_BACKGROUND = 'CoreSettingsReportInBackground'; // @deprecated since 3.5.0
static readonly SETTINGS_SEND_ON_ENTER = 'CoreSettingsSendOnEnter';
static readonly SETTINGS_FONT_SIZE = 'CoreSettingsFontSize';
static readonly SETTINGS_COLOR_SCHEME = 'CoreSettingsColorScheme';
static readonly SETTINGS_ANALYTICS_ENABLED = 'CoreSettingsAnalyticsEnabled';
// WS constants.
static WS_TIMEOUT = 30000; // Timeout when not in WiFi.
static WS_TIMEOUT_WIFI = 30000; // Timeout when in WiFi.
static WS_PREFIX = 'local_mobile_';
static readonly WS_TIMEOUT = 30000; // Timeout when not in WiFi.
static readonly WS_TIMEOUT_WIFI = 30000; // Timeout when in WiFi.
static readonly WS_PREFIX = 'local_mobile_';
// Login constants.
static LOGIN_SSO_CODE = 2; // SSO in browser window is required.
static LOGIN_SSO_INAPP_CODE = 3; // SSO in embedded browser is required.
static LOGIN_LAUNCH_DATA = 'CoreLoginLaunchData';
static readonly LOGIN_SSO_CODE = 2; // SSO in browser window is required.
static readonly LOGIN_SSO_INAPP_CODE = 3; // SSO in embedded browser is required.
static readonly LOGIN_LAUNCH_DATA = 'CoreLoginLaunchData';
// Download status constants.
static DOWNLOADED = 'downloaded';
static DOWNLOADING = 'downloading';
static NOT_DOWNLOADED = 'notdownloaded';
static OUTDATED = 'outdated';
static NOT_DOWNLOADABLE = 'notdownloadable';
static readonly DOWNLOADED = 'downloaded';
static readonly DOWNLOADING = 'downloading';
static readonly NOT_DOWNLOADED = 'notdownloaded';
static readonly OUTDATED = 'outdated';
static readonly NOT_DOWNLOADABLE = 'notdownloadable';
// Constants from Moodle's resourcelib.
static RESOURCELIB_DISPLAY_AUTO = 0; // Try the best way.
static RESOURCELIB_DISPLAY_EMBED = 1; // Display using object tag.
static RESOURCELIB_DISPLAY_FRAME = 2; // Display inside frame.
static RESOURCELIB_DISPLAY_NEW = 3; // Display normal link in new window.
static RESOURCELIB_DISPLAY_DOWNLOAD = 4; // Force download of file instead of display.
static RESOURCELIB_DISPLAY_OPEN = 5; // Open directly.
static RESOURCELIB_DISPLAY_POPUP = 6; // Open in "emulated" pop-up without navigation.
static readonly RESOURCELIB_DISPLAY_AUTO = 0; // Try the best way.
static readonly RESOURCELIB_DISPLAY_EMBED = 1; // Display using object tag.
static readonly RESOURCELIB_DISPLAY_FRAME = 2; // Display inside frame.
static readonly RESOURCELIB_DISPLAY_NEW = 3; // Display normal link in new window.
static readonly RESOURCELIB_DISPLAY_DOWNLOAD = 4; // Force download of file instead of display.
static readonly RESOURCELIB_DISPLAY_OPEN = 5; // Open directly.
static readonly RESOURCELIB_DISPLAY_POPUP = 6; // Open in "emulated" pop-up without navigation.
// Feature constants. Used to report features that are, or are not, supported by a module.
static FEATURE_GRADE_HAS_GRADE = 'grade_has_grade'; // True if module can provide a grade.
static FEATURE_GRADE_OUTCOMES = 'outcomes'; // True if module supports outcomes.
static FEATURE_ADVANCED_GRADING = 'grade_advanced_grading'; // True if module supports advanced grading methods.
static FEATURE_CONTROLS_GRADE_VISIBILITY = 'controlsgradevisbility'; // True if module controls grade visibility over gradebook.
static FEATURE_PLAGIARISM = 'plagiarism'; // True if module supports plagiarism plugins.
static FEATURE_COMPLETION_TRACKS_VIEWS = 'completion_tracks_views'; // True if module tracks whether somebody viewed it.
static FEATURE_COMPLETION_HAS_RULES = 'completion_has_rules'; // True if module has custom completion rules.
static FEATURE_NO_VIEW_LINK = 'viewlink'; // True if module has no 'view' page (like label).
static FEATURE_IDNUMBER = 'idnumber'; // True if module wants support for setting the ID number for grade calculation purposes.
static FEATURE_GROUPS = 'groups'; // True if module supports groups.
static FEATURE_GROUPINGS = 'groupings'; // True if module supports groupings.
static FEATURE_MOD_ARCHETYPE = 'mod_archetype'; // Type of module.
static FEATURE_MOD_INTRO = 'mod_intro'; // True if module supports intro editor.
static FEATURE_MODEDIT_DEFAULT_COMPLETION = 'modedit_default_completion'; // True if module has default completion.
static FEATURE_COMMENT = 'comment';
static FEATURE_RATE = 'rate';
static FEATURE_BACKUP_MOODLE2 = 'backup_moodle2'; // True if module supports backup/restore of moodle2 format.
static FEATURE_SHOW_DESCRIPTION = 'showdescription'; // True if module can show description on course main page.
static FEATURE_USES_QUESTIONS = 'usesquestions'; // True if module uses the question bank.
static readonly FEATURE_GRADE_HAS_GRADE = 'grade_has_grade'; // True if module can provide a grade.
static readonly FEATURE_GRADE_OUTCOMES = 'outcomes'; // True if module supports outcomes.
static readonly FEATURE_ADVANCED_GRADING = 'grade_advanced_grading'; // True if module supports advanced grading methods.
static readonly FEATURE_CONTROLS_GRADE_VISIBILITY = 'controlsgradevisbility'; // True if module controls grade visibility over gradebook.
static readonly FEATURE_PLAGIARISM = 'plagiarism'; // True if module supports plagiarism plugins.
static readonly FEATURE_COMPLETION_TRACKS_VIEWS = 'completion_tracks_views'; // True if module tracks whether somebody viewed it.
static readonly FEATURE_COMPLETION_HAS_RULES = 'completion_has_rules'; // True if module has custom completion rules.
static readonly FEATURE_NO_VIEW_LINK = 'viewlink'; // True if module has no 'view' page (like label).
static readonly FEATURE_IDNUMBER = 'idnumber'; // True if module wants support for setting the ID number for grade calculation purposes.
static readonly FEATURE_GROUPS = 'groups'; // True if module supports groups.
static readonly FEATURE_GROUPINGS = 'groupings'; // True if module supports groupings.
static readonly FEATURE_MOD_ARCHETYPE = 'mod_archetype'; // Type of module.
static readonly FEATURE_MOD_INTRO = 'mod_intro'; // True if module supports intro editor.
static readonly FEATURE_MODEDIT_DEFAULT_COMPLETION = 'modedit_default_completion'; // True if module has default completion.
static readonly FEATURE_COMMENT = 'comment';
static readonly FEATURE_RATE = 'rate';
static readonly FEATURE_BACKUP_MOODLE2 = 'backup_moodle2'; // True if module supports backup/restore of moodle2 format.
static readonly FEATURE_SHOW_DESCRIPTION = 'showdescription'; // True if module can show description on course main page.
static readonly FEATURE_USES_QUESTIONS = 'usesquestions'; // True if module uses the question bank.
// Pssobile archetypes for modules.
static MOD_ARCHETYPE_OTHER = 0; // Unspecified module archetype.
static MOD_ARCHETYPE_RESOURCE = 1; // Resource-like type module.
static MOD_ARCHETYPE_ASSIGNMENT = 2; // Assignment module archetype.
static MOD_ARCHETYPE_SYSTEM = 3; // System (not user-addable) module archetype.
// Possbile archetypes for modules.
static readonly MOD_ARCHETYPE_OTHER = 0; // Unspecified module archetype.
static readonly MOD_ARCHETYPE_RESOURCE = 1; // Resource-like type module.
static readonly MOD_ARCHETYPE_ASSIGNMENT = 2; // Assignment module archetype.
static readonly MOD_ARCHETYPE_SYSTEM = 3; // System (not user-addable) module archetype.
}

View File

@ -69,6 +69,6 @@ import { Zip } from '@ionic-native/zip/ngx';
StatusBar,
WebIntent,
Zip,
]
],
})
export class CoreEmulatorModule { }

View File

@ -17,7 +17,6 @@ import { Router } from '@angular/router';
import { CoreApp } from '@services/app';
import { CoreInit } from '@services/init';
import { CoreConstants } from '@core/constants';
import { SplashScreen } from '@singletons/core.singletons';
/**
@ -42,7 +41,7 @@ export class CoreLoginInitPage implements OnInit {
const redirectData = CoreApp.instance.getRedirect();
if (redirectData.siteId) {
// Unset redirect data.
CoreApp.instance.storeRedirect('', '', '');
CoreApp.instance.storeRedirect('', '', {});
// Only accept the redirect if it was stored less than 20 seconds ago.
if (Date.now() - redirectData.timemodified < 20000) {

View File

@ -28,6 +28,7 @@ export class CoreLoginSitePage implements OnInit {
* Initialize the component.
*/
ngOnInit(): void {
//
}
}
}

View File

@ -25,19 +25,22 @@ import { CoreLogger } from '@singletons/logger';
/**
* Factory to provide some global functionalities, like access to the global app database.
*
* @description
* Each service or component should be responsible of creating their own database tables. Example:
*
* ```ts
* constructor(appProvider: CoreAppProvider) {
* this.appDB = appProvider.getDB();
* this.appDB.createTableFromSchema(this.tableSchema);
* }
* ```
*/
@Injectable()
export class CoreAppProvider {
protected DBNAME = 'MoodleMobile';
protected db: SQLiteDB;
protected logger;
protected logger: CoreLogger;
protected ssoAuthenticationPromise: Promise<any>;
protected isKeyboardShown = false;
protected _isKeyboardOpening = false;
@ -567,18 +570,18 @@ export class CoreAppProvider {
*
* @return Object with siteid, state, params and timemodified.
*/
getRedirect(): CoreRedirectData {
getRedirect<Params extends Record<string, unknown> = Record<string, unknown>>(): CoreRedirectData<Params> {
if (localStorage && localStorage.getItem) {
try {
const data: CoreRedirectData = {
const paramsJson = localStorage.getItem('CoreRedirectParams');
const data: CoreRedirectData<Params> = {
siteId: localStorage.getItem('CoreRedirectSiteId'),
page: localStorage.getItem('CoreRedirectState'),
params: localStorage.getItem('CoreRedirectParams'),
timemodified: parseInt(localStorage.getItem('CoreRedirectTime'), 10)
timemodified: parseInt(localStorage.getItem('CoreRedirectTime'), 10),
};
if (data.params) {
data.params = JSON.parse(data.params);
if (paramsJson) {
data.params = JSON.parse(paramsJson);
}
return data;
@ -597,7 +600,7 @@ export class CoreAppProvider {
* @param page Page to go.
* @param params Page params.
*/
storeRedirect(siteId: string, page: string, params: any): void {
storeRedirect(siteId: string, page: string, params: Record<string, unknown>): void {
if (localStorage && localStorage.setItem) {
try {
localStorage.setItem('CoreRedirectSiteId', siteId);
@ -704,7 +707,7 @@ export class CoreApp extends makeSingleton(CoreAppProvider) {}
/**
* Data stored for a redirect to another page/site.
*/
export type CoreRedirectData = {
export type CoreRedirectData<Params extends Record<string, unknown>> = {
/**
* ID of the site to load.
*/
@ -718,7 +721,7 @@ export type CoreRedirectData = {
/**
* Params to pass to the page.
*/
params?: any;
params?: Params;
/**
* Timestamp when this redirect was last modified.

View File

@ -50,8 +50,8 @@ export type CoreInitHandler = {
*/
@Injectable()
export class CoreInitDelegate {
static DEFAULT_PRIORITY = 100; // Default priority for init processes.
static MAX_RECOMMENDED_PRIORITY = 600;
static readonly DEFAULT_PRIORITY = 100; // Default priority for init processes.
static readonly MAX_RECOMMENDED_PRIORITY = 600;
protected initProcesses = {};
protected logger: CoreLogger;
@ -77,16 +77,12 @@ export class CoreInitDelegate {
for (const name in this.initProcesses) {
ordered.push(this.initProcesses[name]);
}
ordered.sort((a, b) => {
return b.priority - a.priority;
});
ordered.sort((a, b) => b.priority - a.priority);
ordered = ordered.map((data: CoreInitHandler) => {
return {
ordered = ordered.map((data: CoreInitHandler) => ({
func: this.prepareProcess.bind(this, data),
blocking: !!data.blocking,
};
});
}));
// Execute all the processes in order to solve dependencies.
CoreUtils.instance.executeOrderedPromises(ordered).finally(this.readiness.resolve);
@ -115,20 +111,14 @@ export class CoreInitDelegate {
* @param data The data of the process.
* @return Promise of the process.
*/
protected prepareProcess(data: CoreInitHandler): Promise<any> {
let promise;
protected async prepareProcess(data: CoreInitHandler): Promise<void> {
this.logger.debug(`Executing init process '${data.name}'`);
try {
promise = data.load();
await data.load();
} catch (e) {
this.logger.error('Error while calling the init process \'' + data.name + '\'. ' + e);
return;
}
return promise;
}
/**
@ -136,13 +126,13 @@ export class CoreInitDelegate {
*
* @return Resolved when the app is initialised. Never rejected.
*/
ready(): Promise<any> {
async ready(): Promise<void> {
if (typeof this.readiness == 'undefined') {
// Prevent race conditions if this is called before executeInitProcesses.
this.initReadiness();
}
return this.readiness.promise;
await this.readiness.promise;
}
/**

View File

@ -85,7 +85,7 @@ export class CoreUtilsProvider {
* @param promises Promises.
* @return Promise resolved if all promises are resolved and rejected if at least 1 promise fails.
*/
allPromises(promises: Promise<any>[]): Promise<any> {
allPromises(promises: Promise<unknown>[]): Promise<void> {
if (!promises || !promises.length) {
return Promise.resolve();
}
@ -366,7 +366,7 @@ export class CoreUtilsProvider {
* - blocking: Boolean. If promise should block the following.
* @return Promise resolved when all promises are resolved.
*/
executeOrderedPromises(orderedPromisesData: any[]): Promise<any> {
executeOrderedPromises(orderedPromisesData: OrderedPromiseData[]): Promise<void> {
const promises = [];
let dependency = Promise.resolve();
@ -377,17 +377,13 @@ export class CoreUtilsProvider {
// Add the process to the dependency stack.
promise = dependency.finally(() => {
let prom;
try {
prom = data.func.apply(data.context, data.params || []);
return data.function();
} catch (e) {
this.logger.error(e.message);
return;
}
return prom;
});
promises.push(promise);
@ -1582,5 +1578,20 @@ export type PromiseDefer<T> = {
*
* @param reason The reject param.
*/
reject?: (reason?: any) => void;
reject?: (reason?: unknown) => void;
};
/**
* Data for each entry of executeOrderedPromises.
*/
export type OrderedPromiseData = {
/**
* Function to execute.
*/
function: () => Promise<unknown>;
/**
* Whether the promise should block the following one.
*/
blocking?: boolean;
};

View File

@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
import * as moment from 'moment';
import moment from 'moment';
import { environment } from '@/environments/environment';
/**
@ -42,27 +42,33 @@ export class CoreLogger {
static getInstance(className: string): CoreLogger {
// Disable log on production.
if (environment.production) {
/* tslint:next-line no-console */
// eslint-disable-next-line no-console
console.warn('Log is disabled in production app');
// eslint-disable-next-line @typescript-eslint/no-empty-function
const muted = () => {};
return {
log: () => {},
info: () => {},
warn: () => {},
debug: () => {},
error: () => {},
log: muted,
info: muted,
warn: muted,
debug: muted,
error: muted,
};
}
className = className || '';
/* tslint:disable no-console */
return {
// eslint-disable-next-line no-console
log: CoreLogger.prepareLogFn(console.log.bind(console), className),
// eslint-disable-next-line no-console
info: CoreLogger.prepareLogFn(console.info.bind(console), className),
// eslint-disable-next-line no-console
warn: CoreLogger.prepareLogFn(console.warn.bind(console), className),
// eslint-disable-next-line no-console
debug: CoreLogger.prepareLogFn(console.debug.bind(console), className),
// eslint-disable-next-line no-console
error: CoreLogger.prepareLogFn(console.error.bind(console), className),
};
}
@ -87,4 +93,4 @@ export class CoreLogger {
/**
* Log function type.
*/
type LogFunction = (...data: any[]) => void;
type LogFunction = (...data: unknown[]) => void;

View File

@ -29,6 +29,7 @@
"src/**/*.d.ts"
],
"exclude": [
"src/**/*.test.ts"
"src/**/*.test.ts",
"src/tests/**"
]
}

View File

@ -17,6 +17,10 @@
"es2018",
"dom"
],
"types": [
"jest",
"node"
],
"paths": {
"@/*": ["*"],
"@addon/*": ["app/addon/*"],