From af4e07df36632b6cdf8b8bd09e9902d01857ccaf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Thu, 11 Jul 2024 16:39:55 +0200 Subject: [PATCH 01/26] MOBILE-4616 assign: Move assign constants to a file --- src/addons/mod/assign/assign-lazy.module.ts | 2 +- src/addons/mod/assign/assign.module.ts | 10 +-- .../mod/assign/classes/submissions-source.ts | 5 +- .../feedback-plugin/feedback-plugin.ts | 4 +- .../mod/assign/components/index/index.ts | 32 +++++---- .../submission-plugin/submission-plugin.ts | 4 +- .../components/submission/submission.ts | 34 ++++++---- src/addons/mod/assign/constants.ts | 17 +++++ .../feedback/comments/component/comments.ts | 5 +- .../feedback/editpdf/component/editpdf.ts | 5 +- .../assign/feedback/file/component/file.ts | 5 +- src/addons/mod/assign/pages/edit/edit.ts | 19 ++++-- .../pages/submission-list/submission-list.ts | 8 +-- .../mod/assign/services/assign-helper.ts | 6 +- src/addons/mod/assign/services/assign-sync.ts | 13 ++-- src/addons/mod/assign/services/assign.ts | 67 +++++++++---------- .../mod/assign/services/handlers/module.ts | 5 +- .../mod/assign/services/handlers/prefetch.ts | 4 +- .../assign/submission/file/component/file.ts | 5 +- .../submission/file/services/handler.ts | 12 ++-- .../onlinetext/component/onlinetext.ts | 5 +- 21 files changed, 150 insertions(+), 117 deletions(-) diff --git a/src/addons/mod/assign/assign-lazy.module.ts b/src/addons/mod/assign/assign-lazy.module.ts index c1ce4dfba..de02be0c6 100644 --- a/src/addons/mod/assign/assign-lazy.module.ts +++ b/src/addons/mod/assign/assign-lazy.module.ts @@ -82,4 +82,4 @@ const routes: Routes = [ AddonModAssignEditPage, ], }) -export class AddonModAssignLazyModule {} +export default class AddonModAssignLazyModule {} diff --git a/src/addons/mod/assign/assign.module.ts b/src/addons/mod/assign/assign.module.ts index 9203223a9..abd3eead7 100644 --- a/src/addons/mod/assign/assign.module.ts +++ b/src/addons/mod/assign/assign.module.ts @@ -23,15 +23,15 @@ import { CorePushNotificationsDelegate } from '@features/pushnotifications/servi import { CoreCronDelegate } from '@services/cron'; import { CORE_SITE_SCHEMAS } from '@services/sites'; import { AddonModAssignFeedbackModule } from './feedback/feedback.module'; -import { AddonModAssignProvider } from './services/assign'; import { OFFLINE_SITE_SCHEMA } from './services/database/assign'; import { AddonModAssignIndexLinkHandler } from './services/handlers/index-link'; import { AddonModAssignListLinkHandler } from './services/handlers/list-link'; -import { AddonModAssignModuleHandler, AddonModAssignModuleHandlerService } from './services/handlers/module'; +import { AddonModAssignModuleHandler } from './services/handlers/module'; import { AddonModAssignPrefetchHandler } from './services/handlers/prefetch'; import { AddonModAssignPushClickHandler } from './services/handlers/push-click'; import { AddonModAssignSyncCronHandler } from './services/handlers/sync-cron'; import { AddonModAssignSubmissionModule } from './submission/submission.module'; +import { ADDON_MOD_ASSIGN_COMPONENT, ADDON_MOD_ASSIGN_PAGE_NAME } from './constants'; /** * Get mod assign services. @@ -69,8 +69,8 @@ export async function getModAssignComponentModules(): Promise { const routes: Routes = [ { - path: AddonModAssignModuleHandlerService.PAGE_NAME, - loadChildren: () => import('./assign-lazy.module').then(m => m.AddonModAssignLazyModule), + path: ADDON_MOD_ASSIGN_PAGE_NAME, + loadChildren: () => import('./assign-lazy.module'), }, ]; @@ -97,7 +97,7 @@ const routes: Routes = [ CoreCronDelegate.register(AddonModAssignSyncCronHandler.instance); CorePushNotificationsDelegate.registerClickHandler(AddonModAssignPushClickHandler.instance); - CoreCourseHelper.registerModuleReminderClick(AddonModAssignProvider.COMPONENT); + CoreCourseHelper.registerModuleReminderClick(ADDON_MOD_ASSIGN_COMPONENT); }, }, ], diff --git a/src/addons/mod/assign/classes/submissions-source.ts b/src/addons/mod/assign/classes/submissions-source.ts index 1b7df3213..d630dbc32 100644 --- a/src/addons/mod/assign/classes/submissions-source.ts +++ b/src/addons/mod/assign/classes/submissions-source.ts @@ -29,7 +29,8 @@ import { } from '../services/assign'; import { AddonModAssignHelper, AddonModAssignSubmissionFormatted } from '../services/assign-helper'; import { AddonModAssignOffline } from '../services/assign-offline'; -import { AddonModAssignSync, AddonModAssignSyncProvider } from '../services/assign-sync'; +import { AddonModAssignSync } from '../services/assign-sync'; +import { ADDON_MOD_ASSIGN_MANUAL_SYNCED } from '../constants'; /** * Provides a collection of assignment submissions. @@ -116,7 +117,7 @@ export class AddonModAssignSubmissionsSource extends CoreRoutedItemsManagerSourc if (result && result.updated) { CoreEvents.trigger( - AddonModAssignSyncProvider.MANUAL_SYNCED, + ADDON_MOD_ASSIGN_MANUAL_SYNCED, { assignId: this.assign.id, warnings: result.warnings, diff --git a/src/addons/mod/assign/components/feedback-plugin/feedback-plugin.ts b/src/addons/mod/assign/components/feedback-plugin/feedback-plugin.ts index 45d6cdac8..136e991b5 100644 --- a/src/addons/mod/assign/components/feedback-plugin/feedback-plugin.ts +++ b/src/addons/mod/assign/components/feedback-plugin/feedback-plugin.ts @@ -20,11 +20,11 @@ import { AddonModAssignAssign, AddonModAssignSubmission, AddonModAssignPlugin, - AddonModAssignProvider, AddonModAssign, } from '../../services/assign'; import { AddonModAssignHelper, AddonModAssignPluginConfig } from '../../services/assign-helper'; import { AddonModAssignFeedbackDelegate } from '../../services/feedback-delegate'; +import { ADDON_MOD_ASSIGN_COMPONENT } from '../../constants'; /** * Component that displays an assignment feedback plugin. @@ -48,7 +48,7 @@ export class AddonModAssignFeedbackPluginComponent implements OnInit { data?: AddonModAssignFeedbackPluginData; // Data to pass to the component. // Data to render the plugin if it isn't supported. - component = AddonModAssignProvider.COMPONENT; + component = ADDON_MOD_ASSIGN_COMPONENT; text = ''; files: CoreWSFile[] = []; notSupported = false; diff --git a/src/addons/mod/assign/components/index/index.ts b/src/addons/mod/assign/components/index/index.ts index 45cd4195f..e343bbaff 100644 --- a/src/addons/mod/assign/components/index/index.ts +++ b/src/addons/mod/assign/components/index/index.ts @@ -32,18 +32,26 @@ import { AddonModAssignListFilterName } from '../../classes/submissions-source'; import { AddonModAssign, AddonModAssignAssign, - AddonModAssignProvider, AddonModAssignSubmissionGradingSummary, } from '../../services/assign'; import { AddonModAssignOffline } from '../../services/assign-offline'; import { AddonModAssignAutoSyncData, AddonModAssignSync, - AddonModAssignSyncProvider, AddonModAssignSyncResult, } from '../../services/assign-sync'; -import { AddonModAssignModuleHandlerService } from '../../services/handlers/module'; import { AddonModAssignSubmissionComponent } from '../submission/submission'; +import { + ADDON_MOD_ASSIGN_AUTO_SYNCED, + ADDON_MOD_ASSIGN_COMPONENT, + ADDON_MOD_ASSIGN_GRADED_EVENT, + ADDON_MOD_ASSIGN_PAGE_NAME, + ADDON_MOD_ASSIGN_STARTED_EVENT, + ADDON_MOD_ASSIGN_SUBMISSION_SAVED_EVENT, + ADDON_MOD_ASSIGN_SUBMITTED_FOR_GRADING_EVENT, + ADDON_MOD_ASSIGN_WARN_GROUPS_OPTIONAL, + ADDON_MOD_ASSIGN_WARN_GROUPS_REQUIRED, +} from '../../constants'; /** * Component that displays an assignment. @@ -56,7 +64,7 @@ export class AddonModAssignIndexComponent extends CoreCourseModuleMainActivityCo @ViewChild(AddonModAssignSubmissionComponent) submissionComponent?: AddonModAssignSubmissionComponent; - component = AddonModAssignProvider.COMPONENT; + component = ADDON_MOD_ASSIGN_COMPONENT; pluginName = 'assign'; assign?: AddonModAssignAssign; // The assign object. @@ -82,7 +90,7 @@ export class AddonModAssignIndexComponent extends CoreCourseModuleMainActivityCo protected currentUserId!: number; // Current user ID. protected currentSite!: CoreSite; // Current site. - protected syncEventName = AddonModAssignSyncProvider.AUTO_SYNCED; + protected syncEventName = ADDON_MOD_ASSIGN_AUTO_SYNCED; // Observers. protected savedObserver?: CoreEventObserver; @@ -108,7 +116,7 @@ export class AddonModAssignIndexComponent extends CoreCourseModuleMainActivityCo // Listen to events. this.savedObserver = CoreEvents.on( - AddonModAssignProvider.SUBMISSION_SAVED_EVENT, + ADDON_MOD_ASSIGN_SUBMISSION_SAVED_EVENT, (data) => { if (this.assign && data.assignmentId == this.assign.id && data.userId == this.currentUserId) { // Assignment submission saved, refresh data. @@ -119,7 +127,7 @@ export class AddonModAssignIndexComponent extends CoreCourseModuleMainActivityCo ); this.submittedObserver = CoreEvents.on( - AddonModAssignProvider.SUBMITTED_FOR_GRADING_EVENT, + ADDON_MOD_ASSIGN_SUBMITTED_FOR_GRADING_EVENT, (data) => { if (this.assign && data.assignmentId == this.assign.id && data.userId == this.currentUserId) { // Assignment submitted, check completion. @@ -132,14 +140,14 @@ export class AddonModAssignIndexComponent extends CoreCourseModuleMainActivityCo this.siteId, ); - this.gradedObserver = CoreEvents.on(AddonModAssignProvider.GRADED_EVENT, (data) => { + this.gradedObserver = CoreEvents.on(ADDON_MOD_ASSIGN_GRADED_EVENT, (data) => { if (this.assign && data.assignmentId == this.assign.id && data.userId == this.currentUserId) { // Assignment graded, refresh data. this.showLoadingAndRefresh(true, false); } }, this.siteId); - this.startedObserver = CoreEvents.on(AddonModAssignProvider.STARTED_EVENT, (data) => { + this.startedObserver = CoreEvents.on(ADDON_MOD_ASSIGN_STARTED_EVENT, (data) => { if (this.assign && data.assignmentId == this.assign.id) { // Assignment submission started, refresh data. this.showLoadingAndRefresh(false, false); @@ -276,10 +284,10 @@ export class AddonModAssignIndexComponent extends CoreCourseModuleMainActivityCo this.summary.warnofungroupedusers = 'ungroupedusers'; } else { switch (this.summary.warnofungroupedusers) { - case AddonModAssignProvider.WARN_GROUPS_REQUIRED: + case ADDON_MOD_ASSIGN_WARN_GROUPS_REQUIRED: this.summary.warnofungroupedusers = 'ungroupedusers'; break; - case AddonModAssignProvider.WARN_GROUPS_OPTIONAL: + case ADDON_MOD_ASSIGN_WARN_GROUPS_OPTIONAL: this.summary.warnofungroupedusers = 'ungroupedusersoptional'; break; default: @@ -311,7 +319,7 @@ export class AddonModAssignIndexComponent extends CoreCourseModuleMainActivityCo } CoreNavigator.navigateToSitePath( - AddonModAssignModuleHandlerService.PAGE_NAME + `/${this.courseId}/${this.module.id}/submission`, + ADDON_MOD_ASSIGN_PAGE_NAME + `/${this.courseId}/${this.module.id}/submission`, { params, }, diff --git a/src/addons/mod/assign/components/submission-plugin/submission-plugin.ts b/src/addons/mod/assign/components/submission-plugin/submission-plugin.ts index 421aee60c..93210b120 100644 --- a/src/addons/mod/assign/components/submission-plugin/submission-plugin.ts +++ b/src/addons/mod/assign/components/submission-plugin/submission-plugin.ts @@ -18,13 +18,13 @@ import { AddonModAssignAssign, AddonModAssignSubmission, AddonModAssignPlugin, - AddonModAssignProvider, AddonModAssign, } from '../../services/assign'; import { AddonModAssignHelper, AddonModAssignPluginConfig } from '../../services/assign-helper'; import { AddonModAssignSubmissionDelegate } from '../../services/submission-delegate'; import { CoreFileEntry } from '@services/file-helper'; import type { AddonModAssignSubmissionPluginBaseComponent } from '@addons/mod/assign/classes/base-submission-plugin-component'; +import { ADDON_MOD_ASSIGN_COMPONENT } from '../../constants'; /** * Component that displays an assignment submission plugin. @@ -47,7 +47,7 @@ export class AddonModAssignSubmissionPluginComponent implements OnInit { data?: AddonModAssignSubmissionPluginData; // Data to pass to the component. // Data to render the plugin if it isn't supported. - component = AddonModAssignProvider.COMPONENT; + component = ADDON_MOD_ASSIGN_COMPONENT; text = ''; files: CoreFileEntry[] = []; notSupported = false; diff --git a/src/addons/mod/assign/components/submission/submission.ts b/src/addons/mod/assign/components/submission/submission.ts index fb3522d0e..9e6011c32 100644 --- a/src/addons/mod/assign/components/submission/submission.ts +++ b/src/addons/mod/assign/components/submission/submission.ts @@ -16,7 +16,6 @@ import { Component, Input, OnInit, OnDestroy, ViewChild, Optional, ViewChildren, import { CoreEvents, CoreEventObserver } from '@singletons/events'; import { CoreSites } from '@services/sites'; import { - AddonModAssignProvider, AddonModAssignAssign, AddonModAssignSubmissionFeedback, AddonModAssignSubmissionAttempt, @@ -33,7 +32,6 @@ import { AddonModAssignAutoSyncData, AddonModAssignManualSyncData, AddonModAssignSync, - AddonModAssignSyncProvider, } from '../../services/assign-sync'; import { CoreTabsComponent } from '@components/tabs/tabs'; import { CoreTabComponent } from '@components/tabs/tab'; @@ -56,11 +54,19 @@ import { CoreError } from '@classes/errors/error'; import { CoreGroups } from '@services/groups'; import { CoreSync } from '@services/sync'; import { AddonModAssignSubmissionPluginComponent } from '../submission-plugin/submission-plugin'; -import { AddonModAssignModuleHandlerService } from '../../services/handlers/module'; import { CanLeave } from '@guards/can-leave'; import { CoreTime } from '@singletons/time'; import { isSafeNumber, SafeNumber } from '@/core/utils/types'; import { CoreIonicColorNames } from '@singletons/colors'; +import { + ADDON_MOD_ASSIGN_AUTO_SYNCED, + ADDON_MOD_ASSIGN_COMPONENT, + ADDON_MOD_ASSIGN_GRADED_EVENT, + ADDON_MOD_ASSIGN_MANUAL_SYNCED, + ADDON_MOD_ASSIGN_PAGE_NAME, + ADDON_MOD_ASSIGN_SUBMITTED_FOR_GRADING_EVENT, + ADDON_MOD_ASSIGN_UNLIMITED_ATTEMPTS, +} from '../../constants'; /** * Component that displays an assignment submission. @@ -137,7 +143,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy, Can statusNew = AddonModAssignSubmissionStatusValues.NEW; statusReopened = AddonModAssignSubmissionStatusValues.REOPENED; attemptReopenMethodNone = AddonModAssignAttemptReopenMethodValues.NONE; - unlimitedAttempts = AddonModAssignProvider.UNLIMITED_ATTEMPTS; + unlimitedAttempts = ADDON_MOD_ASSIGN_UNLIMITED_ATTEMPTS; protected siteId: string; // Current site ID. protected currentUserId: number; // Current user ID. @@ -161,7 +167,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy, Can this.maxAttemptsText = Translate.instant('addon.mod_assign.unlimitedattempts'); // Refresh data if this assign is synchronized and it's grading. - const events = [AddonModAssignSyncProvider.AUTO_SYNCED, AddonModAssignSyncProvider.MANUAL_SYNCED]; + const events = [ADDON_MOD_ASSIGN_AUTO_SYNCED, ADDON_MOD_ASSIGN_MANUAL_SYNCED]; this.syncObserver = CoreEvents.onMultiple( events, async (data) => { @@ -341,7 +347,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy, Can if (!this.assign.submissiondrafts && this.userSubmission) { // No drafts allowed, so it was submitted. Trigger event. - CoreEvents.trigger(AddonModAssignProvider.SUBMITTED_FOR_GRADING_EVENT, { + CoreEvents.trigger(ADDON_MOD_ASSIGN_SUBMITTED_FOR_GRADING_EVENT, { assignmentId: this.assign.id, submissionId: this.userSubmission.id, userId: this.currentUserId, @@ -389,7 +395,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy, Can } CoreNavigator.navigateToSitePath( - AddonModAssignModuleHandlerService.PAGE_NAME + '/' + this.courseId + '/' + this.moduleId + '/edit', + ADDON_MOD_ASSIGN_PAGE_NAME + '/' + this.courseId + '/' + this.moduleId + '/edit', { params: { blindId: this.blindId, @@ -528,7 +534,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy, Can const result = await AddonModAssignSync.syncAssign(this.assign.id); if (result && result.updated) { - CoreEvents.trigger(AddonModAssignSyncProvider.MANUAL_SYNCED, { + CoreEvents.trigger(ADDON_MOD_ASSIGN_MANUAL_SYNCED, { assignId: this.assign.id, warnings: result.warnings, gradesBlocked: result.gradesBlocked, @@ -703,7 +709,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy, Can await this.treatGradeInfo(assign); const isManual = assign.attemptreopenmethod == AddonModAssignAttemptReopenMethodValues.MANUAL; - const isUnlimited = assign.maxattempts == AddonModAssignProvider.UNLIMITED_ATTEMPTS; + const isUnlimited = assign.maxattempts == ADDON_MOD_ASSIGN_UNLIMITED_ATTEMPTS; const isLessThanMaxAttempts = !!this.userSubmission && (this.userSubmission.attemptnumber < (assign.maxattempts - 1)); this.allowAddAttempt = isManual && (!this.userSubmission || isUnlimited || isLessThanMaxAttempts); @@ -864,7 +870,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy, Can Translate.instant('core.grades.grade'), this.feedback.gradefordisplay, { - component: AddonModAssignProvider.COMPONENT, + component: ADDON_MOD_ASSIGN_COMPONENT, componentId: this.moduleId, }, ); @@ -903,7 +909,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy, Can ); // Submitted, trigger event. - CoreEvents.trigger(AddonModAssignProvider.SUBMITTED_FOR_GRADING_EVENT, { + CoreEvents.trigger(ADDON_MOD_ASSIGN_SUBMITTED_FOR_GRADING_EVENT, { assignmentId: this.assign.id, submissionId: this.userSubmission.id, userId: this.currentUserId, @@ -977,7 +983,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy, Can // Invalidate and refresh data. this.invalidateAndRefresh(true); - CoreEvents.trigger(AddonModAssignProvider.GRADED_EVENT, { + CoreEvents.trigger(ADDON_MOD_ASSIGN_GRADED_EVENT, { assignmentId: this.assign.id, submissionId: this.submitId, userId: this.currentUserId, @@ -1228,9 +1234,9 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy, Can const syncId = AddonModAssignSync.getGradeSyncId(this.assign.id, this.submitId); if (block) { - CoreSync.blockOperation(AddonModAssignProvider.COMPONENT, syncId); + CoreSync.blockOperation(ADDON_MOD_ASSIGN_COMPONENT, syncId); } else { - CoreSync.unblockOperation(AddonModAssignProvider.COMPONENT, syncId); + CoreSync.unblockOperation(ADDON_MOD_ASSIGN_COMPONENT, syncId); } } diff --git a/src/addons/mod/assign/constants.ts b/src/addons/mod/assign/constants.ts index 0d502e358..52797e854 100644 --- a/src/addons/mod/assign/constants.ts +++ b/src/addons/mod/assign/constants.ts @@ -13,3 +13,20 @@ // limitations under the License. export const ADDON_MOD_ASSIGN_FEATURE_NAME = 'CoreCourseModuleDelegate_AddonModAssign'; + +export const ADDON_MOD_ASSIGN_COMPONENT = 'mmaModAssign'; +export const ADDON_MOD_ASSIGN_PAGE_NAME = 'mod_assign'; + +export const ADDON_MOD_ASSIGN_UNLIMITED_ATTEMPTS = -1; + +// Group submissions warnings. +export const ADDON_MOD_ASSIGN_WARN_GROUPS_REQUIRED = 'warnrequired'; +export const ADDON_MOD_ASSIGN_WARN_GROUPS_OPTIONAL = 'warnoptional'; + +// Events. +export const ADDON_MOD_ASSIGN_SUBMISSION_SAVED_EVENT = 'addon_mod_assign_submission_saved'; +export const ADDON_MOD_ASSIGN_SUBMITTED_FOR_GRADING_EVENT = 'addon_mod_assign_submitted_for_grading'; +export const ADDON_MOD_ASSIGN_GRADED_EVENT = 'addon_mod_assign_graded'; +export const ADDON_MOD_ASSIGN_STARTED_EVENT = 'addon_mod_assign_started'; +export const ADDON_MOD_ASSIGN_AUTO_SYNCED = 'addon_mod_assign_autom_synced'; +export const ADDON_MOD_ASSIGN_MANUAL_SYNCED = 'addon_mod_assign_manual_synced'; diff --git a/src/addons/mod/assign/feedback/comments/component/comments.ts b/src/addons/mod/assign/feedback/comments/component/comments.ts index 7113410cb..d23cd85dd 100644 --- a/src/addons/mod/assign/feedback/comments/component/comments.ts +++ b/src/addons/mod/assign/feedback/comments/component/comments.ts @@ -14,7 +14,7 @@ import { Component, OnInit, ElementRef } from '@angular/core'; import { FormBuilder, FormControl } from '@angular/forms'; -import { AddonModAssign, AddonModAssignProvider } from '@addons/mod/assign/services/assign'; +import { AddonModAssign } from '@addons/mod/assign/services/assign'; import { CoreTextUtils } from '@services/utils/text'; import { AddonModAssignFeedbackCommentsDraftData, @@ -26,6 +26,7 @@ import { AddonModAssignOffline } from '@addons/mod/assign/services/assign-offlin import { CoreUtils } from '@services/utils/utils'; import { AddonModAssignFeedbackPluginBaseComponent } from '@addons/mod/assign/classes/base-feedback-plugin-component'; import { ContextLevel } from '@/core/constants'; +import { ADDON_MOD_ASSIGN_COMPONENT } from '@addons/mod/assign/constants'; /** * Component to render a comments feedback plugin. */ @@ -36,7 +37,7 @@ import { ContextLevel } from '@/core/constants'; export class AddonModAssignFeedbackCommentsComponent extends AddonModAssignFeedbackPluginBaseComponent implements OnInit { control?: FormControl; - component = AddonModAssignProvider.COMPONENT; + component = ADDON_MOD_ASSIGN_COMPONENT; text = ''; isSent = false; loaded = false; diff --git a/src/addons/mod/assign/feedback/editpdf/component/editpdf.ts b/src/addons/mod/assign/feedback/editpdf/component/editpdf.ts index bb06c3bc5..6278dcb28 100644 --- a/src/addons/mod/assign/feedback/editpdf/component/editpdf.ts +++ b/src/addons/mod/assign/feedback/editpdf/component/editpdf.ts @@ -13,7 +13,8 @@ // limitations under the License. import { AddonModAssignFeedbackPluginBaseComponent } from '@addons/mod/assign/classes/base-feedback-plugin-component'; -import { AddonModAssignProvider, AddonModAssign } from '@addons/mod/assign/services/assign'; +import { ADDON_MOD_ASSIGN_COMPONENT } from '@addons/mod/assign/constants'; +import { AddonModAssign } from '@addons/mod/assign/services/assign'; import { Component, OnInit } from '@angular/core'; import { CoreWSFile } from '@services/ws'; @@ -26,7 +27,7 @@ import { CoreWSFile } from '@services/ws'; }) export class AddonModAssignFeedbackEditPdfComponent extends AddonModAssignFeedbackPluginBaseComponent implements OnInit { - component = AddonModAssignProvider.COMPONENT; + component = ADDON_MOD_ASSIGN_COMPONENT; files: CoreWSFile[] = []; /** diff --git a/src/addons/mod/assign/feedback/file/component/file.ts b/src/addons/mod/assign/feedback/file/component/file.ts index 2d85f5415..ef86aae46 100644 --- a/src/addons/mod/assign/feedback/file/component/file.ts +++ b/src/addons/mod/assign/feedback/file/component/file.ts @@ -13,7 +13,8 @@ // limitations under the License. import { AddonModAssignFeedbackPluginBaseComponent } from '@addons/mod/assign/classes/base-feedback-plugin-component'; -import { AddonModAssign, AddonModAssignProvider } from '@addons/mod/assign/services/assign'; +import { ADDON_MOD_ASSIGN_COMPONENT } from '@addons/mod/assign/constants'; +import { AddonModAssign } from '@addons/mod/assign/services/assign'; import { Component, OnInit } from '@angular/core'; import { CoreWSFile } from '@services/ws'; @@ -26,7 +27,7 @@ import { CoreWSFile } from '@services/ws'; }) export class AddonModAssignFeedbackFileComponent extends AddonModAssignFeedbackPluginBaseComponent implements OnInit { - component = AddonModAssignProvider.COMPONENT; + component = ADDON_MOD_ASSIGN_COMPONENT; files: CoreWSFile[] = []; /** diff --git a/src/addons/mod/assign/pages/edit/edit.ts b/src/addons/mod/assign/pages/edit/edit.ts index 1618d3918..e421deaf0 100644 --- a/src/addons/mod/assign/pages/edit/edit.ts +++ b/src/addons/mod/assign/pages/edit/edit.ts @@ -27,7 +27,6 @@ import { CoreEvents } from '@singletons/events'; import { AddonModAssignAssign, AddonModAssignSubmission, - AddonModAssignProvider, AddonModAssign, AddonModAssignSubmissionStatusOptions, AddonModAssignGetSubmissionStatusWSResponse, @@ -40,6 +39,12 @@ import { AddonModAssignSync } from '../../services/assign-sync'; import { CoreUtils } from '@services/utils/utils'; import { CoreWSExternalFile } from '@services/ws'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; +import { + ADDON_MOD_ASSIGN_COMPONENT, + ADDON_MOD_ASSIGN_STARTED_EVENT, + ADDON_MOD_ASSIGN_SUBMISSION_SAVED_EVENT, + ADDON_MOD_ASSIGN_SUBMITTED_FOR_GRADING_EVENT, +} from '../../constants'; /** * Page that allows adding or editing an assigment submission. @@ -65,7 +70,7 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy, CanLeave { timeLimitEndTime = 0; // If time limit is enabled, the end time for the timer. activityInstructions?: string; // Activity instructions. introAttachments?: CoreWSExternalFile[]; // Intro attachments. - component = AddonModAssignProvider.COMPONENT; + component = ADDON_MOD_ASSIGN_COMPONENT; protected userId: number; // User doing the submission. protected isBlind = false; // Whether blind is used. @@ -144,7 +149,7 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy, CanLeave { if (!this.isDestroyed) { // Block the assignment. - CoreSync.blockOperation(AddonModAssignProvider.COMPONENT, this.assign.id); + CoreSync.blockOperation(ADDON_MOD_ASSIGN_COMPONENT, this.assign.id); } // Wait for sync to be over (if any). @@ -276,7 +281,7 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy, CanLeave { await AddonModAssign.startSubmission(this.assign.id); - CoreEvents.trigger(AddonModAssignProvider.STARTED_EVENT, { + CoreEvents.trigger(ADDON_MOD_ASSIGN_STARTED_EVENT, { assignmentId: this.assign.id, }, CoreSites.getCurrentSiteId()); @@ -453,7 +458,7 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy, CanLeave { CoreForms.triggerFormSubmittedEvent(this.formElement, sent, CoreSites.getCurrentSiteId()); CoreEvents.trigger( - AddonModAssignProvider.SUBMISSION_SAVED_EVENT, + ADDON_MOD_ASSIGN_SUBMISSION_SAVED_EVENT, { assignmentId: this.assign!.id, submissionId: this.userSubmission!.id, @@ -465,7 +470,7 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy, CanLeave { if (!this.assign!.submissiondrafts) { // No drafts allowed, so it was submitted. Trigger event. CoreEvents.trigger( - AddonModAssignProvider.SUBMITTED_FOR_GRADING_EVENT, + ADDON_MOD_ASSIGN_SUBMITTED_FOR_GRADING_EVENT, { assignmentId: this.assign!.id, submissionId: this.userSubmission!.id, @@ -500,7 +505,7 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy, CanLeave { // Unblock the assignment. if (this.assign) { - CoreSync.unblockOperation(AddonModAssignProvider.COMPONENT, this.assign.id); + CoreSync.unblockOperation(ADDON_MOD_ASSIGN_COMPONENT, this.assign.id); } } diff --git a/src/addons/mod/assign/pages/submission-list/submission-list.ts b/src/addons/mod/assign/pages/submission-list/submission-list.ts index a92830987..32043ec76 100644 --- a/src/addons/mod/assign/pages/submission-list/submission-list.ts +++ b/src/addons/mod/assign/pages/submission-list/submission-list.ts @@ -27,13 +27,13 @@ import { AddonModAssignSubmissionForList, AddonModAssignSubmissionsSource, } from '../../classes/submissions-source'; -import { AddonModAssignAssign, AddonModAssignProvider } from '../../services/assign'; +import { AddonModAssignAssign } from '../../services/assign'; import { - AddonModAssignSyncProvider, AddonModAssignManualSyncData, AddonModAssignAutoSyncData, } from '../../services/assign-sync'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; +import { ADDON_MOD_ASSIGN_AUTO_SYNCED, ADDON_MOD_ASSIGN_GRADED_EVENT, ADDON_MOD_ASSIGN_MANUAL_SYNCED } from '../../constants'; /** * Page that displays a list of submissions of an assignment. @@ -56,7 +56,7 @@ export class AddonModAssignSubmissionListPage implements AfterViewInit, OnDestro constructor() { // Update data if some grade changes. this.gradedObserver = CoreEvents.on( - AddonModAssignProvider.GRADED_EVENT, + ADDON_MOD_ASSIGN_GRADED_EVENT, (data) => { if ( this.submissions.loaded && @@ -72,7 +72,7 @@ export class AddonModAssignSubmissionListPage implements AfterViewInit, OnDestro ); // Refresh data if this assign is synchronized. - const events = [AddonModAssignSyncProvider.AUTO_SYNCED, AddonModAssignSyncProvider.MANUAL_SYNCED]; + const events = [ADDON_MOD_ASSIGN_AUTO_SYNCED, ADDON_MOD_ASSIGN_MANUAL_SYNCED]; this.syncObserver = CoreEvents.onMultiple( events, (data) => { diff --git a/src/addons/mod/assign/services/assign-helper.ts b/src/addons/mod/assign/services/assign-helper.ts index 49384adee..c191c8013 100644 --- a/src/addons/mod/assign/services/assign-helper.ts +++ b/src/addons/mod/assign/services/assign-helper.ts @@ -17,7 +17,6 @@ import { CoreFileUploader, CoreFileUploaderStoreFilesResult } from '@features/fi import { CoreSites, CoreSitesCommonWSOptions } from '@services/sites'; import { FileEntry, DirectoryEntry } from '@awesome-cordova-plugins/file/ngx'; import { - AddonModAssignProvider, AddonModAssignAssign, AddonModAssignSubmission, AddonModAssignParticipant, @@ -37,6 +36,7 @@ import { AddonModAssignFeedbackDelegate } from './feedback-delegate'; import { makeSingleton } from '@singletons'; import { CoreFormFields } from '@singletons/form'; import { CoreFileEntry } from '@services/file-helper'; +import { ADDON_MOD_ASSIGN_COMPONENT } from '../constants'; /** * Service that provides some helper functions for assign. @@ -650,7 +650,7 @@ export class AddonModAssignHelperProvider { * @returns Promise resolved with the itemId. */ uploadFile(assignId: number, file: CoreFileEntry, itemId?: number, siteId?: string): Promise { - return CoreFileUploader.uploadOrReuploadFile(file, itemId, AddonModAssignProvider.COMPONENT, assignId, siteId); + return CoreFileUploader.uploadOrReuploadFile(file, itemId, ADDON_MOD_ASSIGN_COMPONENT, assignId, siteId); } /** @@ -664,7 +664,7 @@ export class AddonModAssignHelperProvider { * @returns Promise resolved with the itemId. */ uploadFiles(assignId: number, files: CoreFileEntry[], siteId?: string): Promise { - return CoreFileUploader.uploadOrReuploadFiles(files, AddonModAssignProvider.COMPONENT, assignId, siteId); + return CoreFileUploader.uploadOrReuploadFiles(files, ADDON_MOD_ASSIGN_COMPONENT, assignId, siteId); } /** diff --git a/src/addons/mod/assign/services/assign-sync.ts b/src/addons/mod/assign/services/assign-sync.ts index 1c5ced9cf..19137968e 100644 --- a/src/addons/mod/assign/services/assign-sync.ts +++ b/src/addons/mod/assign/services/assign-sync.ts @@ -17,7 +17,6 @@ import { CoreEvents } from '@singletons/events'; import { CoreSites, CoreSitesReadingStrategy } from '@services/sites'; import { CoreSyncBlockedError } from '@classes/base-sync'; import { - AddonModAssignProvider, AddonModAssignAssign, AddonModAssignSubmission, AddonModAssign, @@ -40,6 +39,7 @@ import { CoreNetworkError } from '@classes/errors/network-error'; import { CoreGradesFormattedItem, CoreGradesHelper } from '@features/grades/services/grades-helper'; import { AddonModAssignSubmissionDelegate } from './submission-delegate'; import { AddonModAssignFeedbackDelegate } from './feedback-delegate'; +import { ADDON_MOD_ASSIGN_AUTO_SYNCED, ADDON_MOD_ASSIGN_COMPONENT } from '../constants'; /** * Service to sync assigns. @@ -47,9 +47,6 @@ import { AddonModAssignFeedbackDelegate } from './feedback-delegate'; @Injectable({ providedIn: 'root' }) export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvider { - static readonly AUTO_SYNCED = 'addon_mod_assign_autom_synced'; - static readonly MANUAL_SYNCED = 'addon_mod_assign_manual_synced'; - protected componentTranslatableString = 'assign'; constructor() { @@ -129,7 +126,7 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid : await this.syncAssignIfNeeded(assignId, siteId); if (result?.updated) { - CoreEvents.trigger(AddonModAssignSyncProvider.AUTO_SYNCED, { + CoreEvents.trigger(ADDON_MOD_ASSIGN_AUTO_SYNCED, { assignId: assignId, warnings: result.warnings, gradesBlocked: result.gradesBlocked, @@ -170,7 +167,7 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid } // Verify that assign isn't blocked. - if (CoreSync.isBlocked(AddonModAssignProvider.COMPONENT, assignId, siteId)) { + if (CoreSync.isBlocked(ADDON_MOD_ASSIGN_COMPONENT, assignId, siteId)) { this.logger.debug('Cannot sync assign ' + assignId + ' because it is blocked.'); throw new CoreSyncBlockedError(Translate.instant('core.errorsyncblocked', { $a: this.componentTranslate })); @@ -193,7 +190,7 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid protected async performSyncAssign(assignId: number, siteId: string): Promise { // Sync offline logs. await CoreUtils.ignoreErrors( - CoreCourseLogHelper.syncActivity(AddonModAssignProvider.COMPONENT, assignId, siteId), + CoreCourseLogHelper.syncActivity(ADDON_MOD_ASSIGN_COMPONENT, assignId, siteId), ); const result: AddonModAssignSyncResult = { @@ -433,7 +430,7 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid }; // Check if this grade sync is blocked. - if (CoreSync.isBlocked(AddonModAssignProvider.COMPONENT, syncId, siteId)) { + if (CoreSync.isBlocked(ADDON_MOD_ASSIGN_COMPONENT, syncId, siteId)) { this.logger.error(`Cannot sync grade for assign ${assign.id} and user ${userId} because it is blocked.!!!!`); throw new CoreSyncBlockedError(Translate.instant( diff --git a/src/addons/mod/assign/services/assign.ts b/src/addons/mod/assign/services/assign.ts index a0bd72252..f44ccc25c 100644 --- a/src/addons/mod/assign/services/assign.ts +++ b/src/addons/mod/assign/services/assign.ts @@ -31,14 +31,21 @@ import { AddonModAssignSubmissionDelegate } from './submission-delegate'; import { CoreComments } from '@features/comments/services/comments'; import { AddonModAssignSubmissionFormatted } from './assign-helper'; import { CoreWSError } from '@classes/errors/wserror'; -import { AddonModAssignAutoSyncData, AddonModAssignManualSyncData, AddonModAssignSyncProvider } from './assign-sync'; +import { AddonModAssignAutoSyncData, AddonModAssignManualSyncData } from './assign-sync'; import { CoreFormFields } from '@singletons/form'; import { CoreFileHelper } from '@services/file-helper'; import { CoreIonicColorNames } from '@singletons/colors'; import { CoreSiteWSPreSets } from '@classes/sites/authenticated-site'; import { ContextLevel } from '@/core/constants'; - -const ROOT_CACHE_KEY = 'mmaModAssign:'; +import { + ADDON_MOD_ASSIGN_AUTO_SYNCED, + ADDON_MOD_ASSIGN_COMPONENT, + ADDON_MOD_ASSIGN_GRADED_EVENT, + ADDON_MOD_ASSIGN_MANUAL_SYNCED, + ADDON_MOD_ASSIGN_STARTED_EVENT, + ADDON_MOD_ASSIGN_SUBMISSION_SAVED_EVENT, + ADDON_MOD_ASSIGN_SUBMITTED_FOR_GRADING_EVENT, +} from '../constants'; declare module '@singletons/events' { @@ -48,12 +55,12 @@ declare module '@singletons/events' { * @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation */ export interface CoreEventsData { - [AddonModAssignProvider.SUBMISSION_SAVED_EVENT]: AddonModAssignSubmissionSavedEventData; - [AddonModAssignProvider.SUBMITTED_FOR_GRADING_EVENT]: AddonModAssignSubmittedForGradingEventData; - [AddonModAssignProvider.GRADED_EVENT]: AddonModAssignGradedEventData; - [AddonModAssignProvider.STARTED_EVENT]: AddonModAssignStartedEventData; - [AddonModAssignSyncProvider.MANUAL_SYNCED]: AddonModAssignManualSyncData; - [AddonModAssignSyncProvider.AUTO_SYNCED]: AddonModAssignAutoSyncData; + [ADDON_MOD_ASSIGN_SUBMISSION_SAVED_EVENT]: AddonModAssignSubmissionSavedEventData; + [ADDON_MOD_ASSIGN_SUBMITTED_FOR_GRADING_EVENT]: AddonModAssignSubmittedForGradingEventData; + [ADDON_MOD_ASSIGN_GRADED_EVENT]: AddonModAssignGradedEventData; + [ADDON_MOD_ASSIGN_STARTED_EVENT]: AddonModAssignStartedEventData; + [ADDON_MOD_ASSIGN_MANUAL_SYNCED]: AddonModAssignManualSyncData; + [ADDON_MOD_ASSIGN_AUTO_SYNCED]: AddonModAssignAutoSyncData; } } @@ -64,19 +71,7 @@ declare module '@singletons/events' { @Injectable({ providedIn: 'root' }) export class AddonModAssignProvider { - static readonly COMPONENT = 'mmaModAssign'; - static readonly SUBMISSION_COMPONENT = 'mmaModAssignSubmission'; - static readonly UNLIMITED_ATTEMPTS = -1; - - // Group submissions warnings. - static readonly WARN_GROUPS_REQUIRED = 'warnrequired'; - static readonly WARN_GROUPS_OPTIONAL = 'warnoptional'; - - // Events. - static readonly SUBMISSION_SAVED_EVENT = 'addon_mod_assign_submission_saved'; - static readonly SUBMITTED_FOR_GRADING_EVENT = 'addon_mod_assign_submitted_for_grading'; - static readonly GRADED_EVENT = 'addon_mod_assign_graded'; - static readonly STARTED_EVENT = 'addon_mod_assign_started'; + protected static readonly ROOT_CACHE_KEY = 'mmaModAssign:'; /** * Check if the user can submit in offline. This should only be used if submissionStatus.lastattempt.cansubmit cannot @@ -179,7 +174,7 @@ export class AddonModAssignProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getAssignmentCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, - component: AddonModAssignProvider.COMPONENT, + component: ADDON_MOD_ASSIGN_COMPONENT, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -226,7 +221,7 @@ export class AddonModAssignProvider { * @returns Cache key. */ protected getAssignmentCacheKey(courseId: number): string { - return ROOT_CACHE_KEY + 'assignment:' + courseId; + return AddonModAssignProvider.ROOT_CACHE_KEY + 'assignment:' + courseId; } /** @@ -251,7 +246,7 @@ export class AddonModAssignProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getAssignmentUserMappingsCacheKey(assignId), updateFrequency: CoreSite.FREQUENCY_OFTEN, - component: AddonModAssignProvider.COMPONENT, + component: ADDON_MOD_ASSIGN_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), }; @@ -279,7 +274,7 @@ export class AddonModAssignProvider { * @returns Cache key. */ protected getAssignmentUserMappingsCacheKey(assignId: number): string { - return ROOT_CACHE_KEY + 'usermappings:' + assignId; + return AddonModAssignProvider.ROOT_CACHE_KEY + 'usermappings:' + assignId; } /** @@ -297,7 +292,7 @@ export class AddonModAssignProvider { }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getAssignmentGradesCacheKey(assignId), - component: AddonModAssignProvider.COMPONENT, + component: ADDON_MOD_ASSIGN_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), }; @@ -326,7 +321,7 @@ export class AddonModAssignProvider { * @returns Cache key. */ protected getAssignmentGradesCacheKey(assignId: number): string { - return ROOT_CACHE_KEY + 'assigngrades:' + assignId; + return AddonModAssignProvider.ROOT_CACHE_KEY + 'assigngrades:' + assignId; } /** @@ -461,7 +456,7 @@ export class AddonModAssignProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getSubmissionsCacheKey(assignId), updateFrequency: CoreSite.FREQUENCY_OFTEN, - component: AddonModAssignProvider.COMPONENT, + component: ADDON_MOD_ASSIGN_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), }; @@ -489,7 +484,7 @@ export class AddonModAssignProvider { * @returns Cache key. */ protected getSubmissionsCacheKey(assignId: number): string { - return ROOT_CACHE_KEY + 'submissions:' + assignId; + return AddonModAssignProvider.ROOT_CACHE_KEY + 'submissions:' + assignId; } /** @@ -529,7 +524,7 @@ export class AddonModAssignProvider { getCacheUsingCacheKey: true, filter: options.filter, rewriteurls: options.filter, - component: AddonModAssignProvider.COMPONENT, + component: ADDON_MOD_ASSIGN_COMPONENT, componentId: options.cmId, // Don't cache when getting text without filters. // @todo Change this to support offline editing. @@ -659,7 +654,7 @@ export class AddonModAssignProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.listParticipantsCacheKey(assignId, groupId), updateFrequency: CoreSite.FREQUENCY_OFTEN, - component: AddonModAssignProvider.COMPONENT, + component: ADDON_MOD_ASSIGN_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), }; @@ -685,7 +680,7 @@ export class AddonModAssignProvider { * @returns Cache key. */ protected listParticipantsPrefixCacheKey(assignId: number): string { - return ROOT_CACHE_KEY + 'participants:' + assignId; + return AddonModAssignProvider.ROOT_CACHE_KEY + 'participants:' + assignId; } /** @@ -891,7 +886,7 @@ export class AddonModAssignProvider { await CoreCourseLogHelper.log( 'mod_assign_view_submission_status', params, - AddonModAssignProvider.COMPONENT, + ADDON_MOD_ASSIGN_COMPONENT, assignid, siteId, ); @@ -912,7 +907,7 @@ export class AddonModAssignProvider { await CoreCourseLogHelper.log( 'mod_assign_view_grading_table', params, - AddonModAssignProvider.COMPONENT, + ADDON_MOD_ASSIGN_COMPONENT, assignid, siteId, ); @@ -933,7 +928,7 @@ export class AddonModAssignProvider { await CoreCourseLogHelper.log( 'mod_assign_view_assign', params, - AddonModAssignProvider.COMPONENT, + ADDON_MOD_ASSIGN_COMPONENT, assignid, siteId, ); diff --git a/src/addons/mod/assign/services/handlers/module.ts b/src/addons/mod/assign/services/handlers/module.ts index f66f339ec..0179cd4cd 100644 --- a/src/addons/mod/assign/services/handlers/module.ts +++ b/src/addons/mod/assign/services/handlers/module.ts @@ -17,6 +17,7 @@ import { Injectable, Type } from '@angular/core'; import { CoreCourseModuleHandler } from '@features/course/services/module-delegate'; import { makeSingleton } from '@singletons'; import { CoreModuleHandlerBase } from '@features/course/classes/module-base-handler'; +import { ADDON_MOD_ASSIGN_PAGE_NAME } from '../../constants'; /** * Handler to support assign modules. @@ -24,11 +25,9 @@ import { CoreModuleHandlerBase } from '@features/course/classes/module-base-hand @Injectable({ providedIn: 'root' }) export class AddonModAssignModuleHandlerService extends CoreModuleHandlerBase implements CoreCourseModuleHandler { - static readonly PAGE_NAME = 'mod_assign'; - name = 'AddonModAssign'; modName = 'assign'; - protected pageName = AddonModAssignModuleHandlerService.PAGE_NAME; + protected pageName = ADDON_MOD_ASSIGN_PAGE_NAME; supportedFeatures = { [CoreConstants.FEATURE_GROUPS]: true, diff --git a/src/addons/mod/assign/services/handlers/prefetch.ts b/src/addons/mod/assign/services/handlers/prefetch.ts index b90c16a28..bede2324a 100644 --- a/src/addons/mod/assign/services/handlers/prefetch.ts +++ b/src/addons/mod/assign/services/handlers/prefetch.ts @@ -18,7 +18,6 @@ import { makeSingleton } from '@singletons'; import { AddonModAssign, AddonModAssignAssign, - AddonModAssignProvider, AddonModAssignSubmission, AddonModAssignSubmissionStatusOptions, } from '../assign'; @@ -35,6 +34,7 @@ import { AddonModAssignSync, AddonModAssignSyncResult } from '../assign-sync'; import { CoreUser } from '@features/user/services/user'; import { CoreGradesHelper } from '@features/grades/services/grades-helper'; import { CoreCourses } from '@features/courses/services/courses'; +import { ADDON_MOD_ASSIGN_COMPONENT } from '../../constants'; /** * Handler to prefetch assigns. @@ -44,7 +44,7 @@ export class AddonModAssignPrefetchHandlerService extends CoreCourseActivityPref name = 'AddonModAssign'; modName = 'assign'; - component = AddonModAssignProvider.COMPONENT; + component = ADDON_MOD_ASSIGN_COMPONENT; updatesNames = /^configuration$|^.*files$|^submissions$|^grades$|^gradeitems$|^outcomes$|^comments$/; /** diff --git a/src/addons/mod/assign/submission/file/component/file.ts b/src/addons/mod/assign/submission/file/component/file.ts index dd43def99..588c7e9ee 100644 --- a/src/addons/mod/assign/submission/file/component/file.ts +++ b/src/addons/mod/assign/submission/file/component/file.ts @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { AddonModAssign, AddonModAssignProvider } from '@addons/mod/assign/services/assign'; +import { AddonModAssign } from '@addons/mod/assign/services/assign'; import { AddonModAssignHelper } from '@addons/mod/assign/services/assign-helper'; import { AddonModAssignOffline } from '@addons/mod/assign/services/assign-offline'; import { Component, OnInit } from '@angular/core'; @@ -23,6 +23,7 @@ import { AddonModAssignSubmissionFileHandlerService } from '../services/handler' import { FileEntry } from '@awesome-cordova-plugins/file/ngx'; import { AddonModAssignSubmissionPluginBaseComponent } from '@addons/mod/assign/classes/base-submission-plugin-component'; import { CoreFileEntry } from '@services/file-helper'; +import { ADDON_MOD_ASSIGN_COMPONENT } from '@addons/mod/assign/constants'; /** * Component to render a file submission plugin. @@ -33,7 +34,7 @@ import { CoreFileEntry } from '@services/file-helper'; }) export class AddonModAssignSubmissionFileComponent extends AddonModAssignSubmissionPluginBaseComponent implements OnInit { - component = AddonModAssignProvider.COMPONENT; + component = ADDON_MOD_ASSIGN_COMPONENT; files: CoreFileEntry[] = []; maxSize?: number; diff --git a/src/addons/mod/assign/submission/file/services/handler.ts b/src/addons/mod/assign/submission/file/services/handler.ts index 121f64fb5..595572d4d 100644 --- a/src/addons/mod/assign/submission/file/services/handler.ts +++ b/src/addons/mod/assign/submission/file/services/handler.ts @@ -16,7 +16,6 @@ import { AddonModAssignAssign, AddonModAssignSubmission, AddonModAssignPlugin, - AddonModAssignProvider, AddonModAssign, } from '@addons/mod/assign/services/assign'; import { AddonModAssignHelper } from '@addons/mod/assign/services/assign-helper'; @@ -32,6 +31,7 @@ import { makeSingleton } from '@singletons'; import { AddonModAssignSubmissionFileComponent } from '../component/file'; import { FileEntry } from '@awesome-cordova-plugins/file/ngx'; import type { AddonModAssignSubmissionPluginBaseComponent } from '@addons/mod/assign/classes/base-submission-plugin-component'; +import { ADDON_MOD_ASSIGN_COMPONENT } from '@addons/mod/assign/constants'; /** * Handler for file submission plugin. @@ -65,10 +65,10 @@ export class AddonModAssignSubmissionFileHandlerService implements AddonModAssig * @inheritdoc */ clearTmpData(assign: AddonModAssignAssign): void { - const files = CoreFileSession.getFiles(AddonModAssignProvider.COMPONENT, assign.id); + const files = CoreFileSession.getFiles(ADDON_MOD_ASSIGN_COMPONENT, assign.id); // Clear the files in session for this assign. - CoreFileSession.clearFiles(AddonModAssignProvider.COMPONENT, assign.id); + CoreFileSession.clearFiles(ADDON_MOD_ASSIGN_COMPONENT, assign.id); // Now delete the local files from the tmp folder. CoreFileUploader.clearTmpFiles(files); @@ -148,7 +148,7 @@ export class AddonModAssignSubmissionFileHandlerService implements AddonModAssig // Check if there's any change. const hasChanged = await this.hasDataChanged(assign, submission, plugin); if (hasChanged) { - const files = CoreFileSession.getFiles(AddonModAssignProvider.COMPONENT, assign.id); + const files = CoreFileSession.getFiles(ADDON_MOD_ASSIGN_COMPONENT, assign.id); return CoreFileHelper.getTotalFilesSize(files); } else { @@ -183,7 +183,7 @@ export class AddonModAssignSubmissionFileHandlerService implements AddonModAssig numFiles = pluginFiles && pluginFiles.length; } - const currentFiles = CoreFileSession.getFiles(AddonModAssignProvider.COMPONENT, assign.id); + const currentFiles = CoreFileSession.getFiles(ADDON_MOD_ASSIGN_COMPONENT, assign.id); if (currentFiles.length != numFiles) { // Number of files has changed. @@ -230,7 +230,7 @@ export class AddonModAssignSubmissionFileHandlerService implements AddonModAssig } // Data has changed, we need to upload new files and re-upload all the existing files. - const currentFiles = CoreFileSession.getFiles(AddonModAssignProvider.COMPONENT, assign.id); + const currentFiles = CoreFileSession.getFiles(ADDON_MOD_ASSIGN_COMPONENT, assign.id); const error = CoreUtils.hasRepeatedFilenames(currentFiles); if (error) { diff --git a/src/addons/mod/assign/submission/onlinetext/component/onlinetext.ts b/src/addons/mod/assign/submission/onlinetext/component/onlinetext.ts index 942c45518..2feffbd82 100644 --- a/src/addons/mod/assign/submission/onlinetext/component/onlinetext.ts +++ b/src/addons/mod/assign/submission/onlinetext/component/onlinetext.ts @@ -13,7 +13,7 @@ // limitations under the License. import { AddonModAssignSubmissionPluginBaseComponent } from '@addons/mod/assign/classes/base-submission-plugin-component'; -import { AddonModAssignProvider, AddonModAssign } from '@addons/mod/assign/services/assign'; +import { AddonModAssign } from '@addons/mod/assign/services/assign'; import { AddonModAssignOffline } from '@addons/mod/assign/services/assign-offline'; import { Component, OnInit, ElementRef } from '@angular/core'; import { FormBuilder, FormControl } from '@angular/forms'; @@ -22,6 +22,7 @@ import { CoreTextUtils } from '@services/utils/text'; import { CoreUtils } from '@services/utils/utils'; import { AddonModAssignSubmissionOnlineTextPluginData } from '../services/handler'; import { ContextLevel } from '@/core/constants'; +import { ADDON_MOD_ASSIGN_COMPONENT } from '@addons/mod/assign/constants'; /** * Component to render an onlinetext submission plugin. @@ -34,7 +35,7 @@ export class AddonModAssignSubmissionOnlineTextComponent extends AddonModAssignS control?: FormControl; words = 0; - component = AddonModAssignProvider.COMPONENT; + component = ADDON_MOD_ASSIGN_COMPONENT; text = ''; loaded = false; wordLimitEnabled = false; From 62f097dc920576730efb3e4272db1ed845fc3d0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Fri, 12 Jul 2024 10:22:20 +0200 Subject: [PATCH 02/26] MOBILE-4616 lesson: Move lesson constants to a file --- .../mod/lesson/components/index/index.ts | 21 ++- src/addons/mod/lesson/constants.ts | 54 ++++++ src/addons/mod/lesson/lesson-lazy.module.ts | 2 +- src/addons/mod/lesson/lesson.module.ts | 10 +- src/addons/mod/lesson/pages/player/player.ts | 16 +- .../lesson/pages/user-retake/user-retake.ts | 4 +- .../lesson/services/handlers/grade-link.ts | 4 +- .../mod/lesson/services/handlers/module.ts | 5 +- .../mod/lesson/services/handlers/prefetch.ts | 8 +- .../lesson/services/handlers/report-link.ts | 6 +- .../mod/lesson/services/lesson-helper.ts | 19 +- .../mod/lesson/services/lesson-offline.ts | 7 +- src/addons/mod/lesson/services/lesson-sync.ts | 11 +- src/addons/mod/lesson/services/lesson.ts | 169 ++++++++---------- src/core/features/grades/constants.ts | 20 +++ src/core/features/grades/services/grades.ts | 15 +- 16 files changed, 213 insertions(+), 158 deletions(-) create mode 100644 src/addons/mod/lesson/constants.ts create mode 100644 src/core/features/grades/constants.ts diff --git a/src/addons/mod/lesson/components/index/index.ts b/src/addons/mod/lesson/components/index/index.ts index 13eb4b2d0..d5ad92415 100644 --- a/src/addons/mod/lesson/components/index/index.ts +++ b/src/addons/mod/lesson/components/index/index.ts @@ -36,19 +36,22 @@ import { AddonModLessonGetAccessInformationWSResponse, AddonModLessonLessonWSData, AddonModLessonPreventAccessReason, - AddonModLessonProvider, } from '../../services/lesson'; import { AddonModLessonOffline } from '../../services/lesson-offline'; import { AddonModLessonAutoSyncData, AddonModLessonSync, - AddonModLessonSyncProvider, AddonModLessonSyncResult, } from '../../services/lesson-sync'; -import { AddonModLessonModuleHandlerService } from '../../services/handlers/module'; import { CoreTime } from '@singletons/time'; import { CoreError } from '@classes/errors/error'; import { Translate } from '@singletons'; +import { + ADDON_MOD_LESSON_AUTO_SYNCED, + ADDON_MOD_LESSON_COMPONENT, + ADDON_MOD_LESSON_DATA_SENT_EVENT, + ADDON_MOD_LESSON_PAGE_NAME, +} from '../../constants'; /** * Component that displays a lesson entry page. @@ -65,7 +68,7 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo @Input() group = 0; // The group to display. @Input() action?: string; // The "action" to display first. - component = AddonModLessonProvider.COMPONENT; + component = ADDON_MOD_LESSON_COMPONENT; pluginName = 'lesson'; lesson?: AddonModLessonLessonWSData; // The lesson. @@ -86,7 +89,7 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo hightimeReadable?: string; // High time in a readable format. lowtimeReadable?: string; // Low time in a readable format. - protected syncEventName = AddonModLessonSyncProvider.AUTO_SYNCED; + protected syncEventName = ADDON_MOD_LESSON_AUTO_SYNCED; protected accessInfo?: AddonModLessonGetAccessInformationWSResponse; // Lesson access info. protected password?: string; // The password for the lesson. protected hasPlayed = false; // Whether the user has gone to the lesson player (attempted). @@ -411,7 +414,7 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo } await CoreNavigator.navigateToSitePath( - `${AddonModLessonModuleHandlerService.PAGE_NAME}/${this.courseId}/${this.module.id}/player`, + `${ADDON_MOD_LESSON_PAGE_NAME}/${this.courseId}/${this.module.id}/player`, { params: { pageId: pageId, @@ -424,7 +427,7 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo this.hasPlayed = true; this.dataSentObserver?.off(); - this.dataSentObserver = CoreEvents.on(AddonModLessonProvider.DATA_SENT_EVENT, (data) => { + this.dataSentObserver = CoreEvents.on(ADDON_MOD_LESSON_DATA_SENT_EVENT, (data) => { if (data.lessonId !== this.lesson?.id || data.type === 'launch') { // Ignore launch sending because it only affects timers. return; @@ -480,7 +483,7 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo } await CoreNavigator.navigateToSitePath( - `${AddonModLessonModuleHandlerService.PAGE_NAME}/${this.courseId}/${this.module.id}/player`, + `${ADDON_MOD_LESSON_PAGE_NAME}/${this.courseId}/${this.module.id}/player`, { params: { pageId: this.retakeToReview.pageid, @@ -705,7 +708,7 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo */ async openRetake(userId: number): Promise { CoreNavigator.navigateToSitePath( - `${AddonModLessonModuleHandlerService.PAGE_NAME}/${this.courseId}/${this.module.id}/user-retake/${userId}`, + `${ADDON_MOD_LESSON_PAGE_NAME}/${this.courseId}/${this.module.id}/user-retake/${userId}`, ); } diff --git a/src/addons/mod/lesson/constants.ts b/src/addons/mod/lesson/constants.ts new file mode 100644 index 000000000..98280315b --- /dev/null +++ b/src/addons/mod/lesson/constants.ts @@ -0,0 +1,54 @@ +// (C) Copyright 2015 Moodle Pty Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export const ADDON_MOD_LESSON_COMPONENT = 'mmaModLesson'; + +export const ADDON_MOD_LESSON_PAGE_NAME = 'mod_lesson'; + +export const ADDON_MOD_LESSON_AUTO_SYNCED = 'addon_mod_lesson_autom_synced'; +export const ADDON_MOD_LESSON_DATA_SENT_EVENT = 'addon_mod_lesson_data_sent'; + +export const enum AddonModLessonJumpTo { + THISPAGE = 0, // This page. + UNSEENPAGE = 1, // Next page -> any page not seen before. + UNANSWEREDPAGE = 2, // Next page -> any page not answered correctly. + NEXTPAGE = -1, // Jump to Next Page. + EOL = -9, // End of Lesson. + UNSEENBRANCHPAGE = -50, // Jump to an unseen page within a branch and end of branch or end of lesson. + RANDOMPAGE = -60, // Jump to a random page within a branch and end of branch or end of lesson. + RANDOMBRANCH = -70, // Jump to a random Branch. + CLUSTERJUMP = -80, // Cluster Jump. +} + +// Type of page: question or structure (content). +export const enum AddonModLessonPageType { + QUESTION = 0, + STRUCTURE = 1, +} + +// Type of question pages. +export const enum AddonModLessonPageSubtype { + SHORTANSWER = 1, + TRUEFALSE = 2, + MULTICHOICE = 3, + MATCHING = 5, + NUMERICAL = 8, + ESSAY = 10, + BRANCHTABLE = 20, // Content page. + ENDOFBRANCH = 21, + CLUSTER = 30, + ENDOFCLUSTER = 31 +} + +export const ADDON_MOD_LESSON_OTHER_ANSWERS = '@#wronganswer#@'; diff --git a/src/addons/mod/lesson/lesson-lazy.module.ts b/src/addons/mod/lesson/lesson-lazy.module.ts index 749b6547f..b34ec5667 100644 --- a/src/addons/mod/lesson/lesson-lazy.module.ts +++ b/src/addons/mod/lesson/lesson-lazy.module.ts @@ -53,4 +53,4 @@ const routes: Routes = [ AddonModLessonUserRetakePage, ], }) -export class AddonModLessonLazyModule {} +export default class AddonModLessonLazyModule {} diff --git a/src/addons/mod/lesson/lesson.module.ts b/src/addons/mod/lesson/lesson.module.ts index dd05e9f6e..b0d915237 100644 --- a/src/addons/mod/lesson/lesson.module.ts +++ b/src/addons/mod/lesson/lesson.module.ts @@ -27,17 +27,17 @@ import { SITE_SCHEMA, OFFLINE_SITE_SCHEMA, SYNC_SITE_SCHEMA } from './services/d import { AddonModLessonGradeLinkHandler } from './services/handlers/grade-link'; import { AddonModLessonIndexLinkHandler } from './services/handlers/index-link'; import { AddonModLessonListLinkHandler } from './services/handlers/list-link'; -import { AddonModLessonModuleHandler, AddonModLessonModuleHandlerService } from './services/handlers/module'; +import { AddonModLessonModuleHandler } from './services/handlers/module'; import { AddonModLessonPrefetchHandler } from './services/handlers/prefetch'; import { AddonModLessonPushClickHandler } from './services/handlers/push-click'; import { AddonModLessonReportLinkHandler } from './services/handlers/report-link'; import { AddonModLessonSyncCronHandler } from './services/handlers/sync-cron'; -import { AddonModLessonProvider } from './services/lesson'; +import { ADDON_MOD_LESSON_COMPONENT, ADDON_MOD_LESSON_PAGE_NAME } from './constants'; const routes: Routes = [ { - path: AddonModLessonModuleHandlerService.PAGE_NAME, - loadChildren: () => import('./lesson-lazy.module').then(m => m.AddonModLessonLazyModule), + path: ADDON_MOD_LESSON_PAGE_NAME, + loadChildren: () => import('./lesson-lazy.module'), }, ]; @@ -64,7 +64,7 @@ const routes: Routes = [ CoreContentLinksDelegate.registerHandler(AddonModLessonReportLinkHandler.instance); CorePushNotificationsDelegate.registerClickHandler(AddonModLessonPushClickHandler.instance); - CoreCourseHelper.registerModuleReminderClick(AddonModLessonProvider.COMPONENT); + CoreCourseHelper.registerModuleReminderClick(ADDON_MOD_LESSON_COMPONENT); }, }, ], diff --git a/src/addons/mod/lesson/pages/player/player.ts b/src/addons/mod/lesson/pages/player/player.ts index 668baf5ee..a17c77825 100644 --- a/src/addons/mod/lesson/pages/player/player.ts +++ b/src/addons/mod/lesson/pages/player/player.ts @@ -43,7 +43,6 @@ import { AddonModLessonPossibleJumps, AddonModLessonProcessPageOptions, AddonModLessonProcessPageResponse, - AddonModLessonProvider, } from '../../services/lesson'; import { AddonModLessonActivityLink, @@ -55,6 +54,7 @@ import { AddonModLessonOffline } from '../../services/lesson-offline'; import { AddonModLessonSync } from '../../services/lesson-sync'; import { CoreFormFields, CoreForms } from '@singletons/form'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; +import { ADDON_MOD_LESSON_COMPONENT, AddonModLessonJumpTo } from '../../constants'; /** * Page that allows attempting and reviewing a lesson. @@ -69,8 +69,8 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { @ViewChild(IonContent) content?: IonContent; @ViewChild('questionFormEl') formElement?: ElementRef; - component = AddonModLessonProvider.COMPONENT; - readonly LESSON_EOL = AddonModLessonProvider.LESSON_EOL; + component = ADDON_MOD_LESSON_COMPONENT; + readonly LESSON_EOL = AddonModLessonJumpTo.EOL; questionForm?: FormGroup; // The FormGroup for question pages. title?: string; // The page title. lesson?: AddonModLessonLessonWSData; // The lesson object. @@ -449,7 +449,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { } } - this.logPageLoaded(AddonModLessonProvider.LESSON_EOL, Translate.instant('addon.mod_lesson.congratulations')); + this.logPageLoaded(AddonModLessonJumpTo.EOL, Translate.instant('addon.mod_lesson.congratulations')); } /** @@ -466,7 +466,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { CoreNavigator.back(); return; - } else if (pageId == AddonModLessonProvider.LESSON_EOL) { + } else if (pageId == AddonModLessonJumpTo.EOL) { // End of lesson reached. return this.finishRetake(); } @@ -496,7 +496,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { const finished = await AddonModLessonOffline.hasFinishedRetake(this.lesson!.id); if (finished) { // Always show EOL page. - pageId = AddonModLessonProvider.LESSON_EOL; + pageId = AddonModLessonJumpTo.EOL; } } @@ -556,7 +556,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { * @returns Promise resolved when done. */ protected async loadPage(pageId: number): Promise { - if (pageId == AddonModLessonProvider.LESSON_EOL) { + if (pageId == AddonModLessonJumpTo.EOL) { // End of lesson reached. return this.finishRetake(); } else if (!this.lesson) { @@ -580,7 +580,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { options, ); - if (data.newpageid == AddonModLessonProvider.LESSON_EOL) { + if (data.newpageid == AddonModLessonJumpTo.EOL) { // End of lesson reached. return this.finishRetake(); } diff --git a/src/addons/mod/lesson/pages/user-retake/user-retake.ts b/src/addons/mod/lesson/pages/user-retake/user-retake.ts index 0405044dc..ba3cc1028 100644 --- a/src/addons/mod/lesson/pages/user-retake/user-retake.ts +++ b/src/addons/mod/lesson/pages/user-retake/user-retake.ts @@ -28,13 +28,13 @@ import { AddonModLessonAttemptsOverviewsStudentWSData, AddonModLessonGetUserAttemptWSResponse, AddonModLessonLessonWSData, - AddonModLessonProvider, AddonModLessonUserAttemptAnswerData, AddonModLessonUserAttemptAnswerPageWSData, } from '../../services/lesson'; import { AddonModLessonAnswerData, AddonModLessonHelper } from '../../services/lesson-helper'; import { CoreTime } from '@singletons/time'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; +import { ADDON_MOD_LESSON_COMPONENT } from '../../constants'; /** * Page that displays a retake made by a certain user. @@ -46,7 +46,7 @@ import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; }) export class AddonModLessonUserRetakePage implements OnInit { - component = AddonModLessonProvider.COMPONENT; + component = ADDON_MOD_LESSON_COMPONENT; lesson?: AddonModLessonLessonWSData; // The lesson the retake belongs to. courseId!: number; // Course ID the lesson belongs to. selectedRetake?: number; // The retake to see. diff --git a/src/addons/mod/lesson/services/handlers/grade-link.ts b/src/addons/mod/lesson/services/handlers/grade-link.ts index bc77ca7da..97dc7ab9d 100644 --- a/src/addons/mod/lesson/services/handlers/grade-link.ts +++ b/src/addons/mod/lesson/services/handlers/grade-link.ts @@ -22,7 +22,7 @@ import { CoreSitesReadingStrategy } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { makeSingleton } from '@singletons'; import { AddonModLesson } from '../lesson'; -import { AddonModLessonModuleHandlerService } from './module'; +import { ADDON_MOD_LESSON_PAGE_NAME } from '../../constants'; /** * Handler to treat links to lesson grade. @@ -69,7 +69,7 @@ export class AddonModLessonGradeLinkHandlerService extends CoreContentLinksModul if (accessInfo.canviewreports) { // User can view reports, go to view the report. CoreNavigator.navigateToSitePath( - AddonModLessonModuleHandlerService.PAGE_NAME + `/${module.course}/${module.id}/user-retake/${userId}`, + ADDON_MOD_LESSON_PAGE_NAME + `/${module.course}/${module.id}/user-retake/${userId}`, { siteId, }, diff --git a/src/addons/mod/lesson/services/handlers/module.ts b/src/addons/mod/lesson/services/handlers/module.ts index 16763acc1..32a3157f1 100644 --- a/src/addons/mod/lesson/services/handlers/module.ts +++ b/src/addons/mod/lesson/services/handlers/module.ts @@ -18,6 +18,7 @@ import { CoreConstants, ModPurpose } from '@/core/constants'; import { CoreCourseModuleHandler } from '@features/course/services/module-delegate'; import { makeSingleton } from '@singletons'; import { CoreModuleHandlerBase } from '@features/course/classes/module-base-handler'; +import { ADDON_MOD_LESSON_PAGE_NAME } from '../../constants'; /** * Handler to support lesson modules. @@ -25,11 +26,9 @@ import { CoreModuleHandlerBase } from '@features/course/classes/module-base-hand @Injectable({ providedIn: 'root' }) export class AddonModLessonModuleHandlerService extends CoreModuleHandlerBase implements CoreCourseModuleHandler { - static readonly PAGE_NAME = 'mod_lesson'; - name = 'AddonModLesson'; modName = 'lesson'; - protected pageName = AddonModLessonModuleHandlerService.PAGE_NAME; + protected pageName = ADDON_MOD_LESSON_PAGE_NAME; supportedFeatures = { [CoreConstants.FEATURE_GROUPS]: true, diff --git a/src/addons/mod/lesson/services/handlers/prefetch.ts b/src/addons/mod/lesson/services/handlers/prefetch.ts index f9a7e124e..852a07d58 100644 --- a/src/addons/mod/lesson/services/handlers/prefetch.ts +++ b/src/addons/mod/lesson/services/handlers/prefetch.ts @@ -30,9 +30,9 @@ import { AddonModLessonGetAccessInformationWSResponse, AddonModLessonLessonWSData, AddonModLessonPasswordOptions, - AddonModLessonProvider, } from '../lesson'; import { AddonModLessonSync, AddonModLessonSyncResult } from '../lesson-sync'; +import { ADDON_MOD_LESSON_COMPONENT, AddonModLessonJumpTo, AddonModLessonPageSubtype } from '../../constants'; /** * Handler to prefetch lessons. @@ -42,7 +42,7 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref name = 'AddonModLesson'; modName = 'lesson'; - component = AddonModLessonProvider.COMPONENT; + component = ADDON_MOD_LESSON_COMPONENT; // Don't check timers to decrease positives. If a user performs some action it will be reflected in other items. updatesNames = /^configuration$|^.*files$|^grades$|^gradeitems$|^pages$|^answers$|^questionattempts$|^pagesviewed$/; @@ -351,7 +351,7 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref const promises = pages.map(async (data) => { // Check if any page has a RANDOMBRANCH jump. if (!hasRandomBranch) { - hasRandomBranch = data.jumps.some((jump) => jump === AddonModLessonProvider.LESSON_RANDOMBRANCH); + hasRandomBranch = data.jumps.some((jump) => jump === AddonModLessonJumpTo.RANDOMBRANCH); } // Get the page data. We don't pass accessInfo because we don't need to calculate the offline data. @@ -464,7 +464,7 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref // Download embedded files in essays. const files: CoreWSFile[] = []; attempt.answerpages.forEach((answerPage) => { - if (!answerPage.page || answerPage.page.qtype != AddonModLessonProvider.LESSON_PAGE_ESSAY) { + if (!answerPage.page || answerPage.page.qtype !== AddonModLessonPageSubtype.ESSAY) { return; } diff --git a/src/addons/mod/lesson/services/handlers/report-link.ts b/src/addons/mod/lesson/services/handlers/report-link.ts index 92d432b18..de1955316 100644 --- a/src/addons/mod/lesson/services/handlers/report-link.ts +++ b/src/addons/mod/lesson/services/handlers/report-link.ts @@ -21,7 +21,7 @@ import { CoreNavigator } from '@services/navigator'; import { CoreSitesReadingStrategy } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { makeSingleton } from '@singletons'; -import { AddonModLessonModuleHandlerService } from './module'; +import { ADDON_MOD_LESSON_PAGE_NAME } from '../../constants'; /** * Handler to treat links to lesson report. @@ -106,7 +106,7 @@ export class AddonModLessonReportLinkHandlerService extends CoreContentLinksHand }; CoreNavigator.navigateToSitePath( - `${AddonModLessonModuleHandlerService.PAGE_NAME}/${module.course}/${module.id}`, + `${ADDON_MOD_LESSON_PAGE_NAME}/${module.course}/${module.id}`, { params, siteId }, ); } catch (error) { @@ -145,7 +145,7 @@ export class AddonModLessonReportLinkHandlerService extends CoreContentLinksHand }; CoreNavigator.navigateToSitePath( - AddonModLessonModuleHandlerService.PAGE_NAME + `/${module.course}/${module.id}/user-retake/${userId}`, + ADDON_MOD_LESSON_PAGE_NAME + `/${module.course}/${module.id}/user-retake/${userId}`, { params, siteId }, ); } catch (error) { diff --git a/src/addons/mod/lesson/services/lesson-helper.ts b/src/addons/mod/lesson/services/lesson-helper.ts index 7c7666792..9398f2b74 100644 --- a/src/addons/mod/lesson/services/lesson-helper.ts +++ b/src/addons/mod/lesson/services/lesson-helper.ts @@ -24,10 +24,10 @@ import { AddonModLesson, AddonModLessonAttemptsOverviewsAttemptWSData, AddonModLessonGetPageDataWSResponse, - AddonModLessonProvider, } from './lesson'; import { CoreTime } from '@singletons/time'; import { CoreUtils } from '@services/utils/utils'; +import { AddonModLessonPageSubtype } from '../constants'; /** * Helper service that provides some features for quiz. @@ -161,7 +161,7 @@ export class AddonModLessonHelperProvider { // Cannot find contents element. if (AddonModLesson.isQuestionPage(data.page?.type || -1) || - data.page?.qtype == AddonModLessonProvider.LESSON_PAGE_BRANCHTABLE) { + data.page?.qtype == AddonModLessonPageSubtype.BRANCHTABLE) { // Return page.contents to prevent having duplicated elements (some elements like videos might not work). return data.page?.contents || ''; } else { @@ -202,19 +202,19 @@ export class AddonModLessonHelperProvider { } switch (pageData.page?.qtype) { - case AddonModLessonProvider.LESSON_PAGE_TRUEFALSE: - case AddonModLessonProvider.LESSON_PAGE_MULTICHOICE: + case AddonModLessonPageSubtype.TRUEFALSE: + case AddonModLessonPageSubtype.MULTICHOICE: return this.getMultiChoiceQuestionData(questionForm, question, fieldContainer); - case AddonModLessonProvider.LESSON_PAGE_NUMERICAL: - case AddonModLessonProvider.LESSON_PAGE_SHORTANSWER: + case AddonModLessonPageSubtype.NUMERICAL: + case AddonModLessonPageSubtype.SHORTANSWER: return this.getInputQuestionData(questionForm, question, fieldContainer, pageData.page.qtype); - case AddonModLessonProvider.LESSON_PAGE_ESSAY: { + case AddonModLessonPageSubtype.ESSAY: { return this.getEssayQuestionData(questionForm, question, fieldContainer); } - case AddonModLessonProvider.LESSON_PAGE_MATCHING: { + case AddonModLessonPageSubtype.MATCHING: { return this.getMatchingQuestionData(questionForm, question, fieldContainer); } } @@ -332,7 +332,7 @@ export class AddonModLessonHelperProvider { // Init the control. questionForm.addControl(input.name, this.formBuilder.control({ - value: questionType === AddonModLessonProvider.LESSON_PAGE_NUMERICAL ? CoreUtils.formatFloat(input.value) : input.value, + value: questionType === AddonModLessonPageSubtype.NUMERICAL ? CoreUtils.formatFloat(input.value) : input.value, disabled: input.readOnly, })); @@ -597,7 +597,6 @@ export class AddonModLessonHelperProvider { } } - export const AddonModLessonHelper = makeSingleton(AddonModLessonHelperProvider); /** diff --git a/src/addons/mod/lesson/services/lesson-offline.ts b/src/addons/mod/lesson/services/lesson-offline.ts index 24af2b3f7..5e50397db 100644 --- a/src/addons/mod/lesson/services/lesson-offline.ts +++ b/src/addons/mod/lesson/services/lesson-offline.ts @@ -26,7 +26,8 @@ import { RETAKES_TABLE_NAME, } from './database/lesson'; -import { AddonModLessonPageWSData, AddonModLessonProvider } from './lesson'; +import { AddonModLessonPageWSData } from './lesson'; +import { AddonModLessonPageType } from '../constants'; /** * Service to handle offline lesson. @@ -256,7 +257,7 @@ export class AddonModLessonOfflineProvider { ): Promise { const attempts = pageId ? await this.getRetakeAttemptsForPage(lessonId, retake, pageId, siteId) : - await this.getRetakeAttemptsForType(lessonId, retake, AddonModLessonProvider.TYPE_QUESTION, siteId); + await this.getRetakeAttemptsForType(lessonId, retake, AddonModLessonPageType.QUESTION, siteId); if (correct) { return attempts.filter((attempt) => !!attempt.correct); @@ -514,7 +515,7 @@ export class AddonModLessonOfflineProvider { await site.getDb().insertRecord(PAGE_ATTEMPTS_TABLE_NAME, entry); - if (page.type == AddonModLessonProvider.TYPE_QUESTION) { + if (page.type == AddonModLessonPageType.QUESTION) { // It's a question page, set it as last question page attempted. await this.setLastQuestionPageAttempted(lessonId, courseId, retake, page.id, siteId); } diff --git a/src/addons/mod/lesson/services/lesson-sync.ts b/src/addons/mod/lesson/services/lesson-sync.ts index adf4eb126..22da5ab5a 100644 --- a/src/addons/mod/lesson/services/lesson-sync.ts +++ b/src/addons/mod/lesson/services/lesson-sync.ts @@ -29,8 +29,9 @@ import { makeSingleton, Translate } from '@singletons'; import { CoreEvents } from '@singletons/events'; import { AddonModLessonRetakeFinishedInSyncDBRecord, RETAKES_FINISHED_SYNC_TABLE_NAME } from './database/lesson'; import { AddonModLessonGetPasswordResult, AddonModLessonPrefetchHandler } from './handlers/prefetch'; -import { AddonModLesson, AddonModLessonLessonWSData, AddonModLessonProvider } from './lesson'; +import { AddonModLesson, AddonModLessonLessonWSData } from './lesson'; import { AddonModLessonOffline, AddonModLessonPageAttemptRecord } from './lesson-offline'; +import { ADDON_MOD_LESSON_AUTO_SYNCED, ADDON_MOD_LESSON_COMPONENT } from '../constants'; /** * Service to sync lesson. @@ -38,8 +39,6 @@ import { AddonModLessonOffline, AddonModLessonPageAttemptRecord } from './lesson @Injectable({ providedIn: 'root' }) export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvider { - static readonly AUTO_SYNCED = 'addon_mod_lesson_autom_synced'; - protected componentTranslatableString = 'lesson'; constructor() { @@ -144,7 +143,7 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid if (result?.updated) { // Sync successful, send event. - CoreEvents.trigger(AddonModLessonSyncProvider.AUTO_SYNCED, { + CoreEvents.trigger(ADDON_MOD_LESSON_AUTO_SYNCED, { lessonId: lesson.id, warnings: result.warnings, }, siteId); @@ -196,7 +195,7 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid } // Verify that lesson isn't blocked. - if (!ignoreBlock && CoreSync.isBlocked(AddonModLessonProvider.COMPONENT, lessonId, siteId)) { + if (!ignoreBlock && CoreSync.isBlocked(ADDON_MOD_LESSON_COMPONENT, lessonId, siteId)) { this.logger.debug('Cannot sync lesson ' + lessonId + ' because it is blocked.'); throw new CoreSyncBlockedError(Translate.instant('core.errorsyncblocked', { $a: this.componentTranslate })); @@ -226,7 +225,7 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid ): Promise { // Sync offline logs. await CoreUtils.ignoreErrors( - CoreCourseLogHelper.syncActivity(AddonModLessonProvider.COMPONENT, lessonId, siteId), + CoreCourseLogHelper.syncActivity(ADDON_MOD_LESSON_COMPONENT, lessonId, siteId), ); const result: AddonModLessonSyncResult = { diff --git a/src/addons/mod/lesson/services/lesson.ts b/src/addons/mod/lesson/services/lesson.ts index 37ce3389d..1fc068f10 100644 --- a/src/addons/mod/lesson/services/lesson.ts +++ b/src/addons/mod/lesson/services/lesson.ts @@ -17,7 +17,6 @@ import { CoreError } from '@classes/errors/error'; import { CoreSite } from '@classes/sites/site'; import { CoreCourseCommonModWSOptions } from '@features/course/services/course'; import { CoreCourseLogHelper } from '@features/course/services/log-helper'; -import { CoreGradesProvider } from '@features/grades/services/grades'; import { CoreSites, CoreSitesCommonWSOptions, CoreSitesReadingStrategy } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { CoreTextUtils } from '@services/utils/text'; @@ -27,10 +26,18 @@ import { makeSingleton, Translate } from '@singletons'; import { CoreEvents } from '@singletons/events'; import { AddonModLessonPasswordDBRecord, PASSWORD_TABLE_NAME } from './database/lesson'; import { AddonModLessonOffline, AddonModLessonPageAttemptRecord } from './lesson-offline'; -import { AddonModLessonAutoSyncData, AddonModLessonSyncProvider } from './lesson-sync'; +import { AddonModLessonAutoSyncData } from './lesson-sync'; import { CoreSiteWSPreSets } from '@classes/sites/authenticated-site'; - -const ROOT_CACHE_KEY = 'mmaModLesson:'; +import { + ADDON_MOD_LESSON_AUTO_SYNCED, + ADDON_MOD_LESSON_COMPONENT, + ADDON_MOD_LESSON_DATA_SENT_EVENT, + ADDON_MOD_LESSON_OTHER_ANSWERS, + AddonModLessonJumpTo, + AddonModLessonPageType, + AddonModLessonPageSubtype, +} from '../constants'; +import { CoreGradeType } from '@features/grades/constants'; declare module '@singletons/events' { @@ -40,8 +47,8 @@ declare module '@singletons/events' { * @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation */ export interface CoreEventsData { - [AddonModLessonProvider.DATA_SENT_EVENT]: AddonModLessonDataSentData; - [AddonModLessonSyncProvider.AUTO_SYNCED]: AddonModLessonAutoSyncData; + [ADDON_MOD_LESSON_DATA_SENT_EVENT]: AddonModLessonDataSentData; + [ADDON_MOD_LESSON_AUTO_SYNCED]: AddonModLessonAutoSyncData; } } @@ -61,37 +68,9 @@ declare module '@singletons/events' { @Injectable({ providedIn: 'root' }) export class AddonModLessonProvider { - static readonly COMPONENT = 'mmaModLesson'; - static readonly DATA_SENT_EVENT = 'addon_mod_lesson_data_sent'; + protected static readonly ROOT_CACHE_KEY = 'mmaModLesson:'; - static readonly LESSON_THISPAGE = 0; // This page. - static readonly LESSON_UNSEENPAGE = 1; // Next page -> any page not seen before. - static readonly LESSON_UNANSWEREDPAGE = 2; // Next page -> any page not answered correctly. - static readonly LESSON_NEXTPAGE = -1; // Jump to Next Page. - static readonly LESSON_EOL = -9; // End of Lesson. - static readonly LESSON_UNSEENBRANCHPAGE = -50; // Jump to an unseen page within a branch and end of branch or end of lesson. - static readonly LESSON_RANDOMPAGE = -60; // Jump to a random page within a branch and end of branch or end of lesson. - static readonly LESSON_RANDOMBRANCH = -70; // Jump to a random Branch. - static readonly LESSON_CLUSTERJUMP = -80; // Cluster Jump. - - // Type of page: question or structure (content). - static readonly TYPE_QUESTION = 0; - static readonly TYPE_STRUCTURE = 1; - - // Type of question pages. - static readonly LESSON_PAGE_SHORTANSWER = 1; - static readonly LESSON_PAGE_TRUEFALSE = 2; - static readonly LESSON_PAGE_MULTICHOICE = 3; - static readonly LESSON_PAGE_MATCHING = 5; - static readonly LESSON_PAGE_NUMERICAL = 8; - static readonly LESSON_PAGE_ESSAY = 10; - static readonly LESSON_PAGE_BRANCHTABLE = 20; // Content page. - static readonly LESSON_PAGE_ENDOFBRANCH = 21; - static readonly LESSON_PAGE_CLUSTER = 30; - static readonly LESSON_PAGE_ENDOFCLUSTER = 31; - - static readonly MULTIANSWER_DELIMITER = '@^#|'; // Constant used as a delimiter when parsing multianswer questions. - static readonly LESSON_OTHER_ANSWERS = '@#wronganswer#@'; + protected static readonly MULTIANSWER_DELIMITER = '@^#|'; // Constant used as a delimiter when parsing multianswer questions. /** * Add an answer and its response to a feedback string (HTML). @@ -359,33 +338,33 @@ export class AddonModLessonProvider { }; switch (pageData.page!.qtype) { - case AddonModLessonProvider.LESSON_PAGE_BRANCHTABLE: + case AddonModLessonPageSubtype.BRANCHTABLE: // Load the new page immediately. result.inmediatejump = true; result.newpageid = this.getNewPageId(pageData.page!.id, data.jumpto, jumps); break; - case AddonModLessonProvider.LESSON_PAGE_ESSAY: + case AddonModLessonPageSubtype.ESSAY: this.checkAnswerEssay(pageData, data, result); break; - case AddonModLessonProvider.LESSON_PAGE_MATCHING: + case AddonModLessonPageSubtype.MATCHING: this.checkAnswerMatching(pageData, data, result); break; - case AddonModLessonProvider.LESSON_PAGE_MULTICHOICE: + case AddonModLessonPageSubtype.MULTICHOICE: this.checkAnswerMultichoice(lesson, pageData, data, pageIndex, result); break; - case AddonModLessonProvider.LESSON_PAGE_NUMERICAL: + case AddonModLessonPageSubtype.NUMERICAL: this.checkAnswerNumerical(lesson, pageData, data, pageIndex, result); break; - case AddonModLessonProvider.LESSON_PAGE_SHORTANSWER: + case AddonModLessonPageSubtype.SHORTANSWER: this.checkAnswerShort(lesson, pageData, data, pageIndex, result); break; - case AddonModLessonProvider.LESSON_PAGE_TRUEFALSE: + case AddonModLessonPageSubtype.TRUEFALSE: this.checkAnswerTruefalse(lesson, pageData, data, pageIndex, result); break; default: @@ -912,7 +891,7 @@ export class AddonModLessonProvider { // Double check that this is the OTHER_ANSWERS answer. if (typeof lastAnswer.answer == 'string' && - lastAnswer.answer.indexOf(AddonModLessonProvider.LESSON_OTHER_ANSWERS) != -1) { + lastAnswer.answer.indexOf(ADDON_MOD_LESSON_OTHER_ANSWERS) !== -1) { result.newpageid = lastAnswer.jumpto || 0; result.response = lastAnswer.response || ''; @@ -961,7 +940,7 @@ export class AddonModLessonProvider { const response = await this.finishRetakeOnline(lesson.id, options); - CoreEvents.trigger(AddonModLessonProvider.DATA_SENT_EVENT, { + CoreEvents.trigger(ADDON_MOD_LESSON_DATA_SENT_EVENT, { lessonId: lesson.id, type: 'finish', courseId: courseId, @@ -1128,7 +1107,7 @@ export class AddonModLessonProvider { this.addResultValueEolPage(result, 'displayscorewithoutessays', entryData, true); } - if (lesson.grade !== undefined && lesson.grade != CoreGradesProvider.TYPE_NONE) { + if (lesson.grade !== undefined && lesson.grade !== CoreGradeType.NONE) { entryData.grade = CoreTextUtils.roundToDecimals(gradeInfo.grade * lesson.grade / 100, 1); entryData.total = lesson.grade; this.addResultValueEolPage(result, 'yourcurrentgradeisoutof', entryData, true); @@ -1147,7 +1126,7 @@ export class AddonModLessonProvider { } } else { // Display for teacher. - if (lesson.grade != CoreGradesProvider.TYPE_NONE) { + if (lesson.grade !== CoreGradeType.NONE) { this.addResultValueEolPage(result, 'displayofgrade', true, true); } } @@ -1182,7 +1161,7 @@ export class AddonModLessonProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getAccessInformationCacheKey(lessonId), updateFrequency: CoreSite.FREQUENCY_OFTEN, - component: AddonModLessonProvider.COMPONENT, + component: ADDON_MOD_LESSON_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -1197,7 +1176,7 @@ export class AddonModLessonProvider { * @returns Cache key. */ protected getAccessInformationCacheKey(lessonId: number): string { - return ROOT_CACHE_KEY + 'accessInfo:' + lessonId; + return AddonModLessonProvider.ROOT_CACHE_KEY + 'accessInfo:' + lessonId; } /** @@ -1213,7 +1192,7 @@ export class AddonModLessonProvider { retake: number, options: CoreCourseCommonModWSOptions = {}, ): Promise<{online: AddonModLessonWSContentPageViewed[]; offline: AddonModLessonPageAttemptRecord[]}> { - const type = AddonModLessonProvider.TYPE_STRUCTURE; + const type = AddonModLessonPageType.STRUCTURE; const [online, offline] = await Promise.all([ this.getContentPagesViewedOnline(lessonId, retake, options), @@ -1246,7 +1225,7 @@ export class AddonModLessonProvider { * @returns Cache key. */ protected getContentPagesViewedCommonCacheKey(lessonId: number): string { - return ROOT_CACHE_KEY + 'contentPagesViewed:' + lessonId; + return AddonModLessonProvider.ROOT_CACHE_KEY + 'contentPagesViewed:' + lessonId; } /** @@ -1298,7 +1277,7 @@ export class AddonModLessonProvider { }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getContentPagesViewedCacheKey(lessonId, retake), - component: AddonModLessonProvider.COMPONENT, + component: ADDON_MOD_LESSON_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -1431,7 +1410,7 @@ export class AddonModLessonProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getLessonDataCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, - component: AddonModLessonProvider.COMPONENT, + component: ADDON_MOD_LESSON_COMPONENT, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -1469,7 +1448,7 @@ export class AddonModLessonProvider { * @returns Cache key. */ protected getLessonDataCacheKey(courseId: number): string { - return ROOT_CACHE_KEY + 'lesson:' + courseId; + return AddonModLessonProvider.ROOT_CACHE_KEY + 'lesson:' + courseId; } /** @@ -1492,7 +1471,7 @@ export class AddonModLessonProvider { }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getLessonWithPasswordCacheKey(lessonId), - component: AddonModLessonProvider.COMPONENT, + component: ADDON_MOD_LESSON_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -1525,7 +1504,7 @@ export class AddonModLessonProvider { * @returns Cache key. */ protected getLessonWithPasswordCacheKey(lessonId: number): string { - return ROOT_CACHE_KEY + 'lessonWithPswrd:' + lessonId; + return AddonModLessonProvider.ROOT_CACHE_KEY + 'lessonWithPswrd:' + lessonId; } /** @@ -1661,7 +1640,7 @@ export class AddonModLessonProvider { }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getPageDataCacheKey(lesson.id, pageId), - component: AddonModLessonProvider.COMPONENT, + component: ADDON_MOD_LESSON_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -1712,7 +1691,7 @@ export class AddonModLessonProvider { * @returns Cache key. */ protected getPageDataCommonCacheKey(lessonId: number): string { - return ROOT_CACHE_KEY + 'pageData:' + lessonId; + return AddonModLessonProvider.ROOT_CACHE_KEY + 'pageData:' + lessonId; } /** @@ -1732,7 +1711,7 @@ export class AddonModLessonProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getPagesCacheKey(lessonId), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, - component: AddonModLessonProvider.COMPONENT, + component: ADDON_MOD_LESSON_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -1753,7 +1732,7 @@ export class AddonModLessonProvider { * @returns Cache key. */ protected getPagesCacheKey(lessonId: number): string { - return ROOT_CACHE_KEY + 'pages:' + lessonId; + return AddonModLessonProvider.ROOT_CACHE_KEY + 'pages:' + lessonId; } /** @@ -1775,7 +1754,7 @@ export class AddonModLessonProvider { }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getPagesPossibleJumpsCacheKey(lessonId), - component: AddonModLessonProvider.COMPONENT, + component: ADDON_MOD_LESSON_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -1806,7 +1785,7 @@ export class AddonModLessonProvider { * @returns Cache key. */ protected getPagesPossibleJumpsCacheKey(lessonId: number): string { - return ROOT_CACHE_KEY + 'pagesJumps:' + lessonId; + return AddonModLessonProvider.ROOT_CACHE_KEY + 'pagesJumps:' + lessonId; } /** @@ -1905,7 +1884,7 @@ export class AddonModLessonProvider { const messages: AddonModLessonMessageWSData[] = []; if (!accessInfo.canmanage) { - if (page.qtype == AddonModLessonProvider.LESSON_PAGE_BRANCHTABLE && lesson.minquestions) { + if (page.qtype === AddonModLessonPageSubtype.BRANCHTABLE && lesson.minquestions) { // Tell student how many questions they have seen, how many are required and their grade. const retake = accessInfo.attemptscount; @@ -1923,7 +1902,7 @@ export class AddonModLessonProvider { if (!options.review && !lesson.retake) { this.addMessage(messages, 'addon.mod_lesson.numberofcorrectanswers', { $a: gradeInfo.earned }); - if (lesson.grade !== undefined && lesson.grade != CoreGradesProvider.TYPE_NONE) { + if (lesson.grade !== undefined && lesson.grade !== CoreGradeType.NONE) { this.addMessage(messages, 'addon.mod_lesson.yourcurrentgradeisoutof', { $a: { grade: CoreTextUtils.roundToDecimals(gradeInfo.grade * lesson.grade / 100, 1), total: lesson.grade, @@ -2001,7 +1980,7 @@ export class AddonModLessonProvider { * @returns Cache key. */ protected getQuestionsAttemptsCommonCacheKey(lessonId: number): string { - return ROOT_CACHE_KEY + 'questionsAttempts:' + lessonId; + return AddonModLessonProvider.ROOT_CACHE_KEY + 'questionsAttempts:' + lessonId; } /** @@ -2030,7 +2009,7 @@ export class AddonModLessonProvider { }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getQuestionsAttemptsCacheKey(lessonId, retake, userId), - component: AddonModLessonProvider.COMPONENT, + component: ADDON_MOD_LESSON_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -2081,7 +2060,7 @@ export class AddonModLessonProvider { const preSets = { cacheKey: this.getRetakesOverviewCacheKey(lessonId, groupId), updateFrequency: CoreSite.FREQUENCY_OFTEN, - component: AddonModLessonProvider.COMPONENT, + component: ADDON_MOD_LESSON_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -2113,7 +2092,7 @@ export class AddonModLessonProvider { * @returns Cache key. */ protected getRetakesOverviewCommonCacheKey(lessonId: number): string { - return ROOT_CACHE_KEY + 'retakesOverview:' + lessonId; + return AddonModLessonProvider.ROOT_CACHE_KEY + 'retakesOverview:' + lessonId; } /** @@ -2173,7 +2152,7 @@ export class AddonModLessonProvider { }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getTimersCacheKey(lessonId, userId), - component: AddonModLessonProvider.COMPONENT, + component: ADDON_MOD_LESSON_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -2201,7 +2180,7 @@ export class AddonModLessonProvider { * @returns Cache key. */ protected getTimersCommonCacheKey(lessonId: number): string { - return ROOT_CACHE_KEY + 'timers:' + lessonId; + return AddonModLessonProvider.ROOT_CACHE_KEY + 'timers:' + lessonId; } /** @@ -2295,7 +2274,7 @@ export class AddonModLessonProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getUserRetakeCacheKey(lessonId, userId, retake), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, - component: AddonModLessonProvider.COMPONENT, + component: ADDON_MOD_LESSON_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -2333,7 +2312,7 @@ export class AddonModLessonProvider { * @returns Cache key. */ protected getUserRetakeLessonCacheKey(lessonId: number): string { - return ROOT_CACHE_KEY + 'userRetake:' + lessonId; + return AddonModLessonProvider.ROOT_CACHE_KEY + 'userRetake:' + lessonId; } /** @@ -2390,15 +2369,15 @@ export class AddonModLessonProvider { if (!jumpTo) { // Same page return false; - } else if (jumpTo == AddonModLessonProvider.LESSON_NEXTPAGE) { + } else if (jumpTo == AddonModLessonJumpTo.NEXTPAGE) { return true; - } else if (jumpTo == AddonModLessonProvider.LESSON_UNSEENBRANCHPAGE) { + } else if (jumpTo == AddonModLessonJumpTo.UNSEENBRANCHPAGE) { return true; - } else if (jumpTo == AddonModLessonProvider.LESSON_RANDOMPAGE) { + } else if (jumpTo == AddonModLessonJumpTo.RANDOMPAGE) { return true; - } else if (jumpTo == AddonModLessonProvider.LESSON_CLUSTERJUMP) { + } else if (jumpTo == AddonModLessonJumpTo.CLUSTERJUMP) { return true; - } else if (jumpTo == AddonModLessonProvider.LESSON_EOL) { + } else if (jumpTo == AddonModLessonJumpTo.EOL) { return true; } @@ -2719,7 +2698,7 @@ export class AddonModLessonProvider { * @returns True if question page, false if content page. */ isQuestionPage(type: number): boolean { - return type == AddonModLessonProvider.TYPE_QUESTION; + return type === AddonModLessonPageType.QUESTION; } /** @@ -2754,7 +2733,7 @@ export class AddonModLessonProvider { const response = await site.write('mod_lesson_launch_attempt', params); - CoreEvents.trigger(AddonModLessonProvider.DATA_SENT_EVENT, { + CoreEvents.trigger(ADDON_MOD_LESSON_DATA_SENT_EVENT, { lessonId: id, type: 'launch', }, CoreSites.getCurrentSiteId()); @@ -2769,7 +2748,7 @@ export class AddonModLessonProvider { * @returns True if left during timed, false otherwise. */ leftDuringTimed(info?: AddonModLessonGetAccessInformationWSResponse): boolean { - return !!(info?.lastpageseen && info.lastpageseen != AddonModLessonProvider.LESSON_EOL && info.leftduringtimedsession); + return !!(info?.lastpageseen && info.lastpageseen != AddonModLessonJumpTo.EOL && info.leftduringtimedsession); } /** @@ -2789,8 +2768,8 @@ export class AddonModLessonProvider { for (const jumpto in jumps[pageId]) { const jumptoNum = Number(jumpto); - if (jumptoNum == AddonModLessonProvider.LESSON_CLUSTERJUMP || - jumptoNum == AddonModLessonProvider.LESSON_UNSEENBRANCHPAGE) { + if (jumptoNum == AddonModLessonJumpTo.CLUSTERJUMP || + jumptoNum == AddonModLessonJumpTo.UNSEENBRANCHPAGE) { return true; } } @@ -2885,7 +2864,7 @@ export class AddonModLessonProvider { if (lesson.custom) { // If essay question, handle it, otherwise add to score. - if (options.pageIndex[lastAttempt.pageid].qtype == AddonModLessonProvider.LESSON_PAGE_ESSAY) { + if (options.pageIndex[lastAttempt.pageid].qtype === AddonModLessonPageSubtype.ESSAY) { // eslint-disable-next-line @typescript-eslint/no-explicit-any const score: number | undefined = ( lastAttempt.useranswer)?.score; if (score !== undefined) { @@ -2902,7 +2881,7 @@ export class AddonModLessonProvider { }); // If essay question, increase numbers. - if (options.pageIndex[lastAttempt.pageid].qtype == AddonModLessonProvider.LESSON_PAGE_ESSAY) { + if (options.pageIndex[lastAttempt.pageid].qtype === AddonModLessonPageSubtype.ESSAY) { result.nmanual++; result.manualpoints++; } @@ -2967,7 +2946,7 @@ export class AddonModLessonProvider { await CoreCourseLogHelper.log( 'mod_lesson_view_lesson', params, - AddonModLessonProvider.COMPONENT, + ADDON_MOD_LESSON_COMPONENT, id, siteId, ); @@ -3002,7 +2981,7 @@ export class AddonModLessonProvider { if (!options.offline) { const response = await this.processPageOnline(lesson.id, pageId, data, options); - CoreEvents.trigger(AddonModLessonProvider.DATA_SENT_EVENT, { + CoreEvents.trigger(ADDON_MOD_LESSON_DATA_SENT_EVENT, { lessonId: lesson.id, type: 'process', courseId: courseId, @@ -3158,7 +3137,7 @@ export class AddonModLessonProvider { // Processes inmediate jumps. if (result.inmediatejump) { - if (pageData.page?.qtype == AddonModLessonProvider.LESSON_PAGE_BRANCHTABLE) { + if (pageData.page?.qtype === AddonModLessonPageSubtype.BRANCHTABLE) { // Store the content page data. In Moodle this is stored in a separate table, during checkAnswer. await AddonModLessonOffline.processPage( lesson.id, @@ -3204,7 +3183,7 @@ export class AddonModLessonProvider { if (lesson.maxattempts && lesson.maxattempts > 0 && nAttempts >= lesson.maxattempts) { result.maxattemptsreached = true; result.feedback = Translate.instant('addon.mod_lesson.maximumnumberofattemptsreached'); - result.newpageid = AddonModLessonProvider.LESSON_NEXTPAGE; + result.newpageid = AddonModLessonJumpTo.NEXTPAGE; return result; } @@ -3238,7 +3217,7 @@ export class AddonModLessonProvider { if (lesson.maxattempts > 1) { // Don't bother with message if only one attempt. result.maxattemptsreached = true; } - result.newpageid = AddonModLessonProvider.LESSON_NEXTPAGE; + result.newpageid = AddonModLessonJumpTo.NEXTPAGE; } else if (lesson.maxattempts && lesson.maxattempts > 1) { // Don't show message if only one attempt or unlimited. result.attemptsremaining = lesson.maxattempts - nAttempts; } @@ -3382,15 +3361,15 @@ export class AddonModLessonProvider { viewedPagesIds: number[], ): number { - if (page.qtype != AddonModLessonProvider.LESSON_PAGE_ENDOFCLUSTER && - page.qtype != AddonModLessonProvider.LESSON_PAGE_ENDOFBRANCH) { + if (page.qtype !== AddonModLessonPageSubtype.ENDOFCLUSTER && + page.qtype !== AddonModLessonPageSubtype.ENDOFBRANCH) { // Add this page as a valid page. validPages[page.id] = 1; } - if (page.qtype == AddonModLessonProvider.LESSON_PAGE_CLUSTER) { + if (page.qtype === AddonModLessonPageSubtype.CLUSTER) { // Get list of pages in the cluster. - const subPages = this.getSubpagesOf(pages, page.id, [AddonModLessonProvider.LESSON_PAGE_ENDOFCLUSTER]); + const subPages = this.getSubpagesOf(pages, page.id, [AddonModLessonPageSubtype.ENDOFCLUSTER]); subPages.forEach((subPage) => { const position = viewedPagesIds.indexOf(subPage.id); @@ -3817,7 +3796,7 @@ export type AddonModLessonPageWSData = { lessonid: number; // The id of the lesson this page belongs to. prevpageid: number; // The id of the page before this one. nextpageid: number; // The id of the next page in the page sequence. - qtype: number; // Identifies the page type of this page. + qtype: AddonModLessonPageSubtype; // Identifies the page type of this page. qoption: number; // Used to record page type specific options. layout: number; // Used to record page specific layout selections. display: number; // Used to record page specific display selections. @@ -3827,7 +3806,7 @@ export type AddonModLessonPageWSData = { contents?: string; // The contents of this page. contentsformat?: number; // Contents format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN). displayinmenublock: boolean; // Toggles display in the left menu block. - type: number; // The type of the page [question | structure]. + type: AddonModLessonPageType; // The type of the page [question | structure]. typeid: number; // The unique identifier for the page type. typestring: string; // The string that describes this page type. }; diff --git a/src/core/features/grades/constants.ts b/src/core/features/grades/constants.ts new file mode 100644 index 000000000..141ffae54 --- /dev/null +++ b/src/core/features/grades/constants.ts @@ -0,0 +1,20 @@ +// (C) Copyright 2015 Moodle Pty Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export const enum CoreGradeType { + NONE = 0, // Moodle's GRADE_TYPE_NONE. + VALUE = 1, // Moodle's GRADE_TYPE_VALUE. + SCALE = 2, // Moodle's GRADE_TYPE_SCALE. + TEXT = 3, // Moodle's GRADE_TYPE_TEXT. +} diff --git a/src/core/features/grades/services/grades.ts b/src/core/features/grades/services/grades.ts index 789fe0df2..24e8a3c86 100644 --- a/src/core/features/grades/services/grades.ts +++ b/src/core/features/grades/services/grades.ts @@ -21,6 +21,7 @@ import { CoreWSExternalWarning } from '@services/ws'; import { CoreSiteWSPreSets } from '@classes/sites/authenticated-site'; import { CoreError } from '@classes/errors/error'; import { SafeNumber } from '@/core/utils/types'; +import { CoreGradeType } from '../constants'; /** * Service to provide grade functionalities. @@ -28,12 +29,12 @@ import { SafeNumber } from '@/core/utils/types'; @Injectable({ providedIn: 'root' }) export class CoreGradesProvider { - static readonly TYPE_NONE = 0; // Moodle's GRADE_TYPE_NONE. - static readonly TYPE_VALUE = 1; // Moodle's GRADE_TYPE_VALUE. - static readonly TYPE_SCALE = 2; // Moodle's GRADE_TYPE_SCALE. - static readonly TYPE_TEXT = 3; // Moodle's GRADE_TYPE_TEXT. + static readonly TYPE_NONE = CoreGradeType.NONE; + static readonly TYPE_VALUE = CoreGradeType.VALUE; + static readonly TYPE_SCALE = CoreGradeType.SCALE; + static readonly TYPE_TEXT = CoreGradeType.TEXT; - protected readonly ROOT_CACHE_KEY = 'mmGrades:'; + protected static readonly ROOT_CACHE_KEY = 'mmGrades:'; protected logger: CoreLogger; @@ -73,7 +74,7 @@ export class CoreGradesProvider { * @returns Cache key. */ protected getCourseGradesPrefixCacheKey(courseId: number): string { - return this.ROOT_CACHE_KEY + 'items:' + courseId + ':'; + return CoreGradesProvider.ROOT_CACHE_KEY + 'items:' + courseId + ':'; } /** @@ -92,7 +93,7 @@ export class CoreGradesProvider { * @returns Cache key. */ protected getCoursesGradesCacheKey(): string { - return this.ROOT_CACHE_KEY + 'coursesgrades'; + return CoreGradesProvider.ROOT_CACHE_KEY + 'coursesgrades'; } /** From 346e3d8d5771b65c8927641f0cfc42bf0de89388 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Thu, 11 Jul 2024 16:41:34 +0200 Subject: [PATCH 03/26] MOBILE-4616 survey: Move survey constants to a file --- .../mod/survey/components/index/index.ts | 7 +++---- src/addons/mod/survey/constants.ts | 2 ++ .../survey/services/handlers/prefetch-lazy.ts | 5 +++-- src/addons/mod/survey/services/survey-sync.ts | 11 +++++------ src/addons/mod/survey/services/survey.ts | 18 ++++++++---------- src/addons/mod/survey/survey-lazy.module.ts | 2 +- src/addons/mod/survey/survey.module.ts | 2 +- 7 files changed, 23 insertions(+), 24 deletions(-) diff --git a/src/addons/mod/survey/components/index/index.ts b/src/addons/mod/survey/components/index/index.ts index e7570b19f..0d8a4b583 100644 --- a/src/addons/mod/survey/components/index/index.ts +++ b/src/addons/mod/survey/components/index/index.ts @@ -25,7 +25,6 @@ import { Translate } from '@singletons'; import { CoreEvents } from '@singletons/events'; import { getPrefetchHandlerInstance } from '../../services/handlers/prefetch'; import { - AddonModSurveyProvider, AddonModSurveySurvey, AddonModSurvey, AddonModSurveySubmitAnswerData, @@ -35,10 +34,10 @@ import { AddonModSurveyOffline } from '../../services/survey-offline'; import { AddonModSurveyAutoSyncData, AddonModSurveySync, - AddonModSurveySyncProvider, AddonModSurveySyncResult, } from '../../services/survey-sync'; import { CoreUtils } from '@services/utils/utils'; +import { ADDON_MOD_SURVEY_AUTO_SYNCED, ADDON_MOD_SURVEY_COMPONENT } from '../../constants'; /** * Component that displays a survey. @@ -50,7 +49,7 @@ import { CoreUtils } from '@services/utils/utils'; }) export class AddonModSurveyIndexComponent extends CoreCourseModuleMainActivityComponent implements OnInit { - component = AddonModSurveyProvider.COMPONENT; + component = ADDON_MOD_SURVEY_COMPONENT; pluginName = 'survey'; survey?: AddonModSurveySurvey; @@ -58,7 +57,7 @@ export class AddonModSurveyIndexComponent extends CoreCourseModuleMainActivityCo answers: Record = {}; protected currentUserId?: number; - protected syncEventName = AddonModSurveySyncProvider.AUTO_SYNCED; + protected syncEventName = ADDON_MOD_SURVEY_AUTO_SYNCED; constructor( protected content?: IonContent, diff --git a/src/addons/mod/survey/constants.ts b/src/addons/mod/survey/constants.ts index bcbc93f72..3480546df 100644 --- a/src/addons/mod/survey/constants.ts +++ b/src/addons/mod/survey/constants.ts @@ -24,3 +24,5 @@ export const ADDON_MOD_SURVEY_PREFETCH_COMPONENT = ADDON_MOD_SURVEY_COMPONENT; export const ADDON_MOD_SURVEY_PREFETCH_UPDATE_NAMES = /^configuration$|^.*files$|^answers$/; export const ADDON_MOD_SURVEY_SYNC_CRON_NAME = 'AddonModSurveySyncCronHandler'; + +export const ADDON_MOD_SURVEY_AUTO_SYNCED = 'addon_mod_survey_autom_synced'; diff --git a/src/addons/mod/survey/services/handlers/prefetch-lazy.ts b/src/addons/mod/survey/services/handlers/prefetch-lazy.ts index f8b361afa..32b8120c9 100644 --- a/src/addons/mod/survey/services/handlers/prefetch-lazy.ts +++ b/src/addons/mod/survey/services/handlers/prefetch-lazy.ts @@ -19,9 +19,10 @@ import { CoreSitesReadingStrategy } from '@services/sites'; import { CoreUtils } from '@services/utils/utils'; import { CoreWSFile } from '@services/ws'; import { makeSingleton } from '@singletons'; -import { AddonModSurvey, AddonModSurveyProvider } from '../survey'; +import { AddonModSurvey } from '../survey'; import { AddonModSurveySync, AddonModSurveySyncResult } from '../survey-sync'; import { AddonModSurveyPrefetchHandlerService } from '@addons/mod/survey/services/handlers/prefetch'; +import { ADDON_MOD_SURVEY_COMPONENT } from '../../constants'; /** * Handler to prefetch surveys. @@ -84,7 +85,7 @@ export class AddonModSurveyPrefetchHandlerLazyService extends AddonModSurveyPref const files = this.getIntroFilesFromInstance(module, survey); // Prefetch files. - promises.push(CoreFilepool.addFilesToQueue(siteId, files, AddonModSurveyProvider.COMPONENT, module.id)); + promises.push(CoreFilepool.addFilesToQueue(siteId, files, ADDON_MOD_SURVEY_COMPONENT, module.id)); // If survey isn't answered, prefetch the questions. if (!survey.surveydone) { diff --git a/src/addons/mod/survey/services/survey-sync.ts b/src/addons/mod/survey/services/survey-sync.ts index 71c32018f..54a793fe6 100644 --- a/src/addons/mod/survey/services/survey-sync.ts +++ b/src/addons/mod/survey/services/survey-sync.ts @@ -24,8 +24,9 @@ import { CoreUtils } from '@services/utils/utils'; import { makeSingleton } from '@singletons'; import { CoreEvents } from '@singletons/events'; import { getPrefetchHandlerInstance } from './handlers/prefetch'; -import { AddonModSurvey, AddonModSurveyProvider } from './survey'; +import { AddonModSurvey } from './survey'; import { AddonModSurveyAnswersDBRecordFormatted, AddonModSurveyOffline } from './survey-offline'; +import { ADDON_MOD_SURVEY_AUTO_SYNCED, ADDON_MOD_SURVEY_COMPONENT } from '../constants'; /** * Service to sync surveys. @@ -33,8 +34,6 @@ import { AddonModSurveyAnswersDBRecordFormatted, AddonModSurveyOffline } from '. @Injectable( { providedIn: 'root' }) export class AddonModSurveySyncProvider extends CoreCourseActivitySyncBaseProvider { - static readonly AUTO_SYNCED = 'addon_mod_survey_autom_synced'; - protected componentTranslatableString = 'survey'; constructor() { @@ -83,7 +82,7 @@ export class AddonModSurveySyncProvider extends CoreCourseActivitySyncBaseProvid if (result && result.updated) { // Sync successful, send event. - CoreEvents.trigger(AddonModSurveySyncProvider.AUTO_SYNCED, { + CoreEvents.trigger(ADDON_MOD_SURVEY_AUTO_SYNCED, { surveyId: entry.surveyid, userId: entry.userid, warnings: result.warnings, @@ -155,7 +154,7 @@ export class AddonModSurveySyncProvider extends CoreCourseActivitySyncBaseProvid }; // Sync offline logs. - CoreUtils.ignoreErrors(CoreCourseLogHelper.syncActivity(AddonModSurveyProvider.COMPONENT, surveyId, siteId)); + CoreUtils.ignoreErrors(CoreCourseLogHelper.syncActivity(ADDON_MOD_SURVEY_COMPONENT, surveyId, siteId)); let answersNumber = 0; let data: AddonModSurveyAnswersDBRecordFormatted | undefined; @@ -229,7 +228,7 @@ declare module '@singletons/events' { * @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation */ export interface CoreEventsData { - [AddonModSurveySyncProvider.AUTO_SYNCED]: AddonModSurveyAutoSyncData; + [ADDON_MOD_SURVEY_AUTO_SYNCED]: AddonModSurveyAutoSyncData; } } diff --git a/src/addons/mod/survey/services/survey.ts b/src/addons/mod/survey/services/survey.ts index 81824a3e4..ca76d8e34 100644 --- a/src/addons/mod/survey/services/survey.ts +++ b/src/addons/mod/survey/services/survey.ts @@ -25,9 +25,7 @@ import { CoreStatusWithWarningsWSResponse, CoreWSExternalFile, CoreWSExternalWar import { makeSingleton, Translate } from '@singletons'; import { AddonModSurveyOffline } from './survey-offline'; import { CoreSiteWSPreSets } from '@classes/sites/authenticated-site'; -import { ADDON_MOD_SURVEY_COMPONENT } from '@addons/mod/survey/constants'; - -const ROOT_CACHE_KEY = 'mmaModSurvey:'; +import { ADDON_MOD_SURVEY_COMPONENT } from '../constants'; /** * Service that provides some features for surveys. @@ -35,7 +33,7 @@ const ROOT_CACHE_KEY = 'mmaModSurvey:'; @Injectable( { providedIn: 'root' }) export class AddonModSurveyProvider { - static readonly COMPONENT = ADDON_MOD_SURVEY_COMPONENT; + protected static readonly ROOT_CACHE_KEY = 'mmaModSurvey:'; /** * Get a survey's questions. @@ -54,7 +52,7 @@ export class AddonModSurveyProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getQuestionsCacheKey(surveyId), updateFrequency: CoreSite.FREQUENCY_RARELY, - component: AddonModSurveyProvider.COMPONENT, + component: ADDON_MOD_SURVEY_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -74,7 +72,7 @@ export class AddonModSurveyProvider { * @returns Cache key. */ protected getQuestionsCacheKey(surveyId: number): string { - return ROOT_CACHE_KEY + 'questions:' + surveyId; + return AddonModSurveyProvider.ROOT_CACHE_KEY + 'questions:' + surveyId; } /** @@ -84,7 +82,7 @@ export class AddonModSurveyProvider { * @returns Cache key. */ protected getSurveyCacheKey(courseId: number): string { - return ROOT_CACHE_KEY + 'survey:' + courseId; + return AddonModSurveyProvider.ROOT_CACHE_KEY + 'survey:' + courseId; } /** @@ -111,7 +109,7 @@ export class AddonModSurveyProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getSurveyCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, - component: AddonModSurveyProvider.COMPONENT, + component: ADDON_MOD_SURVEY_COMPONENT, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -175,7 +173,7 @@ export class AddonModSurveyProvider { return; })); - promises.push(CoreFilepool.invalidateFilesByComponent(siteId, AddonModSurveyProvider.COMPONENT, moduleId)); + promises.push(CoreFilepool.invalidateFilesByComponent(siteId, ADDON_MOD_SURVEY_COMPONENT, moduleId)); await CoreUtils.allPromises(promises); } @@ -221,7 +219,7 @@ export class AddonModSurveyProvider { await CoreCourseLogHelper.log( 'mod_survey_view_survey', params, - AddonModSurveyProvider.COMPONENT, + ADDON_MOD_SURVEY_COMPONENT, id, siteId, ); diff --git a/src/addons/mod/survey/survey-lazy.module.ts b/src/addons/mod/survey/survey-lazy.module.ts index bd372d315..ff8a578d0 100644 --- a/src/addons/mod/survey/survey-lazy.module.ts +++ b/src/addons/mod/survey/survey-lazy.module.ts @@ -36,4 +36,4 @@ const routes: Routes = [ AddonModSurveyIndexPage, ], }) -export class AddonModSurveyLazyModule {} +export default class AddonModSurveyLazyModule {} diff --git a/src/addons/mod/survey/survey.module.ts b/src/addons/mod/survey/survey.module.ts index 707f22845..3f1c3e8e7 100644 --- a/src/addons/mod/survey/survey.module.ts +++ b/src/addons/mod/survey/survey.module.ts @@ -31,7 +31,7 @@ import { ADDON_MOD_SURVEY_PAGE_NAME } from '@addons/mod/survey/constants'; const routes: Routes = [ { path: ADDON_MOD_SURVEY_PAGE_NAME, - loadChildren: () => import('./survey-lazy.module').then(m => m.AddonModSurveyLazyModule), + loadChildren: () => import('./survey-lazy.module'), }, ]; From 06fec4e6cfef541adeb0c4f1a647011c5d50371f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Thu, 11 Jul 2024 22:39:31 +0200 Subject: [PATCH 04/26] MOBILE-4616 bbb: Move bbb constants to a file --- .../bigbluebuttonbn-lazy.module.ts | 2 +- .../bigbluebuttonbn/bigbluebuttonbn.module.ts | 7 ++++--- .../bigbluebuttonbn/components/index/index.ts | 4 ++-- src/addons/mod/bigbluebuttonbn/constants.ts | 16 ++++++++++++++++ .../services/bigbluebuttonbn.ts | 19 +++++++++---------- .../services/handlers/module.ts | 5 ++--- 6 files changed, 34 insertions(+), 19 deletions(-) create mode 100644 src/addons/mod/bigbluebuttonbn/constants.ts diff --git a/src/addons/mod/bigbluebuttonbn/bigbluebuttonbn-lazy.module.ts b/src/addons/mod/bigbluebuttonbn/bigbluebuttonbn-lazy.module.ts index e2152edb4..a5bf8810a 100644 --- a/src/addons/mod/bigbluebuttonbn/bigbluebuttonbn-lazy.module.ts +++ b/src/addons/mod/bigbluebuttonbn/bigbluebuttonbn-lazy.module.ts @@ -35,4 +35,4 @@ const routes: Routes = [ AddonModBBBIndexPage, ], }) -export class AddonModBBBLazyModule {} +export default class AddonModBBBLazyModule {} diff --git a/src/addons/mod/bigbluebuttonbn/bigbluebuttonbn.module.ts b/src/addons/mod/bigbluebuttonbn/bigbluebuttonbn.module.ts index 131966598..b81a3185b 100644 --- a/src/addons/mod/bigbluebuttonbn/bigbluebuttonbn.module.ts +++ b/src/addons/mod/bigbluebuttonbn/bigbluebuttonbn.module.ts @@ -19,12 +19,13 @@ import { CoreCourseModuleDelegate } from '@features/course/services/module-deleg import { CoreMainMenuTabRoutingModule } from '@features/mainmenu/mainmenu-tab-routing.module'; import { AddonModBBBIndexLinkHandler } from './services/handlers/index-link'; import { AddonModBBBListLinkHandler } from './services/handlers/list-link'; -import { AddonModBBBModuleHandler, ADDON_MOD_BBB_MAIN_MENU_PAGE_NAME } from './services/handlers/module'; +import { AddonModBBBModuleHandler } from './services/handlers/module'; +import { ADDON_MOD_BBB_PAGE_NAME } from './constants'; const routes: Routes = [ { - path: ADDON_MOD_BBB_MAIN_MENU_PAGE_NAME, - loadChildren: () => import('./bigbluebuttonbn-lazy.module').then(m => m.AddonModBBBLazyModule), + path: ADDON_MOD_BBB_PAGE_NAME, + loadChildren: () => import('./bigbluebuttonbn-lazy.module'), }, ]; diff --git a/src/addons/mod/bigbluebuttonbn/components/index/index.ts b/src/addons/mod/bigbluebuttonbn/components/index/index.ts index 92914b8ae..b4f61d185 100644 --- a/src/addons/mod/bigbluebuttonbn/components/index/index.ts +++ b/src/addons/mod/bigbluebuttonbn/components/index/index.ts @@ -30,8 +30,8 @@ import { AddonModBBBData, AddonModBBBMeetingInfo, AddonModBBBRecordingPlaybackTypes, - AddonModBBBService, } from '../../services/bigbluebuttonbn'; +import { ADDON_MOD_BBB_COMPONENT } from '../../constants'; /** * Component that displays a Big Blue Button activity. @@ -43,7 +43,7 @@ import { }) export class AddonModBBBIndexComponent extends CoreCourseModuleMainActivityComponent implements OnInit { - component = AddonModBBBService.COMPONENT; + component = ADDON_MOD_BBB_COMPONENT; pluginName = 'bigbluebuttonbn'; bbb?: AddonModBBBData; groupInfo?: CoreGroupInfo; diff --git a/src/addons/mod/bigbluebuttonbn/constants.ts b/src/addons/mod/bigbluebuttonbn/constants.ts new file mode 100644 index 000000000..db8e8190e --- /dev/null +++ b/src/addons/mod/bigbluebuttonbn/constants.ts @@ -0,0 +1,16 @@ +// (C) Copyright 2015 Moodle Pty Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export const ADDON_MOD_BBB_COMPONENT = 'mmaModBigBlueButtonBN'; +export const ADDON_MOD_BBB_PAGE_NAME = 'mod_bigbluebuttonbn'; diff --git a/src/addons/mod/bigbluebuttonbn/services/bigbluebuttonbn.ts b/src/addons/mod/bigbluebuttonbn/services/bigbluebuttonbn.ts index eb226fe30..a96f4e5d3 100644 --- a/src/addons/mod/bigbluebuttonbn/services/bigbluebuttonbn.ts +++ b/src/addons/mod/bigbluebuttonbn/services/bigbluebuttonbn.ts @@ -24,8 +24,7 @@ import { CoreTextUtils } from '@services/utils/text'; import { CoreUtils } from '@services/utils/utils'; import { CoreWSExternalFile, CoreWSExternalWarning } from '@services/ws'; import { makeSingleton, Translate } from '@singletons'; - -const ROOT_CACHE_KEY = 'AddonModBBB:'; +import { ADDON_MOD_BBB_COMPONENT } from '../constants'; /** * Service that provides some features for Big Blue Button activity. @@ -33,7 +32,7 @@ const ROOT_CACHE_KEY = 'AddonModBBB:'; @Injectable({ providedIn: 'root' }) export class AddonModBBBService { - static readonly COMPONENT = 'mmaModBigBlueButtonBN'; + protected static readonly ROOT_CACHE_KEY = 'AddonModBBB:'; /** * End a meeting. @@ -75,7 +74,7 @@ export class AddonModBBBService { const preSets: CoreSiteWSPreSets = { cacheKey: this.getBBBsCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, - component: AddonModBBBService.COMPONENT, + component: ADDON_MOD_BBB_COMPONENT, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -100,7 +99,7 @@ export class AddonModBBBService { * @returns Cache key. */ protected getBBBsCacheKey(courseId: number): string { - return ROOT_CACHE_KEY + 'bbb:' + courseId; + return AddonModBBBService.ROOT_CACHE_KEY + 'bbb:' + courseId; } /** @@ -166,7 +165,7 @@ export class AddonModBBBService { cacheKey: this.getMeetingInfoCacheKey(id, groupId), getCacheUsingCacheKey: true, uniqueCacheKey: true, - component: AddonModBBBService.COMPONENT, + component: ADDON_MOD_BBB_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -205,7 +204,7 @@ export class AddonModBBBService { * @returns Cache key prefix. */ protected getMeetingInfoCacheKeyPrefix(id: number): string { - return ROOT_CACHE_KEY + 'meetingInfo:' + id + ':'; + return AddonModBBBService.ROOT_CACHE_KEY + 'meetingInfo:' + id + ':'; } /** @@ -229,7 +228,7 @@ export class AddonModBBBService { }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getRecordingsCacheKey(id, groupId), - component: AddonModBBBService.COMPONENT, + component: ADDON_MOD_BBB_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -270,7 +269,7 @@ export class AddonModBBBService { * @returns Cache key prefix. */ protected getRecordingsCacheKeyPrefix(id: number): string { - return ROOT_CACHE_KEY + 'recordings:' + id + ':'; + return AddonModBBBService.ROOT_CACHE_KEY + 'recordings:' + id + ':'; } /** @@ -288,7 +287,7 @@ export class AddonModBBBService { await CoreCourseLogHelper.log( 'mod_bigbluebuttonbn_view_bigbluebuttonbn', params, - AddonModBBBService.COMPONENT, + ADDON_MOD_BBB_COMPONENT, id, siteId, ); diff --git a/src/addons/mod/bigbluebuttonbn/services/handlers/module.ts b/src/addons/mod/bigbluebuttonbn/services/handlers/module.ts index ee71b6308..b458cc618 100644 --- a/src/addons/mod/bigbluebuttonbn/services/handlers/module.ts +++ b/src/addons/mod/bigbluebuttonbn/services/handlers/module.ts @@ -22,8 +22,7 @@ import { CoreSitePlugins } from '@features/siteplugins/services/siteplugins'; import { makeSingleton } from '@singletons'; import { AddonModBBBIndexComponent } from '../../components/index'; import { AddonModBBB } from '../bigbluebuttonbn'; - -export const ADDON_MOD_BBB_MAIN_MENU_PAGE_NAME = 'mod_bigbluebuttonbn'; +import { ADDON_MOD_BBB_PAGE_NAME } from '../../constants'; /** * Handler to support Big Blue Button activities. @@ -33,7 +32,7 @@ export class AddonModBBBModuleHandlerService extends CoreModuleHandlerBase imple name = 'AddonModBBB'; modName = 'bigbluebuttonbn'; - protected pageName = ADDON_MOD_BBB_MAIN_MENU_PAGE_NAME; + protected pageName = ADDON_MOD_BBB_PAGE_NAME; protected sitePluginHandler?: CoreSitePluginsModuleHandler; supportedFeatures = { From bc1e3f00e7fe53b594acf44da6372052f5b5b192 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Thu, 11 Jul 2024 22:40:08 +0200 Subject: [PATCH 05/26] MOBILE-4616 book: Move book constants to a file --- src/addons/mod/book/book-lazy.module.ts | 2 +- src/addons/mod/book/book.module.ts | 7 ++-- src/addons/mod/book/components/index/index.ts | 6 +-- src/addons/mod/book/components/toc/toc.ts | 3 +- src/addons/mod/book/constants.ts | 34 +++++++++++++++++ .../mod/book/pages/contents/contents.ts | 5 +-- src/addons/mod/book/services/book.ts | 38 +++++-------------- .../mod/book/services/handlers/module.ts | 5 +-- .../mod/book/services/handlers/prefetch.ts | 5 ++- 9 files changed, 60 insertions(+), 45 deletions(-) create mode 100644 src/addons/mod/book/constants.ts diff --git a/src/addons/mod/book/book-lazy.module.ts b/src/addons/mod/book/book-lazy.module.ts index 43b4af496..95c30c6f2 100644 --- a/src/addons/mod/book/book-lazy.module.ts +++ b/src/addons/mod/book/book-lazy.module.ts @@ -43,4 +43,4 @@ const routes: Routes = [ AddonModBookContentsPage, ], }) -export class AddonModBookLazyModule {} +export default class AddonModBookLazyModule {} diff --git a/src/addons/mod/book/book.module.ts b/src/addons/mod/book/book.module.ts index 82c5f9f33..9ae4af590 100644 --- a/src/addons/mod/book/book.module.ts +++ b/src/addons/mod/book/book.module.ts @@ -19,18 +19,19 @@ import { CoreCourseModuleDelegate } from '@features/course/services/module-deleg import { CoreCourseModulePrefetchDelegate } from '@features/course/services/module-prefetch-delegate'; import { CoreMainMenuTabRoutingModule } from '@features/mainmenu/mainmenu-tab-routing.module'; import { CoreTagAreaDelegate } from '@features/tag/services/tag-area-delegate'; -import { AddonModBookModuleHandler, AddonModBookModuleHandlerService } from './services/handlers/module'; +import { AddonModBookModuleHandler } from './services/handlers/module'; import { AddonModBookIndexLinkHandler } from './services/handlers/index-link'; import { AddonModBookListLinkHandler } from './services/handlers/list-link'; import { AddonModBookPrefetchHandler } from './services/handlers/prefetch'; import { AddonModBookTagAreaHandler } from './services/handlers/tag-area'; import { CORE_SITE_SCHEMAS } from '@services/sites'; import { BOOK_SITE_SCHEMA } from './services/database/book'; +import { ADDON_MOD_BOOK_PAGE_NAME } from './constants'; const routes: Routes = [ { - path: AddonModBookModuleHandlerService.PAGE_NAME, - loadChildren: () => import('./book-lazy.module').then(m => m.AddonModBookLazyModule), + path: ADDON_MOD_BOOK_PAGE_NAME, + loadChildren: () => import('./book-lazy.module'), }, ]; diff --git a/src/addons/mod/book/components/index/index.ts b/src/addons/mod/book/components/index/index.ts index aa77f2d33..1a03cb0db 100644 --- a/src/addons/mod/book/components/index/index.ts +++ b/src/addons/mod/book/components/index/index.ts @@ -14,12 +14,12 @@ import { Component, Optional, OnInit, OnDestroy } from '@angular/core'; import { CoreCourseModuleMainResourceComponent } from '@features/course/classes/main-resource-component'; -import { AddonModBook, AddonModBookBookWSData, AddonModBookNumbering, AddonModBookTocChapter } from '../../services/book'; +import { AddonModBook, AddonModBookBookWSData, AddonModBookTocChapter } from '../../services/book'; import { CoreCourseContentsPage } from '@features/course/pages/contents/contents'; import { CoreCourse } from '@features/course/services/course'; import { CoreNavigator } from '@services/navigator'; -import { AddonModBookModuleHandlerService } from '../../services/handlers/module'; import { CoreUtils } from '@services/utils/utils'; +import { ADDON_MOD_BOOK_PAGE_NAME, AddonModBookNumbering } from '../../constants'; /** * Component that displays a book entry page. @@ -116,7 +116,7 @@ export class AddonModBookIndexComponent extends CoreCourseModuleMainResourceComp */ async openBook(chapterId?: number): Promise { await CoreNavigator.navigateToSitePath( - `${AddonModBookModuleHandlerService.PAGE_NAME}/${this.courseId}/${this.module.id}/contents`, + `${ADDON_MOD_BOOK_PAGE_NAME}/${this.courseId}/${this.module.id}/contents`, { params: { chapterId } }, ); diff --git a/src/addons/mod/book/components/toc/toc.ts b/src/addons/mod/book/components/toc/toc.ts index ed38ca1aa..f59ccdf2f 100644 --- a/src/addons/mod/book/components/toc/toc.ts +++ b/src/addons/mod/book/components/toc/toc.ts @@ -14,7 +14,8 @@ import { Component, Input, OnInit } from '@angular/core'; import { ModalController } from '@singletons'; -import { AddonModBookTocChapter, AddonModBookBookWSData, AddonModBookNumbering } from '../../services/book'; +import { AddonModBookTocChapter, AddonModBookBookWSData } from '../../services/book'; +import { AddonModBookNumbering } from '../../constants'; /** * Modal to display the TOC of a book. diff --git a/src/addons/mod/book/constants.ts b/src/addons/mod/book/constants.ts new file mode 100644 index 000000000..74f83cfdb --- /dev/null +++ b/src/addons/mod/book/constants.ts @@ -0,0 +1,34 @@ +// (C) Copyright 2015 Moodle Pty Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export const ADDON_MOD_BOOK_COMPONENT = 'mmaModBook'; +export const ADDON_MOD_BOOK_PAGE_NAME = 'mod_book'; +/** + * Constants to define how the chapters and subchapters of a book should be displayed in that table of contents. + */ +export const enum AddonModBookNumbering { + NONE = 0, + NUMBERS = 1, + BULLETS = 2, + INDENTED = 3, +} + +/** + * Constants to define the navigation style used within a book. + */ +export const enum AddonModBookNavStyle { + TOC_ONLY = 0, + IMAGE = 1, + TEXT = 2, +} diff --git a/src/addons/mod/book/pages/contents/contents.ts b/src/addons/mod/book/pages/contents/contents.ts index bff523109..653974be2 100644 --- a/src/addons/mod/book/pages/contents/contents.ts +++ b/src/addons/mod/book/pages/contents/contents.ts @@ -35,12 +35,11 @@ import { AddonModBook, AddonModBookBookWSData, AddonModBookContentsMap, - AddonModBookNavStyle, - AddonModBookProvider, AddonModBookTocChapter, } from '../../services/book'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; import { CoreUrlUtils } from '@services/utils/url'; +import { ADDON_MOD_BOOK_COMPONENT, AddonModBookNavStyle } from '../../constants'; /** * Page that displays a book contents. @@ -58,7 +57,7 @@ export class AddonModBookContentsPage implements OnInit, OnDestroy { cmId!: number; courseId!: number; initialChapterId?: number; - component = AddonModBookProvider.COMPONENT; + component = ADDON_MOD_BOOK_COMPONENT; manager?: CoreSwipeSlidesItemsManager; warning = ''; displayNavBar = true; diff --git a/src/addons/mod/book/services/book.ts b/src/addons/mod/book/services/book.ts index 69ec1c329..e8da3e010 100644 --- a/src/addons/mod/book/services/book.ts +++ b/src/addons/mod/book/services/book.ts @@ -27,27 +27,7 @@ import { CoreDomUtils } from '@services/utils/dom'; import { CoreFile } from '@services/file'; import { CoreError } from '@classes/errors/error'; import { CoreSiteWSPreSets } from '@classes/sites/authenticated-site'; - -/** - * Constants to define how the chapters and subchapters of a book should be displayed in that table of contents. - */ -export const enum AddonModBookNumbering { - NONE = 0, - NUMBERS = 1, - BULLETS = 2, - INDENTED = 3, -} - -/** - * Constants to define the navigation style used within a book. - */ -export const enum AddonModBookNavStyle { - TOC_ONLY = 0, - IMAGE = 1, - TEXT = 2, -} - -const ROOT_CACHE_KEY = 'mmaModBook:'; +import { ADDON_MOD_BOOK_COMPONENT } from '../constants'; /** * Service that provides some features for books. @@ -55,7 +35,7 @@ const ROOT_CACHE_KEY = 'mmaModBook:'; @Injectable({ providedIn: 'root' }) export class AddonModBookProvider { - static readonly COMPONENT = 'mmaModBook'; + protected static readonly ROOT_CACHE_KEY = 'mmaModBook:'; /** * Get a book by course module ID. @@ -92,7 +72,7 @@ export class AddonModBookProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getBookDataCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, - component: AddonModBookProvider.COMPONENT, + component: ADDON_MOD_BOOK_COMPONENT, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), }; @@ -114,7 +94,7 @@ export class AddonModBookProvider { * @returns Cache key. */ protected getBookDataCacheKey(courseId: number): string { - return ROOT_CACHE_KEY + 'book:' + courseId; + return AddonModBookProvider.ROOT_CACHE_KEY + 'book:' + courseId; } /** @@ -140,7 +120,7 @@ export class AddonModBookProvider { const siteId = CoreSites.getCurrentSiteId(); - const url = await CoreFilepool.downloadUrl(siteId, indexUrl, false, AddonModBookProvider.COMPONENT, moduleId); + const url = await CoreFilepool.downloadUrl(siteId, indexUrl, false, ADDON_MOD_BOOK_COMPONENT, moduleId); const content = await CoreWS.getText(url); @@ -226,7 +206,7 @@ export class AddonModBookProvider { */ async getLastChapterViewed(id: number, siteId?: string): Promise { const site = await CoreSites.getSite(siteId); - const entry = await site.getLastViewed(AddonModBookProvider.COMPONENT, id); + const entry = await site.getLastViewed(ADDON_MOD_BOOK_COMPONENT, id); const chapterId = Number(entry?.value); @@ -327,7 +307,7 @@ export class AddonModBookProvider { const promises: Promise[] = []; promises.push(this.invalidateBookData(courseId, siteId)); - promises.push(CoreFilepool.invalidateFilesByComponent(siteId, AddonModBookProvider.COMPONENT, moduleId)); + promises.push(CoreFilepool.invalidateFilesByComponent(siteId, ADDON_MOD_BOOK_COMPONENT, moduleId)); promises.push(CoreCourse.invalidateModule(moduleId, siteId)); return CoreUtils.allPromises(promises); @@ -372,7 +352,7 @@ export class AddonModBookProvider { await CoreCourseLogHelper.log( 'mod_book_view_book', params, - AddonModBookProvider.COMPONENT, + ADDON_MOD_BOOK_COMPONENT, id, siteId, ); @@ -390,7 +370,7 @@ export class AddonModBookProvider { async storeLastChapterViewed(id: number, chapterId: number, courseId: number, siteId?: string): Promise { const site = await CoreSites.getSite(siteId); - await site.storeLastViewed(AddonModBookProvider.COMPONENT, id, chapterId, { data: String(courseId) }); + await site.storeLastViewed(ADDON_MOD_BOOK_COMPONENT, id, chapterId, { data: String(courseId) }); } } diff --git a/src/addons/mod/book/services/handlers/module.ts b/src/addons/mod/book/services/handlers/module.ts index 85abc0d02..341acacc0 100644 --- a/src/addons/mod/book/services/handlers/module.ts +++ b/src/addons/mod/book/services/handlers/module.ts @@ -18,6 +18,7 @@ import { CoreConstants, ModPurpose } from '@/core/constants'; import { CoreCourseModuleHandler } from '@features/course/services/module-delegate'; import { makeSingleton } from '@singletons'; import { CoreModuleHandlerBase } from '@features/course/classes/module-base-handler'; +import { ADDON_MOD_BOOK_PAGE_NAME } from '../../constants'; /** * Handler to support book modules. @@ -25,11 +26,9 @@ import { CoreModuleHandlerBase } from '@features/course/classes/module-base-hand @Injectable({ providedIn: 'root' }) export class AddonModBookModuleHandlerService extends CoreModuleHandlerBase implements CoreCourseModuleHandler { - static readonly PAGE_NAME = 'mod_book'; - name = 'AddonModBook'; modName = 'book'; - protected pageName = AddonModBookModuleHandlerService.PAGE_NAME; + protected pageName = ADDON_MOD_BOOK_PAGE_NAME; supportedFeatures = { [CoreConstants.FEATURE_MOD_ARCHETYPE]: CoreConstants.MOD_ARCHETYPE_RESOURCE, diff --git a/src/addons/mod/book/services/handlers/prefetch.ts b/src/addons/mod/book/services/handlers/prefetch.ts index a4cd7ac76..640a69e40 100644 --- a/src/addons/mod/book/services/handlers/prefetch.ts +++ b/src/addons/mod/book/services/handlers/prefetch.ts @@ -19,7 +19,8 @@ import { CoreCourseModuleData } from '@features/course/services/course-helper'; import { CoreUtils } from '@services/utils/utils'; import { CoreWSFile } from '@services/ws'; import { makeSingleton } from '@singletons'; -import { AddonModBook, AddonModBookProvider } from '../book'; +import { AddonModBook } from '../book'; +import { ADDON_MOD_BOOK_COMPONENT } from '../../constants'; /** * Handler to prefetch books. @@ -29,7 +30,7 @@ export class AddonModBookPrefetchHandlerService extends CoreCourseResourcePrefet name = 'AddonModBook'; modName = 'book'; - component = AddonModBookProvider.COMPONENT; + component = ADDON_MOD_BOOK_COMPONENT; updatesNames = /^configuration$|^.*files$|^entries$/; /** From 4934dcec99577f0d7db0eb08b3185a1fb959ab7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Thu, 11 Jul 2024 22:40:27 +0200 Subject: [PATCH 06/26] MOBILE-4616 feedback: Move feedback constants to a file --- .../classes/feedback-attempts-source.ts | 8 +-- .../mod/feedback/components/index/index.ts | 13 ++-- src/addons/mod/feedback/constants.ts | 26 +++++++ .../mod/feedback/feedback-lazy.module.ts | 2 +- src/addons/mod/feedback/feedback.module.ts | 10 +-- .../mod/feedback/pages/attempt/attempt.ts | 4 +- src/addons/mod/feedback/pages/form/form.ts | 13 ++-- .../mod/feedback/services/feedback-helper.ts | 30 ++++---- .../mod/feedback/services/feedback-sync.ts | 7 +- src/addons/mod/feedback/services/feedback.ts | 68 +++++++++---------- .../services/handlers/analysis-link.ts | 4 +- .../services/handlers/complete-link.ts | 4 +- .../mod/feedback/services/handlers/module.ts | 5 +- .../feedback/services/handlers/prefetch.ts | 4 +- .../feedback/services/handlers/print-link.ts | 4 +- .../handlers/show-non-respondents-link.ts | 4 +- 16 files changed, 118 insertions(+), 88 deletions(-) create mode 100644 src/addons/mod/feedback/constants.ts diff --git a/src/addons/mod/feedback/classes/feedback-attempts-source.ts b/src/addons/mod/feedback/classes/feedback-attempts-source.ts index c2b74eed4..5a6bb73e4 100644 --- a/src/addons/mod/feedback/classes/feedback-attempts-source.ts +++ b/src/addons/mod/feedback/classes/feedback-attempts-source.ts @@ -16,13 +16,13 @@ import { CoreRoutedItemsManagerSource } from '@classes/items-management/routed-i import { CoreGroupInfo, CoreGroups } from '@services/groups'; import { AddonModFeedback, - AddonModFeedbackProvider, AddonModFeedbackWSAnonAttempt, AddonModFeedbackWSAttempt, AddonModFeedbackWSFeedback, } from '../services/feedback'; import { AddonModFeedbackHelper } from '../services/feedback-helper'; import { Params } from '@angular/router'; +import { ADDON_MOD_FEEDBACK_PER_PAGE } from '../constants'; /** * Feedback attempts. @@ -120,7 +120,7 @@ export class AddonModFeedbackAttemptsSource extends CoreRoutedItemsManagerSource * @inheritdoc */ protected getPageLength(): number { - return AddonModFeedbackProvider.PER_PAGE; + return ADDON_MOD_FEEDBACK_PER_PAGE; } /** @@ -146,10 +146,10 @@ export class AddonModFeedbackAttemptsSource extends CoreRoutedItemsManagerSource const pageAttempts: AddonModFeedbackAttemptItem[] = [ // The page argument is ignored in the webservice when there is only one page, // so we should ignore the responses of pages beyond the first if that's the case. - ...(page === 0 || result.totalattempts > AddonModFeedbackProvider.PER_PAGE) + ...(page === 0 || result.totalattempts > ADDON_MOD_FEEDBACK_PER_PAGE) ? result.attempts : [], - ...(page === 0 || result.totalanonattempts > AddonModFeedbackProvider.PER_PAGE) + ...(page === 0 || result.totalanonattempts > ADDON_MOD_FEEDBACK_PER_PAGE) ? result.anonattempts : [], ]; diff --git a/src/addons/mod/feedback/components/index/index.ts b/src/addons/mod/feedback/components/index/index.ts index 7980f3640..957973d9e 100644 --- a/src/addons/mod/feedback/components/index/index.ts +++ b/src/addons/mod/feedback/components/index/index.ts @@ -27,7 +27,6 @@ import { CoreEventObserver, CoreEvents } from '@singletons/events'; import { AddonModFeedback, AddonModFeedbackGetFeedbackAccessInformationWSResponse, - AddonModFeedbackProvider, AddonModFeedbackWSFeedback, AddonModFeedbackWSItem, } from '../../services/feedback'; @@ -38,8 +37,8 @@ import { AddonModFeedbackSyncProvider, AddonModFeedbackSyncResult, } from '../../services/feedback-sync'; -import { AddonModFeedbackModuleHandlerService } from '../../services/handlers/module'; import { AddonModFeedbackPrefetchHandler } from '../../services/handlers/prefetch'; +import { ADDON_MOD_FEEDBACK_COMPONENT, ADDON_MOD_FEEDBACK_FORM_SUBMITTED, ADDON_MOD_FEEDBACK_PAGE_NAME } from '../../constants'; /** * Component that displays a feedback index page. @@ -55,7 +54,7 @@ export class AddonModFeedbackIndexComponent extends CoreCourseModuleMainActivity @Input() tab = 'overview'; @Input() group = 0; - component = AddonModFeedbackProvider.COMPONENT; + component = ADDON_MOD_FEEDBACK_COMPONENT; pluginName = 'feedback'; feedback?: AddonModFeedbackWSFeedback; goPage?: number; @@ -92,7 +91,7 @@ export class AddonModFeedbackIndexComponent extends CoreCourseModuleMainActivity super('AddonModLessonIndexComponent', content, courseContentsPage); // Listen for form submit events. - this.submitObserver = CoreEvents.on(AddonModFeedbackProvider.FORM_SUBMITTED, async (data) => { + this.submitObserver = CoreEvents.on(ADDON_MOD_FEEDBACK_FORM_SUBMITTED, async (data) => { if (!this.feedback || data.feedbackId != this.feedback.id) { return; } @@ -374,7 +373,7 @@ export class AddonModFeedbackIndexComponent extends CoreCourseModuleMainActivity */ gotoAnswerQuestions(preview: boolean = false): void { CoreNavigator.navigateToSitePath( - AddonModFeedbackModuleHandlerService.PAGE_NAME + `/${this.courseId}/${this.module.id}/form`, + ADDON_MOD_FEEDBACK_PAGE_NAME + `/${this.courseId}/${this.module.id}/form`, { params: { preview, @@ -407,7 +406,7 @@ export class AddonModFeedbackIndexComponent extends CoreCourseModuleMainActivity */ openNonRespondents(): void { CoreNavigator.navigateToSitePath( - AddonModFeedbackModuleHandlerService.PAGE_NAME + `/${this.courseId}/${this.module.id}/nonrespondents`, + ADDON_MOD_FEEDBACK_PAGE_NAME + `/${this.courseId}/${this.module.id}/nonrespondents`, { params: { group: this.group, @@ -425,7 +424,7 @@ export class AddonModFeedbackIndexComponent extends CoreCourseModuleMainActivity } CoreNavigator.navigateToSitePath( - AddonModFeedbackModuleHandlerService.PAGE_NAME + `/${this.courseId}/${this.module.id}/attempts`, + ADDON_MOD_FEEDBACK_PAGE_NAME + `/${this.courseId}/${this.module.id}/attempts`, { params: { group: this.group, diff --git a/src/addons/mod/feedback/constants.ts b/src/addons/mod/feedback/constants.ts new file mode 100644 index 000000000..d4d972c52 --- /dev/null +++ b/src/addons/mod/feedback/constants.ts @@ -0,0 +1,26 @@ +// (C) Copyright 2015 Moodle Pty Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export const ADDON_MOD_FEEDBACK_COMPONENT = 'mmaModFeedback'; + +export const ADDON_MOD_FEEDBACK_PAGE_NAME = 'mod_feedback'; + +export const ADDON_MOD_FEEDBACK_FORM_SUBMITTED = 'addon_mod_feedback_form_submitted'; +export const ADDON_MOD_FEEDBACK_LINE_SEP = '|'; +export const ADDON_MOD_FEEDBACK_MULTICHOICE_TYPE_SEP = '>>>>>'; +export const ADDON_MOD_FEEDBACK_MULTICHOICE_ADJUST_SEP = '<<<<<'; +export const ADDON_MOD_FEEDBACK_MULTICHOICE_HIDENOSELECT = 'h'; +export const ADDON_MOD_FEEDBACK_MULTICHOICERATED_VALUE_SEP = '####'; + +export const ADDON_MOD_FEEDBACK_PER_PAGE = 20; diff --git a/src/addons/mod/feedback/feedback-lazy.module.ts b/src/addons/mod/feedback/feedback-lazy.module.ts index f34edca90..b0f067de4 100644 --- a/src/addons/mod/feedback/feedback-lazy.module.ts +++ b/src/addons/mod/feedback/feedback-lazy.module.ts @@ -86,4 +86,4 @@ const routes: Routes = [ AddonModFeedbackAttemptPage, ], }) -export class AddonModFeedbackLazyModule {} +export default class AddonModFeedbackLazyModule {} diff --git a/src/addons/mod/feedback/feedback.module.ts b/src/addons/mod/feedback/feedback.module.ts index a13902749..1f2876a12 100644 --- a/src/addons/mod/feedback/feedback.module.ts +++ b/src/addons/mod/feedback/feedback.module.ts @@ -23,23 +23,23 @@ import { CorePushNotificationsDelegate } from '@features/pushnotifications/servi import { CoreCronDelegate } from '@services/cron'; import { CORE_SITE_SCHEMAS } from '@services/sites'; import { OFFLINE_SITE_SCHEMA } from './services/database/feedback'; -import { AddonModFeedbackProvider } from './services/feedback'; import { AddonModFeedbackAnalysisLinkHandler } from './services/handlers/analysis-link'; import { AddonModFeedbackCompleteLinkHandler } from './services/handlers/complete-link'; import { AddonModFeedbackIndexLinkHandler } from './services/handlers/index-link'; import { AddonModFeedbackListLinkHandler } from './services/handlers/list-link'; -import { AddonModFeedbackModuleHandlerService, AddonModFeedbackModuleHandler } from './services/handlers/module'; +import { AddonModFeedbackModuleHandler } from './services/handlers/module'; import { AddonModFeedbackPrefetchHandler } from './services/handlers/prefetch'; import { AddonModFeedbackPrintLinkHandler } from './services/handlers/print-link'; import { AddonModFeedbackPushClickHandler } from './services/handlers/push-click'; import { AddonModFeedbackShowEntriesLinkHandler } from './services/handlers/show-entries-link'; import { AddonModFeedbackShowNonRespondentsLinkHandler } from './services/handlers/show-non-respondents-link'; import { AddonModFeedbackSyncCronHandler } from './services/handlers/sync-cron'; +import { ADDON_MOD_FEEDBACK_COMPONENT, ADDON_MOD_FEEDBACK_PAGE_NAME } from './constants'; const routes: Routes = [ { - path: AddonModFeedbackModuleHandlerService.PAGE_NAME, - loadChildren: () => import('./feedback-lazy.module').then(m => m.AddonModFeedbackLazyModule), + path: ADDON_MOD_FEEDBACK_PAGE_NAME, + loadChildren: () => import('./feedback-lazy.module'), }, ]; @@ -69,7 +69,7 @@ const routes: Routes = [ CoreContentLinksDelegate.registerHandler(AddonModFeedbackShowNonRespondentsLinkHandler.instance); CorePushNotificationsDelegate.registerClickHandler(AddonModFeedbackPushClickHandler.instance); - CoreCourseHelper.registerModuleReminderClick(AddonModFeedbackProvider.COMPONENT); + CoreCourseHelper.registerModuleReminderClick(ADDON_MOD_FEEDBACK_COMPONENT); }, }, ], diff --git a/src/addons/mod/feedback/pages/attempt/attempt.ts b/src/addons/mod/feedback/pages/attempt/attempt.ts index 540ee2f81..ec1bac755 100644 --- a/src/addons/mod/feedback/pages/attempt/attempt.ts +++ b/src/addons/mod/feedback/pages/attempt/attempt.ts @@ -22,13 +22,13 @@ import { CoreTextUtils } from '@services/utils/text'; import { AddonModFeedbackAttemptsSource } from '../../classes/feedback-attempts-source'; import { AddonModFeedback, - AddonModFeedbackProvider, AddonModFeedbackWSAnonAttempt, AddonModFeedbackWSFeedback, } from '../../services/feedback'; import { AddonModFeedbackAttempt, AddonModFeedbackFormItem, AddonModFeedbackHelper } from '../../services/feedback-helper'; import { CoreTime } from '@singletons/time'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; +import { ADDON_MOD_FEEDBACK_COMPONENT } from '../../constants'; /** * Page that displays a feedback attempt review. @@ -46,7 +46,7 @@ export class AddonModFeedbackAttemptPage implements OnInit, OnDestroy { attempts: AddonModFeedbackAttemptsSwipeManager; anonAttempt?: AddonModFeedbackWSAnonAttempt; items: AddonModFeedbackAttemptItem[] = []; - component = AddonModFeedbackProvider.COMPONENT; + component = ADDON_MOD_FEEDBACK_COMPONENT; loaded = false; protected attemptId: number; diff --git a/src/addons/mod/feedback/pages/form/form.ts b/src/addons/mod/feedback/pages/form/form.ts index 928f70583..0f482f555 100644 --- a/src/addons/mod/feedback/pages/form/form.ts +++ b/src/addons/mod/feedback/pages/form/form.ts @@ -30,14 +30,13 @@ import { AddonModFeedback, AddonModFeedbackGetFeedbackAccessInformationWSResponse, AddonModFeedbackPageItems, - AddonModFeedbackProvider, AddonModFeedbackResponseValue, AddonModFeedbackWSFeedback, } from '../../services/feedback'; import { AddonModFeedbackFormItem, AddonModFeedbackHelper } from '../../services/feedback-helper'; import { AddonModFeedbackSync } from '../../services/feedback-sync'; -import { AddonModFeedbackModuleHandlerService } from '../../services/handlers/module'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; +import { ADDON_MOD_FEEDBACK_COMPONENT, ADDON_MOD_FEEDBACK_FORM_SUBMITTED, ADDON_MOD_FEEDBACK_PAGE_NAME } from '../../constants'; /** * Page that displays feedback form. @@ -65,7 +64,7 @@ export class AddonModFeedbackFormPage implements OnInit, OnDestroy, CanLeave { courseId!: number; feedback?: AddonModFeedbackWSFeedback; completionPageContents?: string; - component = AddonModFeedbackProvider.COMPONENT; + component = ADDON_MOD_FEEDBACK_COMPONENT; offline = false; feedbackLoaded = false; access?: AddonModFeedbackGetFeedbackAccessInformationWSResponse; @@ -356,7 +355,7 @@ export class AddonModFeedbackFormPage implements OnInit, OnDestroy, CanLeave { ]); // If form has been submitted, the info has been already invalidated but we should update index view. - CoreEvents.trigger(AddonModFeedbackProvider.FORM_SUBMITTED, { + CoreEvents.trigger(ADDON_MOD_FEEDBACK_FORM_SUBMITTED, { feedbackId: this.feedback!.id, tab: 'overview', offline: this.completedOffline, @@ -373,7 +372,7 @@ export class AddonModFeedbackFormPage implements OnInit, OnDestroy, CanLeave { // Invalidate access information so user will see home page updated (continue form). await AddonModFeedback.invalidateResumePageData(this.feedback!.id); - CoreEvents.trigger(AddonModFeedbackProvider.FORM_SUBMITTED, { + CoreEvents.trigger(ADDON_MOD_FEEDBACK_FORM_SUBMITTED, { feedbackId: this.feedback!.id, tab: 'overview', offline: this.completedOffline, @@ -395,7 +394,7 @@ export class AddonModFeedbackFormPage implements OnInit, OnDestroy, CanLeave { showAnalysis(): void { if (this.fromIndex) { // Previous page is the index page, go back. - CoreEvents.trigger(AddonModFeedbackProvider.FORM_SUBMITTED, { + CoreEvents.trigger(ADDON_MOD_FEEDBACK_FORM_SUBMITTED, { feedbackId: this.feedback!.id, tab: 'analysis', offline: this.completedOffline, @@ -406,7 +405,7 @@ export class AddonModFeedbackFormPage implements OnInit, OnDestroy, CanLeave { return; } - CoreNavigator.navigateToSitePath(AddonModFeedbackModuleHandlerService.PAGE_NAME + `/${this.courseId}/${this.cmId}`, { + CoreNavigator.navigateToSitePath(ADDON_MOD_FEEDBACK_PAGE_NAME + `/${this.courseId}/${this.cmId}`, { params: { module: this.module, tab: 'analysis', diff --git a/src/addons/mod/feedback/services/feedback-helper.ts b/src/addons/mod/feedback/services/feedback-helper.ts index 8b7f6d58a..d1cccc4f6 100644 --- a/src/addons/mod/feedback/services/feedback-helper.ts +++ b/src/addons/mod/feedback/services/feedback-helper.ts @@ -28,12 +28,18 @@ import { AddonModFeedbackGetResponsesAnalysisWSResponse, AddonModFeedbackGroupPaginatedOptions, AddonModFeedbackItem, - AddonModFeedbackProvider, AddonModFeedbackResponseValue, AddonModFeedbackWSAttempt, AddonModFeedbackWSNonRespondent, } from './feedback'; -import { AddonModFeedbackModuleHandlerService } from './handlers/module'; +import { + ADDON_MOD_FEEDBACK_LINE_SEP, + ADDON_MOD_FEEDBACK_MULTICHOICE_TYPE_SEP, + ADDON_MOD_FEEDBACK_MULTICHOICE_ADJUST_SEP, + ADDON_MOD_FEEDBACK_MULTICHOICERATED_VALUE_SEP, + ADDON_MOD_FEEDBACK_MULTICHOICE_HIDENOSELECT, + ADDON_MOD_FEEDBACK_PAGE_NAME, +} from '../constants'; const MODE_RESPONSETIME = 1; const MODE_COURSE = 2; @@ -184,7 +190,7 @@ export class AddonModFeedbackHelperProvider { if (params.showcompleted === undefined) { // Param showcompleted not defined. Show entry list. await CoreNavigator.navigateToSitePath( - AddonModFeedbackModuleHandlerService.PAGE_NAME + `/${module.course}/${module.id}/attempts`, + ADDON_MOD_FEEDBACK_PAGE_NAME + `/${module.course}/${module.id}/attempts`, { siteId }, ); @@ -198,7 +204,7 @@ export class AddonModFeedbackHelperProvider { }); await CoreNavigator.navigateToSitePath( - AddonModFeedbackModuleHandlerService.PAGE_NAME + `/${module.course}/${module.id}/attempts/${attempt.id}`, + ADDON_MOD_FEEDBACK_PAGE_NAME + `/${module.course}/${module.id}/attempts/${attempt.id}`, { params: { feedbackId: module.instance, @@ -295,7 +301,7 @@ export class AddonModFeedbackHelperProvider { */ protected getItemFormNumeric(item: AddonModFeedbackItem): AddonModFeedbackNumericItem { - const range = item.presentation.split(AddonModFeedbackProvider.LINE_SEP) || []; + const range = item.presentation.split(ADDON_MOD_FEEDBACK_LINE_SEP) || []; const rangeFrom = range.length > 0 ? parseInt(range[0], 10) : undefined; const rangeTo = range.length > 1 ? parseInt(range[1], 10) : undefined; @@ -320,7 +326,7 @@ export class AddonModFeedbackHelperProvider { protected getItemFormTextfield(item: AddonModFeedbackItem): AddonModFeedbackTextItem { return Object.assign(item, { templateName: 'textfield', - length: Number(item.presentation.split(AddonModFeedbackProvider.LINE_SEP)[1]) || 255, + length: Number(item.presentation.split(ADDON_MOD_FEEDBACK_LINE_SEP)[1]) || 255, value: item.rawValue !== undefined ? item.rawValue : '', slottedLabel: true, }); @@ -348,7 +354,7 @@ export class AddonModFeedbackHelperProvider { */ protected getItemFormMultichoice(item: AddonModFeedbackItem): AddonModFeedbackMultichoiceItem { - let parts = item.presentation.split(AddonModFeedbackProvider.MULTICHOICE_TYPE_SEP) || []; + let parts = item.presentation.split(ADDON_MOD_FEEDBACK_MULTICHOICE_TYPE_SEP) || []; const subType = parts.length > 0 && parts[0] ? parts[0] : 'r'; const formItem: AddonModFeedbackMultichoiceItem = Object.assign(item, { @@ -361,20 +367,20 @@ export class AddonModFeedbackHelperProvider { formItem.presentation = parts.length > 1 ? parts[1] : ''; if (formItem.subtype != 'd') { - parts = formItem.presentation.split(AddonModFeedbackProvider.MULTICHOICE_ADJUST_SEP) || []; + parts = formItem.presentation.split(ADDON_MOD_FEEDBACK_MULTICHOICE_ADJUST_SEP) || []; formItem.presentation = parts.length > 0 ? parts[0] : ''; // Horizontal are not supported right now. item.horizontal = parts.length > 1 && !!parts[1]; } - const choices = formItem.presentation.split(AddonModFeedbackProvider.LINE_SEP) || []; + const choices = formItem.presentation.split(ADDON_MOD_FEEDBACK_LINE_SEP) || []; formItem.choices = choices.map((choice, index) => { - const weightValue = choice.split(AddonModFeedbackProvider.MULTICHOICERATED_VALUE_SEP) || ['']; + const weightValue = choice.split(ADDON_MOD_FEEDBACK_MULTICHOICERATED_VALUE_SEP) || ['']; choice = weightValue.length == 1 ? weightValue[0] : '(' + weightValue[0] + ') ' + weightValue[1]; return { value: index + 1, label: choice }; }); - if (formItem.subtype === 'r' && formItem.options.search(AddonModFeedbackProvider.MULTICHOICE_HIDENOSELECT) == -1) { + if (formItem.subtype === 'r' && formItem.options.search(ADDON_MOD_FEEDBACK_MULTICHOICE_HIDENOSELECT) == -1) { formItem.choices.unshift({ value: 0, label: Translate.instant('addon.mod_feedback.not_selected') }); formItem.value = formItem.rawValue !== undefined ? Number(formItem.rawValue) : 0; } else if (formItem.subtype === 'd') { @@ -383,7 +389,7 @@ export class AddonModFeedbackHelperProvider { } else if (formItem.subtype === 'c') { if (formItem.rawValue !== undefined) { formItem.rawValue = String(formItem.rawValue); - const values = formItem.rawValue.split(AddonModFeedbackProvider.LINE_SEP); + const values = formItem.rawValue.split(ADDON_MOD_FEEDBACK_LINE_SEP); formItem.choices.forEach((choice) => { for (const x in values) { if (choice.value == Number(values[x])) { diff --git a/src/addons/mod/feedback/services/feedback-sync.ts b/src/addons/mod/feedback/services/feedback-sync.ts index 32f6791ef..aeaf4d6ab 100644 --- a/src/addons/mod/feedback/services/feedback-sync.ts +++ b/src/addons/mod/feedback/services/feedback-sync.ts @@ -24,9 +24,10 @@ import { CoreSync, CoreSyncResult } from '@services/sync'; import { CoreUtils } from '@services/utils/utils'; import { makeSingleton, Translate } from '@singletons'; import { CoreEvents } from '@singletons/events'; -import { AddonModFeedback, AddonModFeedbackProvider, AddonModFeedbackWSFeedback } from './feedback'; +import { AddonModFeedback, AddonModFeedbackWSFeedback } from './feedback'; import { AddonModFeedbackOffline, AddonModFeedbackOfflineResponse } from './feedback-offline'; import { AddonModFeedbackPrefetchHandler, AddonModFeedbackPrefetchHandlerService } from './handlers/prefetch'; +import { ADDON_MOD_FEEDBACK_COMPONENT } from '../constants'; /** * Service to sync feedbacks. @@ -137,7 +138,7 @@ export class AddonModFeedbackSyncProvider extends CoreCourseActivitySyncBaseProv } // Verify that feedback isn't blocked. - if (CoreSync.isBlocked(AddonModFeedbackProvider.COMPONENT, feedbackId, siteId)) { + if (CoreSync.isBlocked(ADDON_MOD_FEEDBACK_COMPONENT, feedbackId, siteId)) { this.logger.debug(`Cannot sync feedback '${feedbackId}' because it is blocked.`); throw new CoreSyncBlockedError(Translate.instant('core.errorsyncblocked', { $a: this.componentTranslate })); @@ -162,7 +163,7 @@ export class AddonModFeedbackSyncProvider extends CoreCourseActivitySyncBaseProv }; // Sync offline logs. - await CoreUtils.ignoreErrors(CoreCourseLogHelper.syncActivity(AddonModFeedbackProvider.COMPONENT, feedbackId, siteId)); + await CoreUtils.ignoreErrors(CoreCourseLogHelper.syncActivity(ADDON_MOD_FEEDBACK_COMPONENT, feedbackId, siteId)); // Get offline responses to be sent. const responses = await CoreUtils.ignoreErrors(AddonModFeedbackOffline.getFeedbackResponses(feedbackId, siteId)); diff --git a/src/addons/mod/feedback/services/feedback.ts b/src/addons/mod/feedback/services/feedback.ts index 31a29f930..a7f66bd9e 100644 --- a/src/addons/mod/feedback/services/feedback.ts +++ b/src/addons/mod/feedback/services/feedback.ts @@ -26,8 +26,15 @@ import { makeSingleton, Translate } from '@singletons'; import { AddonModFeedbackOffline } from './feedback-offline'; import { AddonModFeedbackAutoSyncData, AddonModFeedbackSyncProvider } from './feedback-sync'; import { CoreSiteWSPreSets } from '@classes/sites/authenticated-site'; - -const ROOT_CACHE_KEY = 'AddonModFeedback:'; +import { + ADDON_MOD_FEEDBACK_COMPONENT, + ADDON_MOD_FEEDBACK_FORM_SUBMITTED, + ADDON_MOD_FEEDBACK_LINE_SEP, + ADDON_MOD_FEEDBACK_MULTICHOICE_ADJUST_SEP, + ADDON_MOD_FEEDBACK_MULTICHOICE_TYPE_SEP, + ADDON_MOD_FEEDBACK_MULTICHOICERATED_VALUE_SEP, + ADDON_MOD_FEEDBACK_PER_PAGE, +} from '../constants'; /** * Service that provides some features for feedbacks. @@ -35,14 +42,7 @@ const ROOT_CACHE_KEY = 'AddonModFeedback:'; @Injectable({ providedIn: 'root' }) export class AddonModFeedbackProvider { - static readonly COMPONENT = 'mmaModFeedback'; - static readonly FORM_SUBMITTED = 'addon_mod_feedback_form_submitted'; - static readonly LINE_SEP = '|'; - static readonly MULTICHOICE_TYPE_SEP = '>>>>>'; - static readonly MULTICHOICE_ADJUST_SEP = '<<<<<'; - static readonly MULTICHOICE_HIDENOSELECT = 'h'; - static readonly MULTICHOICERATED_VALUE_SEP = '####'; - static readonly PER_PAGE = 20; + protected static readonly ROOT_CACHE_KEY = 'AddonModFeedback:'; /** * Check dependency of a question item. @@ -80,11 +80,11 @@ export class AddonModFeedbackProvider { * @returns Return true if dependency is acomplished and it can be shown. False, otherwise. */ protected compareDependItemMultichoice(item: AddonModFeedbackItem, dependValue: string): boolean { - const parts = item.presentation.split(AddonModFeedbackProvider.MULTICHOICE_TYPE_SEP) || []; + const parts = item.presentation.split(ADDON_MOD_FEEDBACK_MULTICHOICE_TYPE_SEP) || []; const subtype = parts.length > 0 && parts[0] ? parts[0] : 'r'; - const choicesStr = (parts[1] || '').split(AddonModFeedbackProvider.MULTICHOICE_ADJUST_SEP)[0] || ''; - const choices = choicesStr.split(AddonModFeedbackProvider.LINE_SEP) || []; + const choicesStr = (parts[1] || '').split(ADDON_MOD_FEEDBACK_MULTICHOICE_ADJUST_SEP)[0] || ''; + const choices = choicesStr.split(ADDON_MOD_FEEDBACK_LINE_SEP) || []; let values: AddonModFeedbackResponseValue[]; if (subtype === 'c') { @@ -92,7 +92,7 @@ export class AddonModFeedbackProvider { values = ['']; } else { item.rawValue = '' + item.rawValue; - values = item.rawValue.split(AddonModFeedbackProvider.LINE_SEP); + values = item.rawValue.split(ADDON_MOD_FEEDBACK_LINE_SEP); } } else { values = [item.rawValue || '']; @@ -104,7 +104,7 @@ export class AddonModFeedbackProvider { let value = choices[index]; if (item.typ == 'multichoicerated') { - value = value.split(AddonModFeedbackProvider.MULTICHOICERATED_VALUE_SEP)[1] || ''; + value = value.split(ADDON_MOD_FEEDBACK_MULTICHOICERATED_VALUE_SEP)[1] || ''; } if (value.trim() == dependValue) { @@ -195,10 +195,10 @@ export class AddonModFeedbackProvider { } // Treat multichoice checkboxes. - if (item.typ === 'multichoice' && item.presentation.split(AddonModFeedbackProvider.MULTICHOICE_TYPE_SEP)[0] === 'c') { + if (item.typ === 'multichoice' && item.presentation.split(ADDON_MOD_FEEDBACK_MULTICHOICE_TYPE_SEP)[0] === 'c') { offlineValues[item.id] = offlineValues[item.id].filter((value) => Number(value) > 0); - item.rawValue = offlineValues[item.id].join(AddonModFeedbackProvider.LINE_SEP); + item.rawValue = offlineValues[item.id].join(ADDON_MOD_FEEDBACK_LINE_SEP); } else { item.rawValue = offlineValues[item.id][0]; } @@ -314,7 +314,7 @@ export class AddonModFeedbackProvider { }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getAnalysisDataCacheKey(feedbackId, options.groupId), - component: AddonModFeedbackProvider.COMPONENT, + component: ADDON_MOD_FEEDBACK_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -429,7 +429,7 @@ export class AddonModFeedbackProvider { }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getCurrentCompletedTimeModifiedDataCacheKey(feedbackId), - component: AddonModFeedbackProvider.COMPONENT, + component: ADDON_MOD_FEEDBACK_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -476,7 +476,7 @@ export class AddonModFeedbackProvider { }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getCurrentValuesDataCacheKey(feedbackId), - component: AddonModFeedbackProvider.COMPONENT, + component: ADDON_MOD_FEEDBACK_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -529,7 +529,7 @@ export class AddonModFeedbackProvider { }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getFeedbackAccessInformationDataCacheKey(feedbackId), - component: AddonModFeedbackProvider.COMPONENT, + component: ADDON_MOD_FEEDBACK_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -554,7 +554,7 @@ export class AddonModFeedbackProvider { * @returns Cache key. */ protected getFeedbackCacheKey(courseId: number): string { - return ROOT_CACHE_KEY + 'feedback:' + courseId; + return AddonModFeedbackProvider.ROOT_CACHE_KEY + 'feedback:' + courseId; } /** @@ -564,7 +564,7 @@ export class AddonModFeedbackProvider { * @returns Cache key. */ protected getFeedbackDataPrefixCacheKey(feedbackId: number): string { - return ROOT_CACHE_KEY + feedbackId; + return AddonModFeedbackProvider.ROOT_CACHE_KEY + feedbackId; } /** @@ -590,7 +590,7 @@ export class AddonModFeedbackProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getFeedbackCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, - component: AddonModFeedbackProvider.COMPONENT, + component: ADDON_MOD_FEEDBACK_COMPONENT, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -648,7 +648,7 @@ export class AddonModFeedbackProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getItemsDataCacheKey(feedbackId), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, - component: AddonModFeedbackProvider.COMPONENT, + component: ADDON_MOD_FEEDBACK_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -686,11 +686,11 @@ export class AddonModFeedbackProvider { feedbackid: feedbackId, groupid: options.groupId, page: options.page, - perpage: AddonModFeedbackProvider.PER_PAGE, + perpage: ADDON_MOD_FEEDBACK_PER_PAGE, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getNonRespondentsDataCacheKey(feedbackId, options.groupId), - component: AddonModFeedbackProvider.COMPONENT, + component: ADDON_MOD_FEEDBACK_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -862,11 +862,11 @@ export class AddonModFeedbackProvider { feedbackid: feedbackId, groupid: options.groupId, page: options.page, - perpage: AddonModFeedbackProvider.PER_PAGE, + perpage: ADDON_MOD_FEEDBACK_PER_PAGE, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getResponsesAnalysisDataCacheKey(feedbackId, options.groupId), - component: AddonModFeedbackProvider.COMPONENT, + component: ADDON_MOD_FEEDBACK_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -910,7 +910,7 @@ export class AddonModFeedbackProvider { }; const preSets = { cacheKey: this.getResumePageDataCacheKey(feedbackId), - component: AddonModFeedbackProvider.COMPONENT, + component: ADDON_MOD_FEEDBACK_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -1024,7 +1024,7 @@ export class AddonModFeedbackProvider { * @returns Promise resolved when the files are invalidated. */ async invalidateFiles(moduleId: number, siteId?: string): Promise { - return CoreFilepool.invalidateFilesByComponent(siteId, AddonModFeedbackProvider.COMPONENT, moduleId); + return CoreFilepool.invalidateFilesByComponent(siteId, ADDON_MOD_FEEDBACK_COMPONENT, moduleId); } /** @@ -1082,7 +1082,7 @@ export class AddonModFeedbackProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getCompletedDataCacheKey(feedbackId), updateFrequency: CoreSite.FREQUENCY_RARELY, - component: AddonModFeedbackProvider.COMPONENT, + component: ADDON_MOD_FEEDBACK_COMPONENT, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -1106,7 +1106,7 @@ export class AddonModFeedbackProvider { await CoreCourseLogHelper.log( 'mod_feedback_view_feedback', params, - AddonModFeedbackProvider.COMPONENT, + ADDON_MOD_FEEDBACK_COMPONENT, id, siteId, ); @@ -1252,7 +1252,7 @@ declare module '@singletons/events' { * @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation */ export interface CoreEventsData { - [AddonModFeedbackProvider.FORM_SUBMITTED]: AddonModFeedbackFormSubmittedData; + [ADDON_MOD_FEEDBACK_FORM_SUBMITTED]: AddonModFeedbackFormSubmittedData; [AddonModFeedbackSyncProvider.AUTO_SYNCED]: AddonModFeedbackAutoSyncData; } diff --git a/src/addons/mod/feedback/services/handlers/analysis-link.ts b/src/addons/mod/feedback/services/handlers/analysis-link.ts index 128fc9859..6ad0dce15 100644 --- a/src/addons/mod/feedback/services/handlers/analysis-link.ts +++ b/src/addons/mod/feedback/services/handlers/analysis-link.ts @@ -19,7 +19,7 @@ import { CoreCourse } from '@features/course/services/course'; import { CoreNavigator } from '@services/navigator'; import { CoreDomUtils } from '@services/utils/dom'; import { makeSingleton } from '@singletons'; -import { AddonModFeedbackModuleHandlerService } from './module'; +import { ADDON_MOD_FEEDBACK_PAGE_NAME } from '../../constants'; /** * Content links handler for a feedback analysis. @@ -54,7 +54,7 @@ export class AddonModFeedbackAnalysisLinkHandlerService extends CoreContentLinks ); await CoreNavigator.navigateToSitePath( - AddonModFeedbackModuleHandlerService.PAGE_NAME + `/${module.course}/${module.id}`, + ADDON_MOD_FEEDBACK_PAGE_NAME + `/${module.course}/${module.id}`, { params: { module, diff --git a/src/addons/mod/feedback/services/handlers/complete-link.ts b/src/addons/mod/feedback/services/handlers/complete-link.ts index 8b1f2ebb6..2a3d6caab 100644 --- a/src/addons/mod/feedback/services/handlers/complete-link.ts +++ b/src/addons/mod/feedback/services/handlers/complete-link.ts @@ -20,7 +20,7 @@ import { CoreNavigator } from '@services/navigator'; import { CoreSitesReadingStrategy } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { makeSingleton } from '@singletons'; -import { AddonModFeedbackModuleHandlerService } from './module'; +import { ADDON_MOD_FEEDBACK_PAGE_NAME } from '../../constants'; /** * Content links handler for feedback complete questions. @@ -50,7 +50,7 @@ export class AddonModFeedbackCompleteLinkHandlerService extends CoreContentLinks ); await CoreNavigator.navigateToSitePath( - AddonModFeedbackModuleHandlerService.PAGE_NAME + `/${module.course}/${module.id}/form`, + ADDON_MOD_FEEDBACK_PAGE_NAME + `/${module.course}/${module.id}/form`, { params: { page: params.gopage !== undefined ? Number(params.gopage) : undefined, diff --git a/src/addons/mod/feedback/services/handlers/module.ts b/src/addons/mod/feedback/services/handlers/module.ts index a1495d718..463d84c19 100644 --- a/src/addons/mod/feedback/services/handlers/module.ts +++ b/src/addons/mod/feedback/services/handlers/module.ts @@ -17,6 +17,7 @@ import { Injectable, Type } from '@angular/core'; import { CoreCourseModuleHandler } from '@features/course/services/module-delegate'; import { makeSingleton } from '@singletons'; import { CoreModuleHandlerBase } from '@features/course/classes/module-base-handler'; +import { ADDON_MOD_FEEDBACK_PAGE_NAME } from '../../constants'; /** * Handler to support feedback modules. @@ -24,11 +25,9 @@ import { CoreModuleHandlerBase } from '@features/course/classes/module-base-hand @Injectable({ providedIn: 'root' }) export class AddonModFeedbackModuleHandlerService extends CoreModuleHandlerBase implements CoreCourseModuleHandler { - static readonly PAGE_NAME = 'mod_feedback'; - name = 'AddonModFeedback'; modName = 'feedback'; - protected pageName = AddonModFeedbackModuleHandlerService.PAGE_NAME; + protected pageName = ADDON_MOD_FEEDBACK_PAGE_NAME; supportedFeatures = { [CoreConstants.FEATURE_GROUPS]: true, diff --git a/src/addons/mod/feedback/services/handlers/prefetch.ts b/src/addons/mod/feedback/services/handlers/prefetch.ts index 058465519..576c841fd 100644 --- a/src/addons/mod/feedback/services/handlers/prefetch.ts +++ b/src/addons/mod/feedback/services/handlers/prefetch.ts @@ -25,10 +25,10 @@ import { makeSingleton } from '@singletons'; import { AddonModFeedback, AddonModFeedbackGetFeedbackAccessInformationWSResponse, - AddonModFeedbackProvider, AddonModFeedbackWSFeedback, } from '../feedback'; import { AddonModFeedbackSync, AddonModFeedbackSyncResult } from '../feedback-sync'; +import { ADDON_MOD_FEEDBACK_COMPONENT } from '../../constants'; /** * Handler to prefetch feedbacks. @@ -38,7 +38,7 @@ export class AddonModFeedbackPrefetchHandlerService extends CoreCourseActivityPr name = 'AddonModFeedback'; modName = 'feedback'; - component = AddonModFeedbackProvider.COMPONENT; + component = ADDON_MOD_FEEDBACK_COMPONENT; updatesNames = /^configuration$|^.*files$|^attemptsfinished|^attemptsunfinished$/; /** diff --git a/src/addons/mod/feedback/services/handlers/print-link.ts b/src/addons/mod/feedback/services/handlers/print-link.ts index 9196b9e59..abbb8d575 100644 --- a/src/addons/mod/feedback/services/handlers/print-link.ts +++ b/src/addons/mod/feedback/services/handlers/print-link.ts @@ -20,7 +20,7 @@ import { CoreNavigator } from '@services/navigator'; import { CoreSitesReadingStrategy } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { makeSingleton } from '@singletons'; -import { AddonModFeedbackModuleHandlerService } from './module'; +import { ADDON_MOD_FEEDBACK_PAGE_NAME } from '../../constants'; /** * Content links handler for feedback print questions. @@ -50,7 +50,7 @@ export class AddonModFeedbackPrintLinkHandlerService extends CoreContentLinksHan ); await CoreNavigator.navigateToSitePath( - AddonModFeedbackModuleHandlerService.PAGE_NAME + `/${module.course}/${module.id}/form`, + ADDON_MOD_FEEDBACK_PAGE_NAME + `/${module.course}/${module.id}/form`, { params: { preview: true, diff --git a/src/addons/mod/feedback/services/handlers/show-non-respondents-link.ts b/src/addons/mod/feedback/services/handlers/show-non-respondents-link.ts index ea6e054ef..7ef4fdc21 100644 --- a/src/addons/mod/feedback/services/handlers/show-non-respondents-link.ts +++ b/src/addons/mod/feedback/services/handlers/show-non-respondents-link.ts @@ -20,7 +20,7 @@ import { CoreNavigator } from '@services/navigator'; import { CoreSitesReadingStrategy } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { makeSingleton } from '@singletons'; -import { AddonModFeedbackModuleHandlerService } from './module'; +import { ADDON_MOD_FEEDBACK_PAGE_NAME } from '../../constants'; /** * Content links handler for feedback show non respondents. * Match mod/feedback/show_nonrespondents.php with a valid feedback id. @@ -49,7 +49,7 @@ export class AddonModFeedbackShowNonRespondentsLinkHandlerService extends CoreCo ); await CoreNavigator.navigateToSitePath( - AddonModFeedbackModuleHandlerService.PAGE_NAME + `/${module.course}/${module.id}/nonrespondents`, + ADDON_MOD_FEEDBACK_PAGE_NAME + `/${module.course}/${module.id}/nonrespondents`, { siteId }, ); } catch (error) { From 09791c8d20905e1596cfd51c384a6863d804d5b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Thu, 11 Jul 2024 22:40:39 +0200 Subject: [PATCH 07/26] MOBILE-4616 data: Move data constants to a file --- .../mod/data/components/action/action.ts | 9 ++-- src/addons/mod/data/components/index/index.ts | 31 +++++++------ src/addons/mod/data/constants.ts | 8 ++++ src/addons/mod/data/data-lazy.module.ts | 2 +- src/addons/mod/data/data.module.ts | 10 ++-- .../mod/data/fields/file/component/file.ts | 5 +- .../mod/data/fields/file/services/handler.ts | 6 +-- .../data/fields/picture/component/picture.ts | 5 +- .../data/fields/picture/services/handler.ts | 4 +- .../fields/textarea/component/textarea.ts | 5 +- src/addons/mod/data/pages/edit/edit.ts | 6 +-- src/addons/mod/data/pages/entry/entry.ts | 17 ++++--- src/addons/mod/data/services/data-helper.ts | 8 ++-- src/addons/mod/data/services/data-sync.ts | 13 +++--- src/addons/mod/data/services/data.ts | 46 ++++++++++--------- .../mod/data/services/handlers/edit-link.ts | 5 +- .../mod/data/services/handlers/module.ts | 5 +- .../mod/data/services/handlers/prefetch.ts | 5 +- .../mod/data/services/handlers/show-link.ts | 5 +- 19 files changed, 107 insertions(+), 88 deletions(-) diff --git a/src/addons/mod/data/components/action/action.ts b/src/addons/mod/data/components/action/action.ts index 9105af4ab..f328e90fc 100644 --- a/src/addons/mod/data/components/action/action.ts +++ b/src/addons/mod/data/components/action/action.ts @@ -24,14 +24,13 @@ import { AddonModDataData, AddonModDataEntry, AddonModDataGetDataAccessInformationWSResponse, - AddonModDataProvider, AddonModDataTemplateMode, } from '../../services/data'; import { AddonModDataHelper } from '../../services/data-helper'; import { AddonModDataOffline } from '../../services/data-offline'; -import { AddonModDataModuleHandlerService } from '../../services/handlers/module'; import { CoreDomUtils } from '@services/utils/dom'; import { AddonModDataActionsMenuComponent, AddonModDataActionsMenuItem } from '../actionsmenu/actionsmenu'; +import { ADDON_MOD_DATA_ENTRY_CHANGED, ADDON_MOD_DATA_PAGE_NAME } from '../../constants'; /** * Component that displays a database action. @@ -101,7 +100,7 @@ export class AddonModDataActionComponent implements OnInit { title: this.title, }; - const basePath = AddonModDataModuleHandlerService.PAGE_NAME; + const basePath = ADDON_MOD_DATA_PAGE_NAME; CoreNavigator.navigateToSitePath( `${basePath}/${this.database.course}/${this.database.coursemodule}/edit/${this.entry.id}`, { params }, @@ -120,7 +119,7 @@ export class AddonModDataActionComponent implements OnInit { sortDirection: this.sortDirection, }; - const basePath = AddonModDataModuleHandlerService.PAGE_NAME; + const basePath = ADDON_MOD_DATA_PAGE_NAME; CoreNavigator.navigateToSitePath( `${basePath}/${this.database.course}/${this.database.coursemodule}/${this.entry.id}`, { params }, @@ -140,7 +139,7 @@ export class AddonModDataActionComponent implements OnInit { // Found. Just delete the action. await AddonModDataOffline.deleteEntry(dataId, entryId, AddonModDataAction.DELETE, this.siteId); - CoreEvents.trigger(AddonModDataProvider.ENTRY_CHANGED, { dataId: dataId, entryId: entryId }, this.siteId); + CoreEvents.trigger(ADDON_MOD_DATA_ENTRY_CHANGED, { dataId: dataId, entryId: entryId }, this.siteId); } /** diff --git a/src/addons/mod/data/components/index/index.ts b/src/addons/mod/data/components/index/index.ts index 3b6c939d6..71293910a 100644 --- a/src/addons/mod/data/components/index/index.ts +++ b/src/addons/mod/data/components/index/index.ts @@ -29,7 +29,6 @@ import { CoreTimeUtils } from '@services/utils/time'; import { CoreUtils } from '@services/utils/utils'; import { CoreEventObserver, CoreEvents } from '@singletons/events'; import { - AddonModDataProvider, AddonModData, AddonModDataEntry, AddonModDataTemplateType, @@ -40,13 +39,19 @@ import { AddonModDataSearchEntriesAdvancedField, } from '../../services/data'; import { AddonModDataHelper, AddonModDatDisplayFieldsOptions } from '../../services/data-helper'; -import { AddonModDataAutoSyncData, AddonModDataSyncProvider, AddonModDataSyncResult } from '../../services/data-sync'; -import { AddonModDataModuleHandlerService } from '../../services/handlers/module'; +import { AddonModDataAutoSyncData, AddonModDataSyncResult } from '../../services/data-sync'; import { AddonModDataPrefetchHandler } from '../../services/handlers/prefetch'; import { AddonModDataComponentsCompileModule } from '../components-compile.module'; import { AddonModDataSearchComponent } from '../search/search'; import { CoreUrlUtils } from '@services/utils/url'; import { CoreTime } from '@singletons/time'; +import { + ADDON_MOD_DATA_AUTO_SYNCED, + ADDON_MOD_DATA_COMPONENT, + ADDON_MOD_DATA_ENTRIES_PER_PAGE, + ADDON_MOD_DATA_ENTRY_CHANGED, + ADDON_MOD_DATA_PAGE_NAME, +} from '../../constants'; const contentToken = ''; @@ -60,7 +65,7 @@ const contentToken = ''; }) export class AddonModDataIndexComponent extends CoreCourseModuleMainActivityComponent implements OnInit, OnDestroy { - component = AddonModDataProvider.COMPONENT; + component = ADDON_MOD_DATA_COMPONENT; pluginName = 'data'; access?: AddonModDataGetDataAccessInformationWSResponse; @@ -110,7 +115,7 @@ export class AddonModDataIndexComponent extends CoreCourseModuleMainActivityComp hasOfflineRatings = false; - protected syncEventName = AddonModDataSyncProvider.AUTO_SYNCED; + protected syncEventName = ADDON_MOD_DATA_AUTO_SYNCED; protected hasComments = false; protected fieldsArray: AddonModDataField[] = []; protected entryChangedObserver?: CoreEventObserver; @@ -134,7 +139,7 @@ export class AddonModDataIndexComponent extends CoreCourseModuleMainActivityComp this.selectedGroup = this.group || 0; // Refresh entries on change. - this.entryChangedObserver = CoreEvents.on(AddonModDataProvider.ENTRY_CHANGED, (eventData) => { + this.entryChangedObserver = CoreEvents.on(ADDON_MOD_DATA_ENTRY_CHANGED, (eventData) => { if (this.database?.id == eventData.dataId) { this.showLoading = true; @@ -303,8 +308,8 @@ export class AddonModDataIndexComponent extends CoreCourseModuleMainActivityComp this.isEmpty = !numEntries && !numOfflineEntries; - this.hasNextPage = numEntries >= AddonModDataProvider.PER_PAGE && ((this.search.page + 1) * - AddonModDataProvider.PER_PAGE) < entries.totalcount; + this.hasNextPage = numEntries >= ADDON_MOD_DATA_ENTRIES_PER_PAGE && ((this.search.page + 1) * + ADDON_MOD_DATA_ENTRIES_PER_PAGE) < entries.totalcount; this.hasOffline = !!entries.hasOfflineActions; @@ -355,7 +360,7 @@ export class AddonModDataIndexComponent extends CoreCourseModuleMainActivityComp const actions = AddonModDataHelper.getActions(this.database!, this.access!, entry, AddonModDataTemplateMode.LIST); const options: AddonModDatDisplayFieldsOptions = {}; if (!this.search.searching) { - options.offset = this.search.page * AddonModDataProvider.PER_PAGE + index - numOfflineEntries; + options.offset = this.search.page * ADDON_MOD_DATA_ENTRIES_PER_PAGE + index - numOfflineEntries; options.sortBy = this.search.sortBy; options.sortDirection = this.search.sortDirection; } @@ -489,7 +494,7 @@ export class AddonModDataIndexComponent extends CoreCourseModuleMainActivityComp }; CoreNavigator.navigateToSitePath( - `${AddonModDataModuleHandlerService.PAGE_NAME}/${this.courseId}/${this.module.id}/edit`, + `${ADDON_MOD_DATA_PAGE_NAME}/${this.courseId}/${this.module.id}/edit`, { params }, ); } @@ -509,14 +514,14 @@ export class AddonModDataIndexComponent extends CoreCourseModuleMainActivityComp if (!this.search.searching) { const pageXOffset = this.entries.findIndex((entry) => entry.id == entryId); if (pageXOffset >= 0) { - params.offset = this.search.page * AddonModDataProvider.PER_PAGE + pageXOffset; + params.offset = this.search.page * ADDON_MOD_DATA_ENTRIES_PER_PAGE + pageXOffset; params.sortBy = this.search.sortBy; params.sortDirection = this.search.sortDirection; } } CoreNavigator.navigateToSitePath( - `${AddonModDataModuleHandlerService.PAGE_NAME}/${this.courseId}/${this.module.id}/${entryId}`, + `${ADDON_MOD_DATA_PAGE_NAME}/${this.courseId}/${this.module.id}/${entryId}`, { params }, ); } @@ -550,7 +555,7 @@ export class AddonModDataIndexComponent extends CoreCourseModuleMainActivityComp } const params: Record = { - perpage: AddonModDataProvider.PER_PAGE, + perpage: ADDON_MOD_DATA_ENTRIES_PER_PAGE, search: !this.search.searchingAdvanced ? this.search.text : '', sort: this.search.sortBy, order: this.search.sortDirection, diff --git a/src/addons/mod/data/constants.ts b/src/addons/mod/data/constants.ts index 9abfb84d2..97bde3afb 100644 --- a/src/addons/mod/data/constants.ts +++ b/src/addons/mod/data/constants.ts @@ -13,3 +13,11 @@ // limitations under the License. export const ADDON_MOD_DATA_FEATURE_NAME = 'CoreCourseModuleDelegate_AddonModData'; + +export const ADDON_MOD_DATA_COMPONENT = 'mmaModData'; +export const ADDON_MOD_DATA_PAGE_NAME = 'mod_data'; + +export const ADDON_MOD_DATA_ENTRIES_PER_PAGE = 25; + +export const ADDON_MOD_DATA_ENTRY_CHANGED = 'addon_mod_data_entry_changed'; +export const ADDON_MOD_DATA_AUTO_SYNCED = 'addon_mod_data_autom_synced'; diff --git a/src/addons/mod/data/data-lazy.module.ts b/src/addons/mod/data/data-lazy.module.ts index e1f6f4dee..f144fcb7b 100644 --- a/src/addons/mod/data/data-lazy.module.ts +++ b/src/addons/mod/data/data-lazy.module.ts @@ -62,4 +62,4 @@ const routes: Routes = [ AddonModDataEditPage, ], }) -export class AddonModDataLazyModule {} +export default class AddonModDataLazyModule {} diff --git a/src/addons/mod/data/data.module.ts b/src/addons/mod/data/data.module.ts index dc7816a58..1388c9771 100644 --- a/src/addons/mod/data/data.module.ts +++ b/src/addons/mod/data/data.module.ts @@ -21,25 +21,25 @@ import { CoreMainMenuTabRoutingModule } from '@features/mainmenu/mainmenu-tab-ro import { CoreTagAreaDelegate } from '@features/tag/services/tag-area-delegate'; import { CoreCronDelegate } from '@services/cron'; import { CORE_SITE_SCHEMAS } from '@services/sites'; -import { AddonModDataProvider } from './services/data'; import { ADDON_MOD_DATA_OFFLINE_SITE_SCHEMA } from './services/database/data'; import { AddonModDataApproveLinkHandler } from './services/handlers/approve-link'; import { AddonModDataDeleteLinkHandler } from './services/handlers/delete-link'; import { AddonModDataEditLinkHandler } from './services/handlers/edit-link'; import { AddonModDataIndexLinkHandler } from './services/handlers/index-link'; import { AddonModDataListLinkHandler } from './services/handlers/list-link'; -import { AddonModDataModuleHandler, AddonModDataModuleHandlerService } from './services/handlers/module'; +import { AddonModDataModuleHandler } from './services/handlers/module'; import { AddonModDataPrefetchHandler } from './services/handlers/prefetch'; import { AddonModDataShowLinkHandler } from './services/handlers/show-link'; import { AddonModDataSyncCronHandler } from './services/handlers/sync-cron'; import { AddonModDataTagAreaHandler } from './services/handlers/tag-area'; import { AddonModDataFieldModule } from './fields/field.module'; import { CoreCourseHelper } from '@features/course/services/course-helper'; +import { ADDON_MOD_DATA_COMPONENT, ADDON_MOD_DATA_PAGE_NAME } from './constants'; const routes: Routes = [ { - path: AddonModDataModuleHandlerService.PAGE_NAME, - loadChildren: () => import('./data-lazy.module').then(m => m.AddonModDataLazyModule), + path: ADDON_MOD_DATA_PAGE_NAME, + loadChildren: () => import('./data-lazy.module'), }, ]; @@ -69,7 +69,7 @@ const routes: Routes = [ CoreContentLinksDelegate.registerHandler(AddonModDataEditLinkHandler.instance); CoreTagAreaDelegate.registerHandler(AddonModDataTagAreaHandler.instance); - CoreCourseHelper.registerModuleReminderClick(AddonModDataProvider.COMPONENT); + CoreCourseHelper.registerModuleReminderClick(ADDON_MOD_DATA_COMPONENT); }, }, ], diff --git a/src/addons/mod/data/fields/file/component/file.ts b/src/addons/mod/data/fields/file/component/file.ts index 210596929..901f1db10 100644 --- a/src/addons/mod/data/fields/file/component/file.ts +++ b/src/addons/mod/data/fields/file/component/file.ts @@ -13,10 +13,11 @@ // limitations under the License. import { Component } from '@angular/core'; -import { AddonModDataEntryField, AddonModDataProvider } from '@addons/mod/data/services/data'; +import { AddonModDataEntryField } from '@addons/mod/data/services/data'; import { AddonModDataFieldPluginBaseComponent } from '@addons/mod/data/classes/base-field-plugin-component'; import { CoreFileSession } from '@services/file-session'; import { CoreFileEntry } from '@services/file-helper'; +import { ADDON_MOD_DATA_COMPONENT } from '@addons/mod/data/constants'; /** * Component to render data file field. @@ -59,7 +60,7 @@ export class AddonModDataFieldFileComponent extends AddonModDataFieldPluginBaseC return; } - this.component = AddonModDataProvider.COMPONENT; + this.component = ADDON_MOD_DATA_COMPONENT; this.componentId = this.database!.coursemodule; this.updateValue(this.value); diff --git a/src/addons/mod/data/fields/file/services/handler.ts b/src/addons/mod/data/fields/file/services/handler.ts index 28db29431..a4f9d83ef 100644 --- a/src/addons/mod/data/fields/file/services/handler.ts +++ b/src/addons/mod/data/fields/file/services/handler.ts @@ -15,7 +15,6 @@ import { AddonModDataEntryField, AddonModDataField, - AddonModDataProvider, AddonModDataSearchEntriesAdvancedFieldFormatted, AddonModDataSubfieldData, } from '@addons/mod/data/services/data'; @@ -29,6 +28,7 @@ import { makeSingleton, Translate } from '@singletons'; import { AddonModDataFieldFileComponent } from '../component/file'; import { CoreFileEntry } from '@services/file-helper'; import type { AddonModDataFieldPluginBaseComponent } from '@addons/mod/data/classes/base-field-plugin-component'; +import { ADDON_MOD_DATA_COMPONENT } from '@addons/mod/data/constants'; /** * Handler for file data field plugin. @@ -79,14 +79,14 @@ export class AddonModDataFieldFileHandlerService implements AddonModDataFieldHan * @inheritdoc */ getFieldEditFiles(field: AddonModDataField): CoreFileEntry[] { - return CoreFileSession.getFiles(AddonModDataProvider.COMPONENT, field.dataid + '_' + field.id); + return CoreFileSession.getFiles(ADDON_MOD_DATA_COMPONENT, field.dataid + '_' + field.id); } /** * @inheritdoc */ hasFieldDataChanged(field: AddonModDataField, inputData: CoreFormFields, originalFieldData: AddonModDataEntryField): boolean { - const files = CoreFileSession.getFiles(AddonModDataProvider.COMPONENT, field.dataid + '_' + field.id) || []; + const files = CoreFileSession.getFiles(ADDON_MOD_DATA_COMPONENT, field.dataid + '_' + field.id) || []; let originalFiles = (originalFieldData && originalFieldData.files) || []; if (originalFiles.length) { diff --git a/src/addons/mod/data/fields/picture/component/picture.ts b/src/addons/mod/data/fields/picture/component/picture.ts index ef9f58e50..6577d1b8f 100644 --- a/src/addons/mod/data/fields/picture/component/picture.ts +++ b/src/addons/mod/data/fields/picture/component/picture.ts @@ -12,13 +12,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { AddonModDataEntryField, AddonModDataProvider } from '@addons/mod/data/services/data'; +import { AddonModDataEntryField } from '@addons/mod/data/services/data'; import { Component } from '@angular/core'; import { CoreFileEntry, CoreFileHelper } from '@services/file-helper'; import { CoreFileSession } from '@services/file-session'; import { CoreDomUtils } from '@services/utils/dom'; import { AddonModDataFieldPluginBaseComponent } from '../../../classes/base-field-plugin-component'; import { CoreFile } from '@services/file'; +import { ADDON_MOD_DATA_COMPONENT } from '@addons/mod/data/constants'; /** * Component to render data picture field. @@ -82,7 +83,7 @@ export class AddonModDataFieldPictureComponent extends AddonModDataFieldPluginBa return; } - this.component = AddonModDataProvider.COMPONENT; + this.component = ADDON_MOD_DATA_COMPONENT; this.componentId = this.database!.coursemodule; this.updateValue(this.value); diff --git a/src/addons/mod/data/fields/picture/services/handler.ts b/src/addons/mod/data/fields/picture/services/handler.ts index 809f3ef7f..4241bd609 100644 --- a/src/addons/mod/data/fields/picture/services/handler.ts +++ b/src/addons/mod/data/fields/picture/services/handler.ts @@ -15,7 +15,6 @@ import { AddonModDataEntryField, AddonModDataField, - AddonModDataProvider, AddonModDataSearchEntriesAdvancedFieldFormatted, AddonModDataSubfieldData, } from '@addons/mod/data/services/data'; @@ -29,6 +28,7 @@ import { makeSingleton, Translate } from '@singletons'; import { AddonModDataFieldPictureComponent } from '../component/picture'; import { CoreFileEntry } from '@services/file-helper'; import type { AddonModDataFieldPluginBaseComponent } from '@addons/mod/data/classes/base-field-plugin-component'; +import { ADDON_MOD_DATA_COMPONENT } from '@addons/mod/data/constants'; /** * Handler for picture data field plugin. @@ -90,7 +90,7 @@ export class AddonModDataFieldPictureHandlerService implements AddonModDataField * @inheritdoc */ getFieldEditFiles(field: AddonModDataField): CoreFileEntry[] { - return CoreFileSession.getFiles(AddonModDataProvider.COMPONENT, field.dataid + '_' + field.id); + return CoreFileSession.getFiles(ADDON_MOD_DATA_COMPONENT, field.dataid + '_' + field.id); } /** diff --git a/src/addons/mod/data/fields/textarea/component/textarea.ts b/src/addons/mod/data/fields/textarea/component/textarea.ts index eabe4fd01..13960a700 100644 --- a/src/addons/mod/data/fields/textarea/component/textarea.ts +++ b/src/addons/mod/data/fields/textarea/component/textarea.ts @@ -14,9 +14,10 @@ import { Component } from '@angular/core'; import { AddonModDataFieldPluginBaseComponent } from '../../../classes/base-field-plugin-component'; -import { AddonModDataEntryField, AddonModDataProvider } from '@addons/mod/data/services/data'; +import { AddonModDataEntryField } from '@addons/mod/data/services/data'; import { CoreTextUtils } from '@services/utils/text'; import { CoreWSFile } from '@services/ws'; +import { ADDON_MOD_DATA_COMPONENT } from '@addons/mod/data/constants'; /** * Component to render data number field. @@ -46,7 +47,7 @@ export class AddonModDataFieldTextareaComponent extends AddonModDataFieldPluginB * Initialize field. */ protected init(): void { - this.component = AddonModDataProvider.COMPONENT; + this.component = ADDON_MOD_DATA_COMPONENT; this.componentId = this.database?.coursemodule; if (this.displayMode) { diff --git a/src/addons/mod/data/pages/edit/edit.ts b/src/addons/mod/data/pages/edit/edit.ts index 4946a6800..c48a102dc 100644 --- a/src/addons/mod/data/pages/edit/edit.ts +++ b/src/addons/mod/data/pages/edit/edit.ts @@ -30,7 +30,6 @@ import { AddonModDataComponentsCompileModule } from '../../components/components import { AddonModDataData, AddonModDataField, - AddonModDataProvider, AddonModData, AddonModDataTemplateType, AddonModDataEntry, @@ -45,6 +44,7 @@ import { AddonModDataEntryFieldInitialized } from '../../classes/base-field-plug import { CoreTextUtils } from '@services/utils/text'; import { CoreTime } from '@singletons/time'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; +import { ADDON_MOD_DATA_COMPONENT, ADDON_MOD_DATA_ENTRY_CHANGED } from '../../constants'; /** * Page that displays the view edit page. @@ -75,7 +75,7 @@ export class AddonModDataEditPage implements OnInit { moduleId = 0; database?: AddonModDataData; title = ''; - component = AddonModDataProvider.COMPONENT; + component = ADDON_MOD_DATA_COMPONENT; loaded = false; selectedGroup = 0; cssClass = ''; @@ -369,7 +369,7 @@ export class AddonModDataEditPage implements OnInit { try { await Promise.all(promises); CoreEvents.trigger( - AddonModDataProvider.ENTRY_CHANGED, + ADDON_MOD_DATA_ENTRY_CHANGED, { dataId: this.database!.id, entryId: this.entryId }, this.siteId, diff --git a/src/addons/mod/data/pages/entry/entry.ts b/src/addons/mod/data/pages/entry/entry.ts index 1c46e26ef..32fc339d0 100644 --- a/src/addons/mod/data/pages/entry/entry.ts +++ b/src/addons/mod/data/pages/entry/entry.ts @@ -25,7 +25,7 @@ import { CoreDomUtils } from '@services/utils/dom'; import { CoreUtils } from '@services/utils/utils'; import { CoreEventObserver, CoreEvents } from '@singletons/events'; import { AddonModDataComponentsCompileModule } from '../../components/components-compile.module'; -import { AddonModDataProvider, +import { AddonModData, AddonModDataData, AddonModDataGetDataAccessInformationWSResponse, @@ -35,9 +35,14 @@ import { AddonModDataProvider, AddonModDataEntry, } from '../../services/data'; import { AddonModDataHelper } from '../../services/data-helper'; -import { AddonModDataSyncProvider } from '../../services/data-sync'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; import { CoreTime } from '@singletons/time'; +import { + ADDON_MOD_DATA_AUTO_SYNCED, + ADDON_MOD_DATA_COMPONENT, + ADDON_MOD_DATA_ENTRIES_PER_PAGE, + ADDON_MOD_DATA_ENTRY_CHANGED, +} from '../../constants'; /** * Page that displays the view entry page. @@ -66,7 +71,7 @@ export class AddonModDataEntryPage implements OnInit, OnDestroy { offset?: number; title = ''; moduleName = 'data'; - component = AddonModDataProvider.COMPONENT; + component = ADDON_MOD_DATA_COMPONENT; entryLoaded = false; renderingEntry = false; loadingComments = false; @@ -102,7 +107,7 @@ export class AddonModDataEntryPage implements OnInit, OnDestroy { this.siteId = CoreSites.getCurrentSiteId(); // Refresh data if this discussion is synchronized automatically. - this.syncObserver = CoreEvents.on(AddonModDataSyncProvider.AUTO_SYNCED, (data) => { + this.syncObserver = CoreEvents.on(ADDON_MOD_DATA_AUTO_SYNCED, (data) => { if (data.entryId === undefined) { return; } @@ -120,7 +125,7 @@ export class AddonModDataEntryPage implements OnInit, OnDestroy { }, this.siteId); // Refresh entry on change. - this.entryChangedObserver = CoreEvents.on(AddonModDataProvider.ENTRY_CHANGED, (data) => { + this.entryChangedObserver = CoreEvents.on(ADDON_MOD_DATA_ENTRY_CHANGED, (data) => { if (data.entryId == this.entryId && this.database?.id == data.dataId) { if (data.deleted) { // If deleted, go back. @@ -331,7 +336,7 @@ export class AddonModDataEntryPage implements OnInit, OnDestroy { return; } - const perPage = AddonModDataProvider.PER_PAGE; + const perPage = ADDON_MOD_DATA_ENTRIES_PER_PAGE; const page = this.offset !== undefined && this.offset >= 0 ? Math.floor(this.offset / perPage) : 0; diff --git a/src/addons/mod/data/services/data-helper.ts b/src/addons/mod/data/services/data-helper.ts index 5b75afca8..a3f788310 100644 --- a/src/addons/mod/data/services/data-helper.ts +++ b/src/addons/mod/data/services/data-helper.ts @@ -28,7 +28,6 @@ import { CoreEvents } from '@singletons/events'; import { AddonModDataEntry, AddonModData, - AddonModDataProvider, AddonModDataSearchEntriesOptions, AddonModDataEntries, AddonModDataEntryFields, @@ -44,6 +43,7 @@ import { import { AddonModDataFieldsDelegate } from './data-fields-delegate'; import { AddonModDataOffline, AddonModDataOfflineAction } from './data-offline'; import { CoreFileEntry } from '@services/file-helper'; +import { ADDON_MOD_DATA_COMPONENT, ADDON_MOD_DATA_ENTRY_CHANGED } from '../constants'; /** * Service that provides helper functions for datas. @@ -171,7 +171,7 @@ export class AddonModDataHelperProvider { await CoreUtils.ignoreErrors(Promise.all(promises)); - CoreEvents.trigger(AddonModDataProvider.ENTRY_CHANGED, { dataId: dataId, entryId: entryId }, siteId); + CoreEvents.trigger(ADDON_MOD_DATA_ENTRY_CHANGED, { dataId: dataId, entryId: entryId }, siteId); CoreDomUtils.showToast( approve ? 'addon.mod_data.recordapproved' : 'addon.mod_data.recorddisapproved', @@ -878,7 +878,7 @@ export class AddonModDataHelperProvider { // Ignore errors. } - CoreEvents.trigger(AddonModDataProvider.ENTRY_CHANGED, { dataId, entryId, deleted: true }, siteId); + CoreEvents.trigger(ADDON_MOD_DATA_ENTRY_CHANGED, { dataId, entryId, deleted: true }, siteId); CoreDomUtils.showToast('addon.mod_data.recorddeleted', true, ToastDuration.LONG); @@ -969,7 +969,7 @@ export class AddonModDataHelperProvider { return 0; } - return CoreFileUploader.uploadOrReuploadFiles(files, AddonModDataProvider.COMPONENT, itemId, siteId); + return CoreFileUploader.uploadOrReuploadFiles(files, ADDON_MOD_DATA_COMPONENT, itemId, siteId); } } diff --git a/src/addons/mod/data/services/data-sync.ts b/src/addons/mod/data/services/data-sync.ts index cd2e2ccea..fe5c4dbfc 100644 --- a/src/addons/mod/data/services/data-sync.ts +++ b/src/addons/mod/data/services/data-sync.ts @@ -29,9 +29,10 @@ import { CoreTextUtils } from '@services/utils/text'; import { CoreUtils } from '@services/utils/utils'; import { Translate, makeSingleton } from '@singletons'; import { CoreEvents } from '@singletons/events'; -import { AddonModDataProvider, AddonModData, AddonModDataData, AddonModDataAction } from './data'; +import { AddonModData, AddonModDataData, AddonModDataAction } from './data'; import { AddonModDataHelper } from './data-helper'; import { AddonModDataOffline, AddonModDataOfflineAction } from './data-offline'; +import { ADDON_MOD_DATA_AUTO_SYNCED, ADDON_MOD_DATA_COMPONENT } from '../constants'; /** * Service to sync databases. @@ -39,8 +40,6 @@ import { AddonModDataOffline, AddonModDataOfflineAction } from './data-offline'; @Injectable({ providedIn: 'root' }) export class AddonModDataSyncProvider extends CoreCourseActivitySyncBaseProvider { - static readonly AUTO_SYNCED = 'addon_mod_data_autom_synced'; - protected componentTranslatableString = 'data'; constructor() { @@ -93,7 +92,7 @@ export class AddonModDataSyncProvider extends CoreCourseActivitySyncBaseProvider if (result && result.updated) { // Sync done. Send event. - CoreEvents.trigger(AddonModDataSyncProvider.AUTO_SYNCED, { + CoreEvents.trigger(ADDON_MOD_DATA_AUTO_SYNCED, { dataId: dataId, warnings: result.warnings, }, siteId); @@ -142,7 +141,7 @@ export class AddonModDataSyncProvider extends CoreCourseActivitySyncBaseProvider } // Verify that database isn't blocked. - if (CoreSync.isBlocked(AddonModDataProvider.COMPONENT, dataId, siteId)) { + if (CoreSync.isBlocked(ADDON_MOD_DATA_COMPONENT, dataId, siteId)) { this.logger.debug(`Cannot sync database '${dataId}' because it is blocked.`); throw new CoreSyncBlockedError(Translate.instant('core.errorsyncblocked', { $a: this.componentTranslate })); @@ -165,7 +164,7 @@ export class AddonModDataSyncProvider extends CoreCourseActivitySyncBaseProvider protected async performSyncDatabase(dataId: number, siteId: string): Promise { // Sync offline logs. await CoreUtils.ignoreErrors( - CoreCourseLogHelper.syncActivity(AddonModDataProvider.COMPONENT, dataId, siteId), + CoreCourseLogHelper.syncActivity(ADDON_MOD_DATA_COMPONENT, dataId, siteId), ); const result: AddonModDataSyncResult = { @@ -243,7 +242,7 @@ export class AddonModDataSyncProvider extends CoreCourseActivitySyncBaseProvider } // Sync done. Send event. - CoreEvents.trigger(AddonModDataSyncProvider.AUTO_SYNCED, { + CoreEvents.trigger(ADDON_MOD_DATA_AUTO_SYNCED, { dataId: database.id, entryId: syncEntryResult.entryId, offlineEntryId: syncEntryResult.offlineId, diff --git a/src/addons/mod/data/services/data.ts b/src/addons/mod/data/services/data.ts index 41dc057fb..3a35dd376 100644 --- a/src/addons/mod/data/services/data.ts +++ b/src/addons/mod/data/services/data.ts @@ -28,10 +28,14 @@ import { CoreWSExternalFile, CoreWSExternalWarning } from '@services/ws'; import { makeSingleton, Translate } from '@singletons'; import { AddonModDataFieldsDelegate } from './data-fields-delegate'; import { AddonModDataOffline } from './data-offline'; -import { AddonModDataAutoSyncData, AddonModDataSyncProvider } from './data-sync'; +import { AddonModDataAutoSyncData } from './data-sync'; import { CoreSiteWSPreSets } from '@classes/sites/authenticated-site'; - -const ROOT_CACHE_KEY = 'mmaModData:'; +import { + ADDON_MOD_DATA_AUTO_SYNCED, + ADDON_MOD_DATA_COMPONENT, + ADDON_MOD_DATA_ENTRIES_PER_PAGE, + ADDON_MOD_DATA_ENTRY_CHANGED, +} from '../constants'; declare module '@singletons/events' { @@ -41,8 +45,8 @@ declare module '@singletons/events' { * @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation */ export interface CoreEventsData { - [AddonModDataSyncProvider.AUTO_SYNCED]: AddonModDataAutoSyncData; - [AddonModDataProvider.ENTRY_CHANGED]: AddonModDataEntryChangedEventData; + [ADDON_MOD_DATA_AUTO_SYNCED]: AddonModDataAutoSyncData; + [ADDON_MOD_DATA_ENTRY_CHANGED]: AddonModDataEntryChangedEventData; } } @@ -90,9 +94,7 @@ export enum AddonModDataTemplateMode { @Injectable({ providedIn: 'root' }) export class AddonModDataProvider { - static readonly COMPONENT = 'mmaModData'; - static readonly PER_PAGE = 25; - static readonly ENTRY_CHANGED = 'addon_mod_data_entry_changed'; + protected static readonly ROOT_CACHE_KEY = 'mmaModData:'; /** * Adds a new entry to a database. @@ -504,7 +506,7 @@ export class AddonModDataProvider { options.siteId = options.siteId || CoreSites.getCurrentSiteId(); options = Object.assign({ page: 0, - perPage: AddonModDataProvider.PER_PAGE, + perPage: ADDON_MOD_DATA_ENTRIES_PER_PAGE, }, options); return this.fetchEntriesRecursive(dataId, [], options); @@ -543,7 +545,7 @@ export class AddonModDataProvider { * @returns Cache key. */ protected getDatabaseDataCacheKey(courseId: number): string { - return ROOT_CACHE_KEY + 'data:' + courseId; + return AddonModDataProvider.ROOT_CACHE_KEY + 'data:' + courseId; } /** @@ -553,7 +555,7 @@ export class AddonModDataProvider { * @returns Cache key. */ protected getDatabaseDataPrefixCacheKey(dataId: number): string { - return ROOT_CACHE_KEY + dataId; + return AddonModDataProvider.ROOT_CACHE_KEY + dataId; } /** @@ -579,7 +581,7 @@ export class AddonModDataProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getDatabaseDataCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, - component: AddonModDataProvider.COMPONENT, + component: ADDON_MOD_DATA_COMPONENT, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const response = @@ -660,7 +662,7 @@ export class AddonModDataProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getDatabaseAccessInformationDataCacheKey(dataId, options.groupId), - component: AddonModDataProvider.COMPONENT, + component: ADDON_MOD_DATA_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -681,7 +683,7 @@ export class AddonModDataProvider { sort: 0, order: 'DESC', page: 0, - perPage: AddonModDataProvider.PER_PAGE, + perPage: ADDON_MOD_DATA_ENTRIES_PER_PAGE, }, options); const site = await CoreSites.getSite(options.siteId); @@ -699,7 +701,7 @@ export class AddonModDataProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getEntriesCacheKey(dataId, options.groupId), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, - component: AddonModDataProvider.COMPONENT, + component: ADDON_MOD_DATA_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -757,7 +759,7 @@ export class AddonModDataProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getEntryCacheKey(dataId, entryId), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, - component: AddonModDataProvider.COMPONENT, + component: ADDON_MOD_DATA_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -809,7 +811,7 @@ export class AddonModDataProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getFieldsCacheKey(dataId), updateFrequency: CoreSite.FREQUENCY_RARELY, - component: AddonModDataProvider.COMPONENT, + component: ADDON_MOD_DATA_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -911,7 +913,7 @@ export class AddonModDataProvider { * @returns Promise resolved when the files are invalidated. */ async invalidateFiles(moduleId: number, siteId?: string): Promise { - await CoreFilepool.invalidateFilesByComponent(siteId, AddonModDataProvider.COMPONENT, moduleId); + await CoreFilepool.invalidateFilesByComponent(siteId, ADDON_MOD_DATA_COMPONENT, moduleId); } /** @@ -969,7 +971,7 @@ export class AddonModDataProvider { await CoreCourseLogHelper.log( 'mod_data_view_database', params, - AddonModDataProvider.COMPONENT, + ADDON_MOD_DATA_COMPONENT, id, siteId, ); @@ -989,7 +991,7 @@ export class AddonModDataProvider { options.sort = options.sort || 0; options.order = options.order || 'DESC'; options.page = options.page || 0; - options.perPage = options.perPage || AddonModDataProvider.PER_PAGE; + options.perPage = options.perPage || ADDON_MOD_DATA_ENTRIES_PER_PAGE; options.readingStrategy = options.readingStrategy || CoreSitesReadingStrategy.PREFER_NETWORK; const params: AddonModDataSearchEntriesWSParams = { @@ -1000,7 +1002,7 @@ export class AddonModDataProvider { perpage: options.perPage, }; const preSets: CoreSiteWSPreSets = { - component: AddonModDataProvider.COMPONENT, + component: ADDON_MOD_DATA_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -1087,7 +1089,7 @@ export type AddonModDataGetEntriesOptions = CoreCourseCommonModWSOptions & { // -4: timemodified order?: string; // The direction of the sorting: 'ASC' or 'DESC'. Defaults to 'DESC'. page?: number; // Page of records to return. Defaults to 0. - perPage?: number; // Records per page to return. Defaults to AddonModDataProvider.PER_PAGE. + perPage?: number; // Records per page to return. Defaults to ADDON_MOD_DATA_ENTRIES_PER_PAGE. }; /** diff --git a/src/addons/mod/data/services/handlers/edit-link.ts b/src/addons/mod/data/services/handlers/edit-link.ts index f3fb943a8..ce57e83e1 100644 --- a/src/addons/mod/data/services/handlers/edit-link.ts +++ b/src/addons/mod/data/services/handlers/edit-link.ts @@ -21,8 +21,7 @@ import { CoreNavigator } from '@services/navigator'; import { CoreSitesReadingStrategy } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { makeSingleton } from '@singletons'; -import { AddonModDataModuleHandlerService } from './module'; -import { ADDON_MOD_DATA_FEATURE_NAME } from '../../constants'; +import { ADDON_MOD_DATA_FEATURE_NAME, ADDON_MOD_DATA_PAGE_NAME } from '../../constants'; /** * Content links handler for database add or edit entry. @@ -56,7 +55,7 @@ export class AddonModDataEditLinkHandlerService extends CoreContentLinksHandlerB }; await CoreNavigator.navigateToSitePath( - `${AddonModDataModuleHandlerService.PAGE_NAME}/${module.course}/${module.id}/edit/${rId}`, + `${ADDON_MOD_DATA_PAGE_NAME}/${module.course}/${module.id}/edit/${rId}`, { siteId, params: pageParams }, ); } finally { diff --git a/src/addons/mod/data/services/handlers/module.ts b/src/addons/mod/data/services/handlers/module.ts index 0abcdcc08..6a03b7781 100644 --- a/src/addons/mod/data/services/handlers/module.ts +++ b/src/addons/mod/data/services/handlers/module.ts @@ -17,6 +17,7 @@ import { Injectable, Type } from '@angular/core'; import { CoreModuleHandlerBase } from '@features/course/classes/module-base-handler'; import { CoreCourseModuleHandler } from '@features/course/services/module-delegate'; import { makeSingleton } from '@singletons'; +import { ADDON_MOD_DATA_PAGE_NAME } from '../../constants'; /** * Handler to support data modules. @@ -24,11 +25,9 @@ import { makeSingleton } from '@singletons'; @Injectable({ providedIn: 'root' }) export class AddonModDataModuleHandlerService extends CoreModuleHandlerBase implements CoreCourseModuleHandler { - static readonly PAGE_NAME = 'mod_data'; - name = 'AddonModData'; modName = 'data'; - protected pageName = AddonModDataModuleHandlerService.PAGE_NAME; + protected pageName = ADDON_MOD_DATA_PAGE_NAME; supportedFeatures = { [CoreConstants.FEATURE_GROUPS]: true, diff --git a/src/addons/mod/data/services/handlers/prefetch.ts b/src/addons/mod/data/services/handlers/prefetch.ts index d34fa7123..c863cc25a 100644 --- a/src/addons/mod/data/services/handlers/prefetch.ts +++ b/src/addons/mod/data/services/handlers/prefetch.ts @@ -24,9 +24,10 @@ import { CoreTimeUtils } from '@services/utils/time'; import { CoreUtils } from '@services/utils/utils'; import { CoreWSFile } from '@services/ws'; import { makeSingleton } from '@singletons'; -import { AddonModDataProvider, AddonModDataEntry, AddonModData, AddonModDataData } from '../data'; +import { AddonModDataEntry, AddonModData, AddonModDataData } from '../data'; import { AddonModDataSync, AddonModDataSyncResult } from '../data-sync'; import { ContextLevel } from '@/core/constants'; +import { ADDON_MOD_DATA_COMPONENT } from '../../constants'; /** * Handler to prefetch databases. @@ -36,7 +37,7 @@ export class AddonModDataPrefetchHandlerService extends CoreCourseActivityPrefet name = 'AddonModData'; modName = 'data'; - component = AddonModDataProvider.COMPONENT; + component = ADDON_MOD_DATA_COMPONENT; updatesNames = /^configuration$|^.*files$|^entries$|^gradeitems$|^outcomes$|^comments$|^ratings/; /** diff --git a/src/addons/mod/data/services/handlers/show-link.ts b/src/addons/mod/data/services/handlers/show-link.ts index bf0c735bb..52b47de9d 100644 --- a/src/addons/mod/data/services/handlers/show-link.ts +++ b/src/addons/mod/data/services/handlers/show-link.ts @@ -21,8 +21,7 @@ import { CoreNavigator } from '@services/navigator'; import { CoreSitesReadingStrategy } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { makeSingleton } from '@singletons'; -import { AddonModDataModuleHandlerService } from './module'; -import { ADDON_MOD_DATA_FEATURE_NAME } from '../../constants'; +import { ADDON_MOD_DATA_FEATURE_NAME, ADDON_MOD_DATA_PAGE_NAME } from '../../constants'; /** * Content links handler for database show entry. @@ -67,7 +66,7 @@ export class AddonModDataShowLinkHandlerService extends CoreContentLinksHandlerB } await CoreNavigator.navigateToSitePath( - `${AddonModDataModuleHandlerService.PAGE_NAME}/${module.course}/${module.id}/${rId}`, + `${ADDON_MOD_DATA_PAGE_NAME}/${module.course}/${module.id}/${rId}`, { siteId, params: pageParams }, ); } finally { From c836e94101f0c50d4073b26c8da5bcffccdd03e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Thu, 11 Jul 2024 22:40:51 +0200 Subject: [PATCH 08/26] MOBILE-4616 folder: Move folder constants to a file --- src/addons/mod/folder/components/index/index.ts | 8 ++++---- src/addons/mod/folder/constants.ts | 17 +++++++++++++++++ src/addons/mod/folder/folder-lazy.module.ts | 2 +- src/addons/mod/folder/folder.module.ts | 7 ++++--- src/addons/mod/folder/services/folder.ts | 11 +++++------ .../mod/folder/services/handlers/module.ts | 5 ++--- .../mod/folder/services/handlers/prefetch.ts | 5 +++-- 7 files changed, 36 insertions(+), 19 deletions(-) create mode 100644 src/addons/mod/folder/constants.ts diff --git a/src/addons/mod/folder/components/index/index.ts b/src/addons/mod/folder/components/index/index.ts index 3039947ce..a9baa74f8 100644 --- a/src/addons/mod/folder/components/index/index.ts +++ b/src/addons/mod/folder/components/index/index.ts @@ -19,10 +19,10 @@ import { CoreCourseContentsPage } from '@features/course/pages/contents/contents import { CoreCourse } from '@features/course/services/course'; import { CoreNavigator } from '@services/navigator'; import { Md5 } from 'ts-md5'; -import { AddonModFolder, AddonModFolderFolder, AddonModFolderProvider } from '../../services/folder'; +import { AddonModFolder, AddonModFolderFolder } from '../../services/folder'; import { AddonModFolderFolderFormattedData, AddonModFolderHelper } from '../../services/folder-helper'; -import { AddonModFolderModuleHandlerService } from '../../services/handlers/module'; import { CoreUtils } from '@services/utils/utils'; +import { ADDON_MOD_FOLDER_COMPONENT, ADDON_MOD_FOLDER_PAGE_NAME } from '../../constants'; /** * Component that displays a folder. @@ -39,7 +39,7 @@ export class AddonModFolderIndexComponent extends CoreCourseModuleMainResourceCo @Input() folderInstance?: AddonModFolderFolder; // The mod_folder instance. @Input() subfolder?: AddonModFolderFolderFormattedData; // Subfolder to show. - component = AddonModFolderProvider.COMPONENT; + component = ADDON_MOD_FOLDER_COMPONENT; pluginName = 'folder'; contents?: AddonModFolderFolderFormattedData; @@ -141,7 +141,7 @@ export class AddonModFolderIndexComponent extends CoreCourseModuleMainResourceCo const hash = Md5.hashAsciiStr(folder.filepath); CoreNavigator.navigateToSitePath( - `${AddonModFolderModuleHandlerService.PAGE_NAME}/${this.courseId}/${this.module.id}/${hash}`, + `${ADDON_MOD_FOLDER_PAGE_NAME}/${this.courseId}/${this.module.id}/${hash}`, { params }, ); } diff --git a/src/addons/mod/folder/constants.ts b/src/addons/mod/folder/constants.ts new file mode 100644 index 000000000..71275672b --- /dev/null +++ b/src/addons/mod/folder/constants.ts @@ -0,0 +1,17 @@ +// (C) Copyright 2015 Moodle Pty Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export const ADDON_MOD_FOLDER_COMPONENT = 'mmaModFolder'; + +export const ADDON_MOD_FOLDER_PAGE_NAME = 'mod_folder'; diff --git a/src/addons/mod/folder/folder-lazy.module.ts b/src/addons/mod/folder/folder-lazy.module.ts index ab66c8051..3000b0726 100644 --- a/src/addons/mod/folder/folder-lazy.module.ts +++ b/src/addons/mod/folder/folder-lazy.module.ts @@ -42,4 +42,4 @@ const routes: Routes = [ AddonModFolderIndexPage, ], }) -export class AddonModFolderLazyModule {} +export default class AddonModFolderLazyModule {} diff --git a/src/addons/mod/folder/folder.module.ts b/src/addons/mod/folder/folder.module.ts index f27d0ddac..c5531762d 100644 --- a/src/addons/mod/folder/folder.module.ts +++ b/src/addons/mod/folder/folder.module.ts @@ -21,14 +21,15 @@ import { CoreMainMenuTabRoutingModule } from '@features/mainmenu/mainmenu-tab-ro import { CorePluginFileDelegate } from '@services/plugin-file-delegate'; import { AddonModFolderIndexLinkHandler } from './services/handlers/index-link'; import { AddonModFolderListLinkHandler } from './services/handlers/list-link'; -import { AddonModFolderModuleHandler, AddonModFolderModuleHandlerService } from './services/handlers/module'; +import { AddonModFolderModuleHandler } from './services/handlers/module'; import { AddonModFolderPluginFileHandler } from './services/handlers/pluginfile'; import { AddonModFolderPrefetchHandler } from './services/handlers/prefetch'; +import { ADDON_MOD_FOLDER_PAGE_NAME } from './constants'; const routes: Routes = [ { - path: AddonModFolderModuleHandlerService.PAGE_NAME, - loadChildren: () => import('./folder-lazy.module').then(m => m.AddonModFolderLazyModule), + path: ADDON_MOD_FOLDER_PAGE_NAME, + loadChildren: () => import('./folder-lazy.module'), }, ]; diff --git a/src/addons/mod/folder/services/folder.ts b/src/addons/mod/folder/services/folder.ts index 459ca6b12..ca36e2985 100644 --- a/src/addons/mod/folder/services/folder.ts +++ b/src/addons/mod/folder/services/folder.ts @@ -22,8 +22,7 @@ import { CoreSites, CoreSitesCommonWSOptions } from '@services/sites'; import { CoreUtils } from '@services/utils/utils'; import { CoreWSExternalFile, CoreWSExternalWarning } from '@services/ws'; import { makeSingleton, Translate } from '@singletons'; - -const ROOT_CACHE_KEY = 'mmaModFolder:'; +import { ADDON_MOD_FOLDER_COMPONENT } from '../constants'; /** * Service that provides some features for folder. @@ -31,7 +30,7 @@ const ROOT_CACHE_KEY = 'mmaModFolder:'; @Injectable({ providedIn: 'root' }) export class AddonModFolderProvider { - static readonly COMPONENT = 'mmaModFolder'; + protected static readonly ROOT_CACHE_KEY = 'mmaModFolder:'; /** * Get a folder by course module ID. @@ -69,7 +68,7 @@ export class AddonModFolderProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getFolderCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, - component: AddonModFolderProvider.COMPONENT, + component: ADDON_MOD_FOLDER_COMPONENT, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), }; @@ -91,7 +90,7 @@ export class AddonModFolderProvider { * @returns Cache key. */ protected getFolderCacheKey(courseId: number): string { - return ROOT_CACHE_KEY + 'folder:' + courseId; + return AddonModFolderProvider.ROOT_CACHE_KEY + 'folder:' + courseId; } /** @@ -138,7 +137,7 @@ export class AddonModFolderProvider { await CoreCourseLogHelper.log( 'mod_folder_view_folder', params, - AddonModFolderProvider.COMPONENT, + ADDON_MOD_FOLDER_COMPONENT, id, siteId, ); diff --git a/src/addons/mod/folder/services/handlers/module.ts b/src/addons/mod/folder/services/handlers/module.ts index 848e624ba..aefa39df7 100644 --- a/src/addons/mod/folder/services/handlers/module.ts +++ b/src/addons/mod/folder/services/handlers/module.ts @@ -20,6 +20,7 @@ import { CoreCourseModuleHandler, CoreCourseModuleHandlerData } from '@features/ import { CoreNavigator } from '@services/navigator'; import { CoreDomUtils } from '@services/utils/dom'; import { makeSingleton } from '@singletons'; +import { ADDON_MOD_FOLDER_PAGE_NAME } from '../../constants'; /** * Handler to support folder modules. @@ -27,11 +28,9 @@ import { makeSingleton } from '@singletons'; @Injectable({ providedIn: 'root' }) export class AddonModFolderModuleHandlerService extends CoreModuleHandlerBase implements CoreCourseModuleHandler { - static readonly PAGE_NAME = 'mod_folder'; - name = 'AddonModFolder'; modName = 'folder'; - protected pageName = AddonModFolderModuleHandlerService.PAGE_NAME; + protected pageName = ADDON_MOD_FOLDER_PAGE_NAME; supportedFeatures = { [CoreConstants.FEATURE_MOD_ARCHETYPE]: CoreConstants.MOD_ARCHETYPE_RESOURCE, diff --git a/src/addons/mod/folder/services/handlers/prefetch.ts b/src/addons/mod/folder/services/handlers/prefetch.ts index 33535bfb3..52ed44754 100644 --- a/src/addons/mod/folder/services/handlers/prefetch.ts +++ b/src/addons/mod/folder/services/handlers/prefetch.ts @@ -17,7 +17,8 @@ import { CoreCourseResourcePrefetchHandlerBase } from '@features/course/classes/ import { CoreCourse, CoreCourseAnyModuleData } from '@features/course/services/course'; import { CoreCourseModuleData } from '@features/course/services/course-helper'; import { makeSingleton } from '@singletons'; -import { AddonModFolder, AddonModFolderProvider } from '../folder'; +import { AddonModFolder } from '../folder'; +import { ADDON_MOD_FOLDER_COMPONENT } from '../../constants'; /** * Handler to prefetch folders. @@ -27,7 +28,7 @@ export class AddonModFolderPrefetchHandlerService extends CoreCourseResourcePref name = 'AddonModFolder'; modName = 'folder'; - component = AddonModFolderProvider.COMPONENT; + component = ADDON_MOD_FOLDER_COMPONENT; /** * @inheritdoc From 94743ed70073eb0a549de327f19a70b8b599ace0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Thu, 11 Jul 2024 22:40:59 +0200 Subject: [PATCH 09/26] MOBILE-4616 glossary: Move glossary constants to a file --- .../classes/glossary-entries-source.ts | 4 +- .../mod/glossary/components/index/index.ts | 22 +++--- src/addons/mod/glossary/constants.ts | 23 ++++++ .../mod/glossary/glossary-edit-lazy.module.ts | 2 +- .../glossary/glossary-entry-lazy.module.ts | 2 +- .../mod/glossary/glossary-lazy.module.ts | 10 +-- src/addons/mod/glossary/glossary.module.ts | 38 +++++----- src/addons/mod/glossary/pages/edit/edit.ts | 6 +- src/addons/mod/glossary/pages/entry/entry.ts | 7 +- .../mod/glossary/services/glossary-offline.ts | 9 ++- .../mod/glossary/services/glossary-sync.ts | 9 ++- src/addons/mod/glossary/services/glossary.ts | 76 +++++++++---------- .../glossary/services/handlers/edit-link.ts | 4 +- .../glossary/services/handlers/entry-link.ts | 4 +- .../mod/glossary/services/handlers/module.ts | 5 +- .../glossary/services/handlers/prefetch.ts | 5 +- 16 files changed, 126 insertions(+), 100 deletions(-) create mode 100644 src/addons/mod/glossary/constants.ts diff --git a/src/addons/mod/glossary/classes/glossary-entries-source.ts b/src/addons/mod/glossary/classes/glossary-entries-source.ts index 08d525dc4..40cd562c7 100644 --- a/src/addons/mod/glossary/classes/glossary-entries-source.ts +++ b/src/addons/mod/glossary/classes/glossary-entries-source.ts @@ -20,9 +20,9 @@ import { AddonModGlossaryGetEntriesOptions, AddonModGlossaryGetEntriesWSResponse, AddonModGlossaryGlossary, - AddonModGlossaryProvider, } from '../services/glossary'; import { AddonModGlossaryOffline, AddonModGlossaryOfflineEntry } from '../services/glossary-offline'; +import { ADDON_MOD_GLOSSARY_LIMIT_ENTRIES } from '../constants'; /** * Provides a collection of glossary entries. @@ -259,7 +259,7 @@ export class AddonModGlossaryEntriesSource extends CoreRoutedItemsManagerSource< * @inheritdoc */ protected getPageLength(): number { - return AddonModGlossaryProvider.LIMIT_ENTRIES; + return ADDON_MOD_GLOSSARY_LIMIT_ENTRIES; } /** diff --git a/src/addons/mod/glossary/components/index/index.ts b/src/addons/mod/glossary/components/index/index.ts index a7dcd26ab..7209c2ba8 100644 --- a/src/addons/mod/glossary/components/index/index.ts +++ b/src/addons/mod/glossary/components/index/index.ts @@ -42,10 +42,6 @@ import { AddonModGlossaryEntry, AddonModGlossaryEntryWithCategory, AddonModGlossaryGlossary, - AddonModGlossaryProvider, - GLOSSARY_ENTRY_ADDED, - GLOSSARY_ENTRY_DELETED, - GLOSSARY_ENTRY_UPDATED, } from '../../services/glossary'; import { AddonModGlossaryOfflineEntry } from '../../services/glossary-offline'; import { @@ -53,10 +49,16 @@ import { AddonModGlossarySyncResult, GLOSSARY_AUTO_SYNCED, } from '../../services/glossary-sync'; -import { AddonModGlossaryModuleHandlerService } from '../../services/handlers/module'; import { AddonModGlossaryPrefetchHandler } from '../../services/handlers/prefetch'; import { AddonModGlossaryModePickerPopoverComponent } from '../mode-picker/mode-picker'; import { CoreTime } from '@singletons/time'; +import { + ADDON_MOD_GLOSSARY_COMPONENT, + ADDON_MOD_GLOSSARY_ENTRY_ADDED, + ADDON_MOD_GLOSSARY_ENTRY_DELETED, + ADDON_MOD_GLOSSARY_ENTRY_UPDATED, + ADDON_MOD_GLOSSARY_PAGE_NAME, +} from '../../constants'; /** * Component that displays a glossary entry page. @@ -71,7 +73,7 @@ export class AddonModGlossaryIndexComponent extends CoreCourseModuleMainActivity @ViewChild(CoreSplitViewComponent) splitView!: CoreSplitViewComponent; - component = AddonModGlossaryProvider.COMPONENT; + component = ADDON_MOD_GLOSSARY_COMPONENT; pluginName = 'glossary'; canAdd = false; @@ -128,7 +130,7 @@ export class AddonModGlossaryIndexComponent extends CoreCourseModuleMainActivity // Initialize entries manager. const source = CoreRoutedItemsManagerSourcesTracker.getOrCreateSource( AddonModGlossaryEntriesSource, - [this.courseId, this.module.id, this.courseContentsPage ? `${AddonModGlossaryModuleHandlerService.PAGE_NAME}/` : ''], + [this.courseId, this.module.id, this.courseContentsPage ? `${ADDON_MOD_GLOSSARY_PAGE_NAME}/` : ''], ); this.promisedEntries.resolve(new AddonModGlossaryEntriesManager(source, this)); @@ -142,7 +144,7 @@ export class AddonModGlossaryIndexComponent extends CoreCourseModuleMainActivity // When an entry is added, we reload the data. this.observers = [ - CoreEvents.on(GLOSSARY_ENTRY_ADDED, ({ glossaryId }) => { + CoreEvents.on(ADDON_MOD_GLOSSARY_ENTRY_ADDED, ({ glossaryId }) => { if (this.glossary?.id !== glossaryId) { return; } @@ -152,14 +154,14 @@ export class AddonModGlossaryIndexComponent extends CoreCourseModuleMainActivity this.showLoadingAndRefresh(false); }), - CoreEvents.on(GLOSSARY_ENTRY_UPDATED, ({ glossaryId }) => { + CoreEvents.on(ADDON_MOD_GLOSSARY_ENTRY_UPDATED, ({ glossaryId }) => { if (this.glossary?.id !== glossaryId) { return; } this.showLoadingAndRefresh(false); }), - CoreEvents.on(GLOSSARY_ENTRY_DELETED, ({ glossaryId }) => { + CoreEvents.on(ADDON_MOD_GLOSSARY_ENTRY_DELETED, ({ glossaryId }) => { if (this.glossary?.id !== glossaryId) { return; } diff --git a/src/addons/mod/glossary/constants.ts b/src/addons/mod/glossary/constants.ts new file mode 100644 index 000000000..e7eae3be2 --- /dev/null +++ b/src/addons/mod/glossary/constants.ts @@ -0,0 +1,23 @@ +// (C) Copyright 2015 Moodle Pty Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export const ADDON_MOD_GLOSSARY_COMPONENT = 'mmaModGlossary'; +export const ADDON_MOD_GLOSSARY_PAGE_NAME = 'mod_glossary'; + +export const ADDON_MOD_GLOSSARY_ENTRY_ADDED = 'addon_mod_glossary_entry_added'; +export const ADDON_MOD_GLOSSARY_ENTRY_UPDATED = 'addon_mod_glossary_entry_updated'; +export const ADDON_MOD_GLOSSARY_ENTRY_DELETED = 'addon_mod_glossary_entry_deleted'; + +export const ADDON_MOD_GLOSSARY_LIMIT_ENTRIES = 25; +export const ADDON_MOD_GLOSSARY_LIMIT_CATEGORIES = 10; diff --git a/src/addons/mod/glossary/glossary-edit-lazy.module.ts b/src/addons/mod/glossary/glossary-edit-lazy.module.ts index 0107cdaff..acc79104c 100644 --- a/src/addons/mod/glossary/glossary-edit-lazy.module.ts +++ b/src/addons/mod/glossary/glossary-edit-lazy.module.ts @@ -35,4 +35,4 @@ const routes: Routes = [{ CoreEditorComponentsModule, ], }) -export class AddonModGlossaryEditLazyModule {} +export default class AddonModGlossaryEditLazyModule {} diff --git a/src/addons/mod/glossary/glossary-entry-lazy.module.ts b/src/addons/mod/glossary/glossary-entry-lazy.module.ts index 781b896f5..3e012147e 100644 --- a/src/addons/mod/glossary/glossary-entry-lazy.module.ts +++ b/src/addons/mod/glossary/glossary-entry-lazy.module.ts @@ -37,4 +37,4 @@ const routes: Routes = [{ CoreTagComponentsModule, ], }) -export class AddonModGlossaryEntryLazyModule {} +export default class AddonModGlossaryEntryLazyModule {} diff --git a/src/addons/mod/glossary/glossary-lazy.module.ts b/src/addons/mod/glossary/glossary-lazy.module.ts index 7d74f30f7..a9b93b048 100644 --- a/src/addons/mod/glossary/glossary-lazy.module.ts +++ b/src/addons/mod/glossary/glossary-lazy.module.ts @@ -28,7 +28,7 @@ const mobileRoutes: Routes = [ }, { path: ':courseId/:cmId/entry/:entrySlug', - loadChildren: () => import('./glossary-entry-lazy.module').then(m => m.AddonModGlossaryEntryLazyModule), + loadChildren: () => import('./glossary-entry-lazy.module'), }, ]; @@ -39,7 +39,7 @@ const tabletRoutes: Routes = [ children: [ { path: 'entry/:entrySlug', - loadChildren: () => import('./glossary-entry-lazy.module').then(m => m.AddonModGlossaryEntryLazyModule), + loadChildren: () => import('./glossary-entry-lazy.module'), }, ], }, @@ -48,11 +48,11 @@ const tabletRoutes: Routes = [ const routes: Routes = [ { path: ':courseId/:cmId/entry/new', - loadChildren: () => import('./glossary-edit-lazy.module').then(m => m.AddonModGlossaryEditLazyModule), + loadChildren: () => import('./glossary-edit-lazy.module'), }, { path: ':courseId/:cmId/entry/:entrySlug/edit', - loadChildren: () => import('./glossary-edit-lazy.module').then(m => m.AddonModGlossaryEditLazyModule), + loadChildren: () => import('./glossary-edit-lazy.module'), }, ...conditionalRoutes(mobileRoutes, () => CoreScreen.isMobile), ...conditionalRoutes(tabletRoutes, () => CoreScreen.isTablet), @@ -68,4 +68,4 @@ const routes: Routes = [ AddonModGlossaryIndexPage, ], }) -export class AddonModGlossaryLazyModule {} +export default class AddonModGlossaryLazyModule {} diff --git a/src/addons/mod/glossary/glossary.module.ts b/src/addons/mod/glossary/glossary.module.ts index f7fe4c4f4..624e71874 100644 --- a/src/addons/mod/glossary/glossary.module.ts +++ b/src/addons/mod/glossary/glossary.module.ts @@ -27,45 +27,45 @@ import { CoreCronDelegate } from '@services/cron'; import { CoreScreen } from '@services/screen'; import { CORE_SITE_SCHEMAS } from '@services/sites'; import { SITE_SCHEMA, OFFLINE_SITE_SCHEMA } from './services/database/glossary'; -import { AddonModGlossaryProvider } from './services/glossary'; import { AddonModGlossaryEditLinkHandler } from './services/handlers/edit-link'; import { AddonModGlossaryEntryLinkHandler } from './services/handlers/entry-link'; import { AddonModGlossaryIndexLinkHandler } from './services/handlers/index-link'; import { AddonModGlossaryListLinkHandler } from './services/handlers/list-link'; -import { AddonModGlossaryModuleHandler, AddonModGlossaryModuleHandlerService } from './services/handlers/module'; +import { AddonModGlossaryModuleHandler } from './services/handlers/module'; import { AddonModGlossaryPrefetchHandler } from './services/handlers/prefetch'; import { AddonModGlossarySyncCronHandler } from './services/handlers/sync-cron'; import { AddonModGlossaryTagAreaHandler } from './services/handlers/tag-area'; +import { ADDON_MOD_GLOSSARY_COMPONENT, ADDON_MOD_GLOSSARY_PAGE_NAME } from './constants'; const mainMenuRoutes: Routes = [ // Link handlers navigation. { - path: `${AddonModGlossaryModuleHandlerService.PAGE_NAME}/entry/:entrySlug`, - loadChildren: () => import('./glossary-entry-lazy.module').then(m => m.AddonModGlossaryEntryLazyModule), + path: `${ADDON_MOD_GLOSSARY_PAGE_NAME}/entry/:entrySlug`, + loadChildren: () => import('./glossary-entry-lazy.module'), }, // Course activity navigation. { - path: AddonModGlossaryModuleHandlerService.PAGE_NAME, - loadChildren: () => import('./glossary-lazy.module').then(m => m.AddonModGlossaryLazyModule), + path: ADDON_MOD_GLOSSARY_PAGE_NAME, + loadChildren: () => import('./glossary-lazy.module'), }, // Single Activity format navigation. { - path: `${COURSE_CONTENTS_PATH}/${AddonModGlossaryModuleHandlerService.PAGE_NAME}/entry/new`, - loadChildren: () => import('./glossary-edit-lazy.module').then(m => m.AddonModGlossaryEditLazyModule), - data: { glossaryPathPrefix: `${AddonModGlossaryModuleHandlerService.PAGE_NAME}/` }, + path: `${COURSE_CONTENTS_PATH}/${ADDON_MOD_GLOSSARY_PAGE_NAME}/entry/new`, + loadChildren: () => import('./glossary-edit-lazy.module'), + data: { glossaryPathPrefix: `${ADDON_MOD_GLOSSARY_PAGE_NAME}/` }, }, { - path: `${COURSE_CONTENTS_PATH}/${AddonModGlossaryModuleHandlerService.PAGE_NAME}/entry/:entrySlug/edit`, - loadChildren: () => import('./glossary-edit-lazy.module').then(m => m.AddonModGlossaryEditLazyModule), - data: { glossaryPathPrefix: `${AddonModGlossaryModuleHandlerService.PAGE_NAME}/` }, + path: `${COURSE_CONTENTS_PATH}/${ADDON_MOD_GLOSSARY_PAGE_NAME}/entry/:entrySlug/edit`, + loadChildren: () => import('./glossary-edit-lazy.module'), + data: { glossaryPathPrefix: `${ADDON_MOD_GLOSSARY_PAGE_NAME}/` }, }, ...conditionalRoutes( [{ - path: `${COURSE_CONTENTS_PATH}/${AddonModGlossaryModuleHandlerService.PAGE_NAME}/entry/:entrySlug`, - loadChildren: () => import('./glossary-entry-lazy.module').then(m => m.AddonModGlossaryEntryLazyModule), - data: { glossaryPathPrefix: `${AddonModGlossaryModuleHandlerService.PAGE_NAME}/` }, + path: `${COURSE_CONTENTS_PATH}/${ADDON_MOD_GLOSSARY_PAGE_NAME}/entry/:entrySlug`, + loadChildren: () => import('./glossary-entry-lazy.module'), + data: { glossaryPathPrefix: `${ADDON_MOD_GLOSSARY_PAGE_NAME}/` }, }], () => CoreScreen.isMobile, ), @@ -74,9 +74,9 @@ const mainMenuRoutes: Routes = [ // Single Activity format navigation. const courseContentsRoutes: Routes = conditionalRoutes( [{ - path: `${AddonModGlossaryModuleHandlerService.PAGE_NAME}/entry/:entrySlug`, - loadChildren: () => import('./glossary-entry-lazy.module').then(m => m.AddonModGlossaryEntryLazyModule), - data: { glossaryPathPrefix: `${AddonModGlossaryModuleHandlerService.PAGE_NAME}/` }, + path: `${ADDON_MOD_GLOSSARY_PAGE_NAME}/entry/:entrySlug`, + loadChildren: () => import('./glossary-entry-lazy.module'), + data: { glossaryPathPrefix: `${ADDON_MOD_GLOSSARY_PAGE_NAME}/` }, }], () => CoreScreen.isTablet, ); @@ -105,7 +105,7 @@ const courseContentsRoutes: Routes = conditionalRoutes( CoreContentLinksDelegate.registerHandler(AddonModGlossaryEntryLinkHandler.instance); CoreTagAreaDelegate.registerHandler(AddonModGlossaryTagAreaHandler.instance); - CoreCourseHelper.registerModuleReminderClick(AddonModGlossaryProvider.COMPONENT); + CoreCourseHelper.registerModuleReminderClick(ADDON_MOD_GLOSSARY_COMPONENT); }, }, ], diff --git a/src/addons/mod/glossary/pages/edit/edit.ts b/src/addons/mod/glossary/pages/edit/edit.ts index 5705cf257..0edecc377 100644 --- a/src/addons/mod/glossary/pages/edit/edit.ts +++ b/src/addons/mod/glossary/pages/edit/edit.ts @@ -36,11 +36,11 @@ import { AddonModGlossaryEntry, AddonModGlossaryEntryOption, AddonModGlossaryGlossary, - AddonModGlossaryProvider, } from '../../services/glossary'; import { AddonModGlossaryHelper } from '../../services/glossary-helper'; import { AddonModGlossaryOffline } from '../../services/glossary-offline'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; +import { ADDON_MOD_GLOSSARY_COMPONENT } from '../../constants'; /** * Page that displays the edit form. @@ -53,7 +53,7 @@ export class AddonModGlossaryEditPage implements OnInit, CanLeave { @ViewChild('editFormEl') formElement?: ElementRef; - component = AddonModGlossaryProvider.COMPONENT; + component = ADDON_MOD_GLOSSARY_COMPONENT; cmId!: number; courseId!: number; loaded = false; @@ -305,7 +305,7 @@ abstract class AddonModGlossaryFormHandler { const data = this.page.data; const itemId = await CoreFileUploader.uploadOrReuploadFiles( data.attachments, - AddonModGlossaryProvider.COMPONENT, + ADDON_MOD_GLOSSARY_COMPONENT, glossary.id, ); diff --git a/src/addons/mod/glossary/pages/entry/entry.ts b/src/addons/mod/glossary/pages/entry/entry.ts index 4daad9772..e0da0fc1c 100644 --- a/src/addons/mod/glossary/pages/entry/entry.ts +++ b/src/addons/mod/glossary/pages/entry/entry.ts @@ -35,11 +35,10 @@ import { AddonModGlossary, AddonModGlossaryEntry, AddonModGlossaryGlossary, - AddonModGlossaryProvider, - GLOSSARY_ENTRY_UPDATED, } from '../../services/glossary'; import { CoreTime } from '@singletons/time'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; +import { ADDON_MOD_GLOSSARY_COMPONENT, ADDON_MOD_GLOSSARY_ENTRY_UPDATED } from '../../constants'; /** * Page that displays a glossary entry. @@ -52,7 +51,7 @@ export class AddonModGlossaryEntryPage implements OnInit, OnDestroy { @ViewChild(CoreCommentsCommentsComponent) comments?: CoreCommentsCommentsComponent; - component = AddonModGlossaryProvider.COMPONENT; + component = ADDON_MOD_GLOSSARY_COMPONENT; componentId?: number; onlineEntry?: AddonModGlossaryEntry; offlineEntry?: AddonModGlossaryOfflineEntry; @@ -125,7 +124,7 @@ export class AddonModGlossaryEntryPage implements OnInit, OnDestroy { return; } - this.entryUpdatedObserver = CoreEvents.on(GLOSSARY_ENTRY_UPDATED, data => { + this.entryUpdatedObserver = CoreEvents.on(ADDON_MOD_GLOSSARY_ENTRY_UPDATED, data => { if (data.glossaryId !== this.glossary?.id) { return; } diff --git a/src/addons/mod/glossary/services/glossary-offline.ts b/src/addons/mod/glossary/services/glossary-offline.ts index cc4b89c86..a4807e6f9 100644 --- a/src/addons/mod/glossary/services/glossary-offline.ts +++ b/src/addons/mod/glossary/services/glossary-offline.ts @@ -21,7 +21,8 @@ import { makeSingleton } from '@singletons'; import { CoreEvents } from '@singletons/events'; import { CorePath } from '@singletons/path'; import { AddonModGlossaryOfflineEntryDBRecord, OFFLINE_ENTRIES_TABLE_NAME } from './database/glossary'; -import { AddonModGlossaryEntryOption, GLOSSARY_ENTRY_ADDED, GLOSSARY_ENTRY_DELETED, GLOSSARY_ENTRY_UPDATED } from './glossary'; +import { AddonModGlossaryEntryOption } from './glossary'; +import { ADDON_MOD_GLOSSARY_ENTRY_DELETED, ADDON_MOD_GLOSSARY_ENTRY_ADDED, ADDON_MOD_GLOSSARY_ENTRY_UPDATED } from '../constants'; /** * Service to handle offline glossary. @@ -47,7 +48,7 @@ export class AddonModGlossaryOfflineProvider { await site.getDb().deleteRecords(OFFLINE_ENTRIES_TABLE_NAME, conditions); - CoreEvents.trigger(GLOSSARY_ENTRY_DELETED, { glossaryId, timecreated }); + CoreEvents.trigger(ADDON_MOD_GLOSSARY_ENTRY_DELETED, { glossaryId, timecreated }); } /** @@ -188,7 +189,7 @@ export class AddonModGlossaryOfflineProvider { await site.getDb().insertRecord(OFFLINE_ENTRIES_TABLE_NAME, entry); - CoreEvents.trigger(GLOSSARY_ENTRY_ADDED, { glossaryId, timecreated }, siteId); + CoreEvents.trigger(ADDON_MOD_GLOSSARY_ENTRY_ADDED, { glossaryId, timecreated }, siteId); return false; } @@ -223,7 +224,7 @@ export class AddonModGlossaryOfflineProvider { userid: site.getUserId(), }); - CoreEvents.trigger(GLOSSARY_ENTRY_UPDATED, { + CoreEvents.trigger(ADDON_MOD_GLOSSARY_ENTRY_UPDATED, { glossaryId: originalEntry.glossaryid, timecreated: originalEntry.timecreated, }); diff --git a/src/addons/mod/glossary/services/glossary-sync.ts b/src/addons/mod/glossary/services/glossary-sync.ts index b922d7262..61a6b1f9f 100644 --- a/src/addons/mod/glossary/services/glossary-sync.ts +++ b/src/addons/mod/glossary/services/glossary-sync.ts @@ -25,11 +25,12 @@ import { CoreSync, CoreSyncResult } from '@services/sync'; import { CoreUtils } from '@services/utils/utils'; import { makeSingleton, Translate } from '@singletons'; import { CoreEvents } from '@singletons/events'; -import { AddonModGlossary, AddonModGlossaryProvider } from './glossary'; +import { AddonModGlossary } from './glossary'; import { AddonModGlossaryHelper } from './glossary-helper'; import { AddonModGlossaryOffline, AddonModGlossaryOfflineEntry } from './glossary-offline'; import { CoreFileUploader } from '@features/fileuploader/services/fileuploader'; import { CoreFileEntry } from '@services/file-helper'; +import { ADDON_MOD_GLOSSARY_COMPONENT } from '../constants'; export const GLOSSARY_AUTO_SYNCED = 'addon_mod_glossary_auto_synced'; @@ -148,7 +149,7 @@ export class AddonModGlossarySyncProvider extends CoreCourseActivitySyncBaseProv } // Verify that glossary isn't blocked. - if (CoreSync.isBlocked(AddonModGlossaryProvider.COMPONENT, syncId, siteId)) { + if (CoreSync.isBlocked(ADDON_MOD_GLOSSARY_COMPONENT, syncId, siteId)) { this.logger.debug('Cannot sync glossary ' + glossaryId + ' because it is blocked.'); throw new CoreSyncBlockedError(Translate.instant('core.errorsyncblocked', { $a: this.componentTranslate })); @@ -173,7 +174,7 @@ export class AddonModGlossarySyncProvider extends CoreCourseActivitySyncBaseProv const syncId = this.getGlossarySyncId(glossaryId, userId); // Sync offline logs. - await CoreUtils.ignoreErrors(CoreCourseLogHelper.syncActivity(AddonModGlossaryProvider.COMPONENT, glossaryId, siteId)); + await CoreUtils.ignoreErrors(CoreCourseLogHelper.syncActivity(ADDON_MOD_GLOSSARY_COMPONENT, glossaryId, siteId)); // Get offline responses to be sent. const entries = await CoreUtils.ignoreErrors( @@ -317,7 +318,7 @@ export class AddonModGlossarySyncProvider extends CoreCourseActivitySyncBaseProv files = files.concat(storedFiles); } - return CoreFileUploader.uploadOrReuploadFiles(files, AddonModGlossaryProvider.COMPONENT, glossaryId, siteId); + return CoreFileUploader.uploadOrReuploadFiles(files, ADDON_MOD_GLOSSARY_COMPONENT, glossaryId, siteId); } /** diff --git a/src/addons/mod/glossary/services/glossary.ts b/src/addons/mod/glossary/services/glossary.ts index f6257a11e..a9c12cf1a 100644 --- a/src/addons/mod/glossary/services/glossary.ts +++ b/src/addons/mod/glossary/services/glossary.ts @@ -29,10 +29,14 @@ import { CoreEvents } from '@singletons/events'; import { AddonModGlossaryEntryDBRecord, ENTRIES_TABLE_NAME } from './database/glossary'; import { AddonModGlossaryOffline } from './glossary-offline'; import { CoreSiteWSPreSets } from '@classes/sites/authenticated-site'; - -export const GLOSSARY_ENTRY_ADDED = 'addon_mod_glossary_entry_added'; -export const GLOSSARY_ENTRY_UPDATED = 'addon_mod_glossary_entry_updated'; -export const GLOSSARY_ENTRY_DELETED = 'addon_mod_glossary_entry_deleted'; +import { + ADDON_MOD_GLOSSARY_COMPONENT, + ADDON_MOD_GLOSSARY_ENTRY_ADDED, + ADDON_MOD_GLOSSARY_ENTRY_DELETED, + ADDON_MOD_GLOSSARY_ENTRY_UPDATED, + ADDON_MOD_GLOSSARY_LIMIT_CATEGORIES, + ADDON_MOD_GLOSSARY_LIMIT_ENTRIES, +} from '../constants'; /** * Service that provides some features for glossaries. @@ -40,12 +44,8 @@ export const GLOSSARY_ENTRY_DELETED = 'addon_mod_glossary_entry_deleted'; @Injectable({ providedIn: 'root' }) export class AddonModGlossaryProvider { - static readonly COMPONENT = 'mmaModGlossary'; - static readonly LIMIT_ENTRIES = 25; - static readonly LIMIT_CATEGORIES = 10; - - private static readonly SHOW_ALL_CATEGORIES = 0; - private static readonly ROOT_CACHE_KEY = 'mmaModGlossary:'; + protected static readonly SHOW_ALL_CATEGORIES = 0; + protected static readonly ROOT_CACHE_KEY = 'mmaModGlossary:'; /** * Get the course glossary cache key. @@ -73,7 +73,7 @@ export class AddonModGlossaryProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getCourseGlossariesCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, - component: AddonModGlossaryProvider.COMPONENT, + component: ADDON_MOD_GLOSSARY_COMPONENT, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -129,12 +129,12 @@ export class AddonModGlossaryProvider { field: 'LASTNAME', sort: 'ASC', from: options.from || 0, - limit: options.limit || AddonModGlossaryProvider.LIMIT_ENTRIES, + limit: options.limit || ADDON_MOD_GLOSSARY_LIMIT_ENTRIES, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getEntriesByAuthorCacheKey(glossaryId), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, - component: AddonModGlossaryProvider.COMPONENT, + component: ADDON_MOD_GLOSSARY_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -173,12 +173,12 @@ export class AddonModGlossaryProvider { id: glossaryId, categoryid: AddonModGlossaryProvider.SHOW_ALL_CATEGORIES, from: options.from || 0, - limit: options.limit || AddonModGlossaryProvider.LIMIT_ENTRIES, + limit: options.limit || ADDON_MOD_GLOSSARY_LIMIT_ENTRIES, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getEntriesByCategoryCacheKey(glossaryId), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, - component: AddonModGlossaryProvider.COMPONENT, + component: ADDON_MOD_GLOSSARY_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -243,12 +243,12 @@ export class AddonModGlossaryProvider { order: order, sort: 'DESC', from: options.from || 0, - limit: options.limit || AddonModGlossaryProvider.LIMIT_ENTRIES, + limit: options.limit || ADDON_MOD_GLOSSARY_LIMIT_ENTRIES, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getEntriesByDateCacheKey(glossaryId, order), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, - component: AddonModGlossaryProvider.COMPONENT, + component: ADDON_MOD_GLOSSARY_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -293,7 +293,7 @@ export class AddonModGlossaryProvider { options: AddonModGlossaryGetEntriesOptions = {}, ): Promise { const from = options.from || 0; - const limit = options.limit || AddonModGlossaryProvider.LIMIT_ENTRIES; + const limit = options.limit || ADDON_MOD_GLOSSARY_LIMIT_ENTRIES; const site = await CoreSites.getSite(options.siteId); @@ -306,7 +306,7 @@ export class AddonModGlossaryProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getEntriesByLetterCacheKey(glossaryId), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, - component: AddonModGlossaryProvider.COMPONENT, + component: ADDON_MOD_GLOSSARY_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -317,7 +317,7 @@ export class AddonModGlossaryProvider { preSets, ); - if (limit === AddonModGlossaryProvider.LIMIT_ENTRIES) { + if (limit === ADDON_MOD_GLOSSARY_LIMIT_ENTRIES) { // Store entries in background, don't block the user for this. CoreUtils.ignoreErrors(this.storeEntries(glossaryId, result.entries, from, site.getId())); } @@ -375,12 +375,12 @@ export class AddonModGlossaryProvider { order: 'CONCEPT', sort: 'ASC', from: options.from || 0, - limit: options.limit || AddonModGlossaryProvider.LIMIT_ENTRIES, + limit: options.limit || ADDON_MOD_GLOSSARY_LIMIT_ENTRIES, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getEntriesBySearchCacheKey(glossaryId, query, fullSearch), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, - component: AddonModGlossaryProvider.COMPONENT, + component: ADDON_MOD_GLOSSARY_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -448,7 +448,7 @@ export class AddonModGlossaryProvider { options: AddonModGlossaryGetCategoriesOptions = {}, ): Promise { const from = options.from || 0; - const limit = options.limit || AddonModGlossaryProvider.LIMIT_CATEGORIES; + const limit = options.limit || ADDON_MOD_GLOSSARY_LIMIT_CATEGORIES; const params: AddonModGlossaryGetCategoriesWSParams = { id: glossaryId, @@ -458,7 +458,7 @@ export class AddonModGlossaryProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getCategoriesCacheKey(glossaryId), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, - component: AddonModGlossaryProvider.COMPONENT, + component: ADDON_MOD_GLOSSARY_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -515,7 +515,7 @@ export class AddonModGlossaryProvider { const preSets = { cacheKey: this.getEntryCacheKey(entryId), updateFrequency: CoreSite.FREQUENCY_RARELY, - component: AddonModGlossaryProvider.COMPONENT, + component: ADDON_MOD_GLOSSARY_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -919,7 +919,7 @@ export class AddonModGlossaryProvider { const response = await site.write('mod_glossary_add_entry', params); - CoreEvents.trigger(GLOSSARY_ENTRY_ADDED, { glossaryId, entryId: response.entryid }, siteId); + CoreEvents.trigger(ADDON_MOD_GLOSSARY_ENTRY_ADDED, { glossaryId, entryId: response.entryid }, siteId); return response.entryid; } @@ -967,7 +967,7 @@ export class AddonModGlossaryProvider { throw new CoreError(response.warnings?.[0].message ?? 'Error updating entry'); } - CoreEvents.trigger(GLOSSARY_ENTRY_UPDATED, { glossaryId, entryId }, siteId); + CoreEvents.trigger(ADDON_MOD_GLOSSARY_ENTRY_UPDATED, { glossaryId, entryId }, siteId); } /** @@ -981,7 +981,7 @@ export class AddonModGlossaryProvider { await site.write('mod_glossary_delete_entry', { entryid: entryId }); - CoreEvents.trigger(GLOSSARY_ENTRY_DELETED, { glossaryId, entryId }); + CoreEvents.trigger(ADDON_MOD_GLOSSARY_ENTRY_DELETED, { glossaryId, entryId }); } /** @@ -1033,7 +1033,7 @@ export class AddonModGlossaryProvider { await CoreCourseLogHelper.log( 'mod_glossary_view_glossary', params, - AddonModGlossaryProvider.COMPONENT, + ADDON_MOD_GLOSSARY_COMPONENT, glossaryId, siteId, ); @@ -1054,7 +1054,7 @@ export class AddonModGlossaryProvider { await CoreCourseLogHelper.log( 'mod_glossary_view_entry', params, - AddonModGlossaryProvider.COMPONENT, + ADDON_MOD_GLOSSARY_COMPONENT, glossaryId, siteId, ); @@ -1109,15 +1109,15 @@ declare module '@singletons/events' { * @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation */ export interface CoreEventsData { - [GLOSSARY_ENTRY_ADDED]: AddonModGlossaryEntryAddedEventData; - [GLOSSARY_ENTRY_UPDATED]: AddonModGlossaryEntryUpdatedEventData; - [GLOSSARY_ENTRY_DELETED]: AddonModGlossaryEntryDeletedEventData; + [ADDON_MOD_GLOSSARY_ENTRY_ADDED]: AddonModGlossaryEntryAddedEventData; + [ADDON_MOD_GLOSSARY_ENTRY_UPDATED]: AddonModGlossaryEntryUpdatedEventData; + [ADDON_MOD_GLOSSARY_ENTRY_DELETED]: AddonModGlossaryEntryDeletedEventData; } } /** - * GLOSSARY_ENTRY_ADDED event payload. + * ADDON_MOD_GLOSSARY_ENTRY_ADDED event payload. */ export type AddonModGlossaryEntryAddedEventData = { glossaryId: number; @@ -1126,7 +1126,7 @@ export type AddonModGlossaryEntryAddedEventData = { }; /** - * GLOSSARY_ENTRY_UPDATED event payload. + * ADDON_MOD_GLOSSARY_ENTRY_UPDATED event payload. */ export type AddonModGlossaryEntryUpdatedEventData = { glossaryId: number; @@ -1135,7 +1135,7 @@ export type AddonModGlossaryEntryUpdatedEventData = { }; /** - * GLOSSARY_ENTRY_DELETED event payload. + * ADDON_MOD_GLOSSARY_ENTRY_DELETED event payload. */ export type AddonModGlossaryEntryDeletedEventData = { glossaryId: number; @@ -1451,7 +1451,7 @@ export type AddonModGlossaryAddEntryOptions = { */ export type AddonModGlossaryGetEntriesOptions = CoreCourseCommonModWSOptions & { from?: number; // Start returning records from here. Defaults to 0. - limit?: number; // Number of records to return. Defaults to AddonModGlossaryProvider.LIMIT_ENTRIES. + limit?: number; // Number of records to return. Defaults to ADDON_MOD_GLOSSARY_LIMIT_ENTRIES. }; /** @@ -1459,7 +1459,7 @@ export type AddonModGlossaryGetEntriesOptions = CoreCourseCommonModWSOptions & { */ export type AddonModGlossaryGetCategoriesOptions = CoreCourseCommonModWSOptions & { from?: number; // Start returning records from here. Defaults to 0. - limit?: number; // Number of records to return. Defaults to AddonModGlossaryProvider.LIMIT_CATEGORIES. + limit?: number; // Number of records to return. Defaults to ADDON_MOD_GLOSSARY_LIMIT_CATEGORIES. }; /** diff --git a/src/addons/mod/glossary/services/handlers/edit-link.ts b/src/addons/mod/glossary/services/handlers/edit-link.ts index 541a975ed..56a4c54f8 100644 --- a/src/addons/mod/glossary/services/handlers/edit-link.ts +++ b/src/addons/mod/glossary/services/handlers/edit-link.ts @@ -20,7 +20,7 @@ import { CoreNavigator } from '@services/navigator'; import { CoreSitesReadingStrategy } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { makeSingleton } from '@singletons'; -import { AddonModGlossaryModuleHandlerService } from './module'; +import { ADDON_MOD_GLOSSARY_PAGE_NAME } from '../../constants'; /** * Content links handler for glossary new entry. @@ -51,7 +51,7 @@ export class AddonModGlossaryEditLinkHandlerService extends CoreContentLinksHand ); await CoreNavigator.navigateToSitePath( - AddonModGlossaryModuleHandlerService.PAGE_NAME + `/${module.course}/${module.id}/entry/new`, + `${ADDON_MOD_GLOSSARY_PAGE_NAME}/${module.course}/${module.id}/entry/new`, { siteId }, ); } catch (error) { diff --git a/src/addons/mod/glossary/services/handlers/entry-link.ts b/src/addons/mod/glossary/services/handlers/entry-link.ts index 7907c4d8b..742056478 100644 --- a/src/addons/mod/glossary/services/handlers/entry-link.ts +++ b/src/addons/mod/glossary/services/handlers/entry-link.ts @@ -21,7 +21,7 @@ import { CoreSitesReadingStrategy } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { makeSingleton } from '@singletons'; import { AddonModGlossary } from '../glossary'; -import { AddonModGlossaryModuleHandlerService } from './module'; +import { ADDON_MOD_GLOSSARY_PAGE_NAME } from '../../constants'; /** * Handler to treat links to glossary entries. @@ -56,7 +56,7 @@ export class AddonModGlossaryEntryLinkHandlerService extends CoreContentLinksHan ); await CoreNavigator.navigateToSitePath( - `${AddonModGlossaryModuleHandlerService.PAGE_NAME}/entry/${entryId}`, + `${ADDON_MOD_GLOSSARY_PAGE_NAME}/entry/${entryId}`, { siteId, params: { diff --git a/src/addons/mod/glossary/services/handlers/module.ts b/src/addons/mod/glossary/services/handlers/module.ts index b4ad38a05..cf6d1a6df 100644 --- a/src/addons/mod/glossary/services/handlers/module.ts +++ b/src/addons/mod/glossary/services/handlers/module.ts @@ -17,6 +17,7 @@ import { Injectable, Type } from '@angular/core'; import { CoreModuleHandlerBase } from '@features/course/classes/module-base-handler'; import { CoreCourseModuleHandler } from '@features/course/services/module-delegate'; import { makeSingleton } from '@singletons'; +import { ADDON_MOD_GLOSSARY_PAGE_NAME } from '../../constants'; /** * Handler to support glossary modules. @@ -24,11 +25,9 @@ import { makeSingleton } from '@singletons'; @Injectable({ providedIn: 'root' }) export class AddonModGlossaryModuleHandlerService extends CoreModuleHandlerBase implements CoreCourseModuleHandler { - static readonly PAGE_NAME = 'mod_glossary'; - name = 'AddonModGlossary'; modName = 'glossary'; - protected pageName = AddonModGlossaryModuleHandlerService.PAGE_NAME; + protected pageName = ADDON_MOD_GLOSSARY_PAGE_NAME; supportedFeatures = { [CoreConstants.FEATURE_GROUPS]: false, diff --git a/src/addons/mod/glossary/services/handlers/prefetch.ts b/src/addons/mod/glossary/services/handlers/prefetch.ts index 713f56d83..7e5a6b8d3 100644 --- a/src/addons/mod/glossary/services/handlers/prefetch.ts +++ b/src/addons/mod/glossary/services/handlers/prefetch.ts @@ -23,9 +23,10 @@ import { CoreSitesReadingStrategy } from '@services/sites'; import { CoreUtils } from '@services/utils/utils'; import { CoreWSFile } from '@services/ws'; import { makeSingleton } from '@singletons'; -import { AddonModGlossary, AddonModGlossaryEntry, AddonModGlossaryGlossary, AddonModGlossaryProvider } from '../glossary'; +import { AddonModGlossary, AddonModGlossaryEntry, AddonModGlossaryGlossary } from '../glossary'; import { AddonModGlossarySync, AddonModGlossarySyncResult } from '../glossary-sync'; import { ContextLevel } from '@/core/constants'; +import { ADDON_MOD_GLOSSARY_COMPONENT } from '../../constants'; /** * Handler to prefetch forums. @@ -35,7 +36,7 @@ export class AddonModGlossaryPrefetchHandlerService extends CoreCourseActivityPr name = 'AddonModGlossary'; modName = 'glossary'; - component = AddonModGlossaryProvider.COMPONENT; + component = ADDON_MOD_GLOSSARY_COMPONENT; updatesNames = /^configuration$|^.*files$|^entries$/; /** From 67cae258f6643187ccc2d18238c9962ca6c89a8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Thu, 11 Jul 2024 22:41:20 +0200 Subject: [PATCH 10/26] MOBILE-4616 forum: Move forum constants to a file --- .../forum/classes/forum-discussions-source.ts | 4 +- .../discussion-options-menu.ts | 9 +- .../mod/forum/components/index/index.ts | 35 +++--- src/addons/mod/forum/components/post/post.ts | 8 +- src/addons/mod/forum/constants.ts | 26 +++++ .../mod/forum/forum-discussion-lazy.module.ts | 2 +- src/addons/mod/forum/forum-lazy.module.ts | 12 +- .../forum/forum-new-discussion-lazy.module.ts | 2 +- .../mod/forum/forum-search-lazy.module.ts | 2 +- src/addons/mod/forum/forum.module.ts | 41 ++++--- .../mod/forum/pages/discussion/discussion.ts | 31 ++++-- .../pages/new-discussion/new-discussion.ts | 26 +++-- src/addons/mod/forum/services/forum-helper.ts | 8 +- .../mod/forum/services/forum-offline.ts | 4 +- src/addons/mod/forum/services/forum-sync.ts | 28 ++--- src/addons/mod/forum/services/forum.ts | 105 ++++++++---------- .../services/handlers/discussion-link.ts | 4 +- .../mod/forum/services/handlers/module.ts | 9 +- .../mod/forum/services/handlers/post-link.ts | 4 +- .../mod/forum/services/handlers/prefetch.ts | 5 +- .../mod/forum/services/handlers/push-click.ts | 4 +- 21 files changed, 205 insertions(+), 164 deletions(-) diff --git a/src/addons/mod/forum/classes/forum-discussions-source.ts b/src/addons/mod/forum/classes/forum-discussions-source.ts index 06a51ffdd..5b095d07f 100644 --- a/src/addons/mod/forum/classes/forum-discussions-source.ts +++ b/src/addons/mod/forum/classes/forum-discussions-source.ts @@ -22,10 +22,10 @@ import { AddonModForumCanAddDiscussion, AddonModForumData, AddonModForumDiscussion, - AddonModForumProvider, AddonModForumSortOrder, } from '../services/forum'; import { AddonModForumOffline, AddonModForumOfflineDiscussion } from '../services/forum-offline'; +import { ADDON_MOD_FORUM_DISCUSSIONS_PER_PAGE } from '../constants'; export class AddonModForumDiscussionsSource extends CoreRoutedItemsManagerSource { @@ -136,7 +136,7 @@ export class AddonModForumDiscussionsSource extends CoreRoutedItemsManagerSource * @inheritdoc */ getPageLength(): number { - return AddonModForumProvider.DISCUSSIONS_PER_PAGE; + return ADDON_MOD_FORUM_DISCUSSIONS_PER_PAGE; } /** diff --git a/src/addons/mod/forum/components/discussion-options-menu/discussion-options-menu.ts b/src/addons/mod/forum/components/discussion-options-menu/discussion-options-menu.ts index 43c28b716..77dfa2971 100644 --- a/src/addons/mod/forum/components/discussion-options-menu/discussion-options-menu.ts +++ b/src/addons/mod/forum/components/discussion-options-menu/discussion-options-menu.ts @@ -17,7 +17,8 @@ import { CoreSites } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { PopoverController } from '@singletons'; import { CoreEvents } from '@singletons/events'; -import { AddonModForum, AddonModForumDiscussion, AddonModForumProvider } from '../../services/forum'; +import { AddonModForum, AddonModForumDiscussion } from '../../services/forum'; +import { ADDON_MOD_FORUM_CHANGE_DISCUSSION_EVENT } from '../../constants'; /** * This component is meant to display a popover with the discussion options. @@ -71,7 +72,7 @@ export class AddonModForumDiscussionOptionsMenuComponent implements OnInit { locked: response.locked, }; - CoreEvents.trigger(AddonModForumProvider.CHANGE_DISCUSSION_EVENT, data, CoreSites.getCurrentSiteId()); + CoreEvents.trigger(ADDON_MOD_FORUM_CHANGE_DISCUSSION_EVENT, data, CoreSites.getCurrentSiteId()); PopoverController.dismiss({ action: 'lock', value: locked }); CoreDomUtils.showToast('addon.mod_forum.lockupdated', true); } catch (error) { @@ -100,7 +101,7 @@ export class AddonModForumDiscussionOptionsMenuComponent implements OnInit { pinned: pinned, }; - CoreEvents.trigger(AddonModForumProvider.CHANGE_DISCUSSION_EVENT, data, CoreSites.getCurrentSiteId()); + CoreEvents.trigger(ADDON_MOD_FORUM_CHANGE_DISCUSSION_EVENT, data, CoreSites.getCurrentSiteId()); PopoverController.dismiss({ action: 'pin', value: pinned }); CoreDomUtils.showToast('addon.mod_forum.pinupdated', true); } catch (error) { @@ -129,7 +130,7 @@ export class AddonModForumDiscussionOptionsMenuComponent implements OnInit { starred: starred, }; - CoreEvents.trigger(AddonModForumProvider.CHANGE_DISCUSSION_EVENT, data, CoreSites.getCurrentSiteId()); + CoreEvents.trigger(ADDON_MOD_FORUM_CHANGE_DISCUSSION_EVENT, data, CoreSites.getCurrentSiteId()); PopoverController.dismiss({ action: 'star', value: starred }); CoreDomUtils.showToast('addon.mod_forum.favouriteupdated', true); } catch (error) { diff --git a/src/addons/mod/forum/components/index/index.ts b/src/addons/mod/forum/components/index/index.ts index e087d013e..7746222cd 100644 --- a/src/addons/mod/forum/components/index/index.ts +++ b/src/addons/mod/forum/components/index/index.ts @@ -20,7 +20,6 @@ import { CoreCourseModuleMainActivityComponent } from '@features/course/classes/ import { AddonModForum, AddonModForumData, - AddonModForumProvider, AddonModForumSortOrder, AddonModForumDiscussion, AddonModForumNewDiscussionData, @@ -35,7 +34,6 @@ import { CoreEvents, CoreEventObserver } from '@singletons/events'; import { AddonModForumAutoSyncData, AddonModForumManualSyncData, - AddonModForumSyncProvider, AddonModForumSyncResult, } from '@addons/mod/forum/services/forum-sync'; import { CoreSites } from '@services/sites'; @@ -46,7 +44,6 @@ import { CoreSplitViewComponent } from '@components/split-view/split-view'; import { AddonModForumDiscussionOptionsMenuComponent } from '../discussion-options-menu/discussion-options-menu'; import { CoreScreen } from '@services/screen'; import { AddonModForumPrefetchHandler } from '../../services/handlers/prefetch'; -import { AddonModForumModuleHandlerService } from '../../services/handlers/module'; import { CoreRatingProvider } from '@features/rating/services/rating'; import { CoreRatingSyncProvider } from '@features/rating/services/rating-sync'; import { CoreRatingOffline } from '@features/rating/services/rating-offline'; @@ -56,7 +53,17 @@ import { CoreListItemsManager } from '@classes/items-management/list-items-manag import { CoreRoutedItemsManagerSourcesTracker } from '@classes/items-management/routed-items-manager-sources-tracker'; import { CorePromisedValue } from '@classes/promised-value'; import { CoreNavigator } from '@services/navigator'; -import { ADDON_MOD_FORUM_SEARCH_PAGE_NAME } from '@addons/mod/forum/constants'; +import { + ADDON_MOD_FORUM_AUTO_SYNCED, + ADDON_MOD_FORUM_CHANGE_DISCUSSION_EVENT, + ADDON_MOD_FORUM_COMPONENT, + ADDON_MOD_FORUM_MANUAL_SYNCED, + ADDON_MOD_FORUM_NEW_DISCUSSION_EVENT, + ADDON_MOD_FORUM_PAGE_NAME, + ADDON_MOD_FORUM_PREFERENCE_SORTORDER, + ADDON_MOD_FORUM_REPLY_DISCUSSION_EVENT, + ADDON_MOD_FORUM_SEARCH_PAGE_NAME, +} from '@addons/mod/forum/constants'; import { CoreSearchGlobalSearch } from '@features/search/services/global-search'; /** * Component that displays a forum entry page. @@ -70,7 +77,7 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom @ViewChild(CoreSplitViewComponent) splitView!: CoreSplitViewComponent; - component = AddonModForumProvider.COMPONENT; + component = ADDON_MOD_FORUM_COMPONENT; pluginName = 'forum'; descriptionNote?: string; promisedDiscussions: CorePromisedValue; @@ -87,7 +94,7 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom showSearch = false; protected fetchContentDefaultError = 'addon.mod_forum.errorgetforum'; - protected syncEventName = AddonModForumSyncProvider.AUTO_SYNCED; + protected syncEventName = ADDON_MOD_FORUM_AUTO_SYNCED; protected syncManualObserver?: CoreEventObserver; // It will observe the sync manual event. protected replyObserver?: CoreEventObserver; protected newDiscObserver?: CoreEventObserver; @@ -188,7 +195,7 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom // Initialize discussions manager. const source = CoreRoutedItemsManagerSourcesTracker.getOrCreateSource( AddonModForumDiscussionsSource, - [this.courseId, this.module.id, this.courseContentsPage ? `${AddonModForumModuleHandlerService.PAGE_NAME}/` : ''], + [this.courseId, this.module.id, this.courseContentsPage ? `${ADDON_MOD_FORUM_PAGE_NAME}/` : ''], ); this.sourceUnsubscribe = source.addListener({ @@ -229,20 +236,20 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom this.promisedDiscussions.resolve(new AddonModForumDiscussionsManager(source, this)); // Refresh data if this forum discussion is synchronized from discussions list. - this.syncManualObserver = CoreEvents.on(AddonModForumSyncProvider.MANUAL_SYNCED, (data) => { + this.syncManualObserver = CoreEvents.on(ADDON_MOD_FORUM_MANUAL_SYNCED, (data) => { this.autoSyncEventReceived(data); }, this.siteId); // Listen for discussions added. When a discussion is added, we reload the data. this.newDiscObserver = CoreEvents.on( - AddonModForumProvider.NEW_DISCUSSION_EVENT, + ADDON_MOD_FORUM_NEW_DISCUSSION_EVENT, (data) => this.eventReceived(true, data), ); this.replyObserver = CoreEvents.on( - AddonModForumProvider.REPLY_DISCUSSION_EVENT, + ADDON_MOD_FORUM_REPLY_DISCUSSION_EVENT, (data) => this.eventReceived(false, data), ); - this.changeDiscObserver = CoreEvents.on(AddonModForumProvider.CHANGE_DISCUSSION_EVENT, data => { + this.changeDiscObserver = CoreEvents.on(ADDON_MOD_FORUM_CHANGE_DISCUSSION_EVENT, data => { if (!this.forum) { return; } @@ -419,7 +426,7 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom if (updated) { // Sync successful, send event. - CoreEvents.trigger(AddonModForumSyncProvider.MANUAL_SYNCED, { + CoreEvents.trigger(ADDON_MOD_FORUM_MANUAL_SYNCED, { forumId: forum.id, userId: CoreSites.getCurrentSiteUserId(), source: 'index', @@ -502,7 +509,7 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom } if (this.sortingAvailable) { - promises.push(CoreUser.invalidateUserPreference(AddonModForumProvider.PREFERENCE_SORTORDER)); + promises.push(CoreUser.invalidateUserPreference(ADDON_MOD_FORUM_PREFERENCE_SORTORDER)); } await Promise.all(promises); @@ -602,7 +609,7 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom this.discussions.getSource().setDirty(true); try { - await CoreUser.setUserPreference(AddonModForumProvider.PREFERENCE_SORTORDER, sortOrder.value.toFixed(0)); + await CoreUser.setUserPreference(ADDON_MOD_FORUM_PREFERENCE_SORTORDER, sortOrder.value.toFixed(0)); await this.showLoadingAndFetch(); } catch (error) { CoreDomUtils.showErrorModalDefault(error, 'Error updating preference.'); diff --git a/src/addons/mod/forum/components/post/post.ts b/src/addons/mod/forum/components/post/post.ts index ab834b428..49f7b0db0 100644 --- a/src/addons/mod/forum/components/post/post.ts +++ b/src/addons/mod/forum/components/post/post.ts @@ -34,7 +34,6 @@ import { AddonModForumData, AddonModForumDiscussion, AddonModForumPost, - AddonModForumProvider, AddonModForumPostFormData, } from '../../services/forum'; import { CoreTag } from '@features/tag/services/tag'; @@ -53,6 +52,7 @@ import { CoreFileEntry } from '@services/file-helper'; import { AddonModForumSharedPostFormData } from '../../pages/discussion/discussion'; import { CoreDom } from '@singletons/dom'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; +import { ADDON_MOD_FORUM_CHANGE_DISCUSSION_EVENT, ADDON_MOD_FORUM_COMPONENT } from '../../constants'; /** * Components that shows a discussion post, its attachments and the action buttons allowed (reply, etc.). @@ -162,7 +162,7 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges }; CoreEvents.trigger( - AddonModForumProvider.CHANGE_DISCUSSION_EVENT, + ADDON_MOD_FORUM_CHANGE_DISCUSSION_EVENT, data, CoreSites.getCurrentSiteId(), ); @@ -307,7 +307,7 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges await this.confirmDiscard(); this.formData.syncId = AddonModForumSync.getDiscussionSyncId(this.discussionId); - CoreSync.blockOperation(AddonModForumProvider.COMPONENT, this.formData.syncId); + CoreSync.blockOperation(ADDON_MOD_FORUM_COMPONENT, this.formData.syncId); this.setFormData( this.post.parentid, @@ -546,7 +546,7 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges return; } - CoreSync.unblockOperation(AddonModForumProvider.COMPONENT, this.formData.syncId); + CoreSync.unblockOperation(ADDON_MOD_FORUM_COMPONENT, this.formData.syncId); delete this.formData.syncId; } diff --git a/src/addons/mod/forum/constants.ts b/src/addons/mod/forum/constants.ts index e238a9e5f..459bf53e2 100644 --- a/src/addons/mod/forum/constants.ts +++ b/src/addons/mod/forum/constants.ts @@ -12,4 +12,30 @@ // See the License for the specific language governing permissions and // limitations under the License. +export const ADDON_MOD_FORUM_PAGE_NAME = 'mod_forum'; export const ADDON_MOD_FORUM_SEARCH_PAGE_NAME = 'forum/search'; + +export const ADDON_MOD_FORUM_COMPONENT = 'mmaModForum'; + +export const ADDON_MOD_FORUM_AUTO_SYNCED = 'addon_mod_forum_autom_synced'; +export const ADDON_MOD_FORUM_MANUAL_SYNCED = 'addon_mod_forum_manual_synced'; + +export const ADDON_MOD_FORUM_DISCUSSIONS_PER_PAGE = 10; // Max of discussions per page. +export const ADDON_MOD_FORUM_NEW_DISCUSSION_EVENT = 'addon_mod_forum_new_discussion'; +export const ADDON_MOD_FORUM_REPLY_DISCUSSION_EVENT = 'addon_mod_forum_reply_discussion'; +export const ADDON_MOD_FORUM_CHANGE_DISCUSSION_EVENT = 'addon_mod_forum_change_discussion_status'; +export const ADDON_MOD_FORUM_MARK_READ_EVENT = 'addon_mod_forum_mark_read'; + +export const ADDON_MOD_FORUM_PREFERENCE_SORTORDER = 'forum_discussionlistsortorder'; + +export const enum AddonModForumSortorder { + LASTPOST_DESC = 1, + LASTPOST_ASC = 2, + CREATED_DESC = 3, + CREATED_ASC = 4, + REPLIES_DESC = 5, + REPLIES_ASC = 6, +} + +export const ADDON_MOD_FORUM_ALL_PARTICIPANTS = -1; +export const ADDON_MOD_FORUM_ALL_GROUPS = -2; diff --git a/src/addons/mod/forum/forum-discussion-lazy.module.ts b/src/addons/mod/forum/forum-discussion-lazy.module.ts index a365aacc9..6c6a19681 100644 --- a/src/addons/mod/forum/forum-discussion-lazy.module.ts +++ b/src/addons/mod/forum/forum-discussion-lazy.module.ts @@ -36,4 +36,4 @@ const routes: Routes = [{ AddonModForumDiscussionPage, ], }) -export class AddonModForumDiscussionLazyModule {} +export default class AddonModForumDiscussionLazyModule {} diff --git a/src/addons/mod/forum/forum-lazy.module.ts b/src/addons/mod/forum/forum-lazy.module.ts index 8610f26b5..ff14520f5 100644 --- a/src/addons/mod/forum/forum-lazy.module.ts +++ b/src/addons/mod/forum/forum-lazy.module.ts @@ -29,15 +29,15 @@ const mobileRoutes: Routes = [ }, { path: ':courseId/:cmId/new/:timeCreated', - loadChildren: () => import('./forum-new-discussion-lazy.module').then(m => m.AddonModForumNewDiscussionLazyModule), + loadChildren: () => import('./forum-new-discussion-lazy.module'), }, { path: ':courseId/:cmId/:discussionId', - loadChildren: () => import('./forum-discussion-lazy.module').then(m => m.AddonModForumDiscussionLazyModule), + loadChildren: () => import('./forum-discussion-lazy.module'), }, { path: 'discussion/:discussionId', // Only for discussion link handling. - loadChildren: () => import('./forum-discussion-lazy.module').then(m => m.AddonModForumDiscussionLazyModule), + loadChildren: () => import('./forum-discussion-lazy.module'), }, ]; @@ -48,11 +48,11 @@ const tabletRoutes: Routes = [ children: [ { path: 'new/:timeCreated', - loadChildren: () => import('./forum-new-discussion-lazy.module').then(m => m.AddonModForumNewDiscussionLazyModule), + loadChildren: () => import('./forum-new-discussion-lazy.module'), }, { path: ':discussionId', - loadChildren: () => import('./forum-discussion-lazy.module').then(m => m.AddonModForumDiscussionLazyModule), + loadChildren: () => import('./forum-discussion-lazy.module'), }, ], }, @@ -73,4 +73,4 @@ const routes: Routes = [ AddonModForumIndexPage, ], }) -export class AddonModForumLazyModule {} +export default class AddonModForumLazyModule {} diff --git a/src/addons/mod/forum/forum-new-discussion-lazy.module.ts b/src/addons/mod/forum/forum-new-discussion-lazy.module.ts index a1224b72b..72fb57ea2 100644 --- a/src/addons/mod/forum/forum-new-discussion-lazy.module.ts +++ b/src/addons/mod/forum/forum-new-discussion-lazy.module.ts @@ -38,4 +38,4 @@ const routes: Routes = [{ AddonModForumNewDiscussionPage, ], }) -export class AddonModForumNewDiscussionLazyModule {} +export default class AddonModForumNewDiscussionLazyModule {} diff --git a/src/addons/mod/forum/forum-search-lazy.module.ts b/src/addons/mod/forum/forum-search-lazy.module.ts index 64e02c6ba..c7f09a364 100644 --- a/src/addons/mod/forum/forum-search-lazy.module.ts +++ b/src/addons/mod/forum/forum-search-lazy.module.ts @@ -35,4 +35,4 @@ const routes: Routes = [{ AddonModForumSearchPage, ], }) -export class AddonModForumSearchLazyModule {} +export default class AddonModForumSearchLazyModule {} diff --git a/src/addons/mod/forum/forum.module.ts b/src/addons/mod/forum/forum.module.ts index bdc2095cc..c7bfbe804 100644 --- a/src/addons/mod/forum/forum.module.ts +++ b/src/addons/mod/forum/forum.module.ts @@ -22,7 +22,7 @@ import { CoreCourseModuleDelegate } from '@features/course/services/module-deleg import { CoreMainMenuTabRoutingModule } from '@features/mainmenu/mainmenu-tab-routing.module'; import { CoreScreen } from '@services/screen'; -import { AddonModForumModuleHandler, AddonModForumModuleHandlerService } from './services/handlers/module'; +import { AddonModForumModuleHandler } from './services/handlers/module'; import { SITE_SCHEMA } from './services/database/offline'; import { CoreCourseModulePrefetchDelegate } from '@features/course/services/module-prefetch-delegate'; import { AddonModForumPrefetchHandler } from './services/handlers/prefetch'; @@ -37,36 +37,35 @@ import { CoreTagAreaDelegate } from '@features/tag/services/tag-area-delegate'; import { AddonModForumTagAreaHandler } from './services/handlers/tag-area'; import { CorePushNotificationsDelegate } from '@features/pushnotifications/services/push-delegate'; import { AddonModForumPushClickHandler } from './services/handlers/push-click'; -import { AddonModForumProvider } from './services/forum'; import { COURSE_CONTENTS_PATH } from '@features/course/course.module'; import { CoreCourseHelper } from '@features/course/services/course-helper'; -import { ADDON_MOD_FORUM_SEARCH_PAGE_NAME } from './constants'; +import { ADDON_MOD_FORUM_COMPONENT, ADDON_MOD_FORUM_PAGE_NAME, ADDON_MOD_FORUM_SEARCH_PAGE_NAME } from './constants'; const mainMenuRoutes: Routes = [ { path: ADDON_MOD_FORUM_SEARCH_PAGE_NAME, - loadChildren: () => import('./forum-search-lazy.module').then(m => m.AddonModForumSearchLazyModule), + loadChildren: () => import('./forum-search-lazy.module'), }, { - path: `${AddonModForumModuleHandlerService.PAGE_NAME}/discussion/:discussionId`, - loadChildren: () => import('./forum-discussion-lazy.module').then(m => m.AddonModForumDiscussionLazyModule), + path: `${ADDON_MOD_FORUM_PAGE_NAME}/discussion/:discussionId`, + loadChildren: () => import('./forum-discussion-lazy.module'), data: { swipeEnabled: false }, }, { - path: AddonModForumModuleHandlerService.PAGE_NAME, - loadChildren: () => import('./forum-lazy.module').then(m => m.AddonModForumLazyModule), + path: ADDON_MOD_FORUM_PAGE_NAME, + loadChildren: () => import('./forum-lazy.module'), }, ...conditionalRoutes( [ { - path: `${COURSE_CONTENTS_PATH}/${AddonModForumModuleHandlerService.PAGE_NAME}/new/:timeCreated`, - loadChildren: () => import('./forum-new-discussion-lazy.module').then(m => m.AddonModForumNewDiscussionLazyModule), - data: { discussionsPathPrefix: `${AddonModForumModuleHandlerService.PAGE_NAME}/` }, + path: `${COURSE_CONTENTS_PATH}/${ADDON_MOD_FORUM_PAGE_NAME}/new/:timeCreated`, + loadChildren: () => import('./forum-new-discussion-lazy.module'), + data: { discussionsPathPrefix: `${ADDON_MOD_FORUM_PAGE_NAME}/` }, }, { - path: `${COURSE_CONTENTS_PATH}/${AddonModForumModuleHandlerService.PAGE_NAME}/:discussionId`, - loadChildren: () => import('./forum-discussion-lazy.module').then(m => m.AddonModForumDiscussionLazyModule), - data: { discussionsPathPrefix: `${AddonModForumModuleHandlerService.PAGE_NAME}/` }, + path: `${COURSE_CONTENTS_PATH}/${ADDON_MOD_FORUM_PAGE_NAME}/:discussionId`, + loadChildren: () => import('./forum-discussion-lazy.module'), + data: { discussionsPathPrefix: `${ADDON_MOD_FORUM_PAGE_NAME}/` }, }, ], () => CoreScreen.isMobile, @@ -77,14 +76,14 @@ const mainMenuRoutes: Routes = [ const courseContentsRoutes: Routes = conditionalRoutes( [ { - path: `${AddonModForumModuleHandlerService.PAGE_NAME}/new/:timeCreated`, - loadChildren: () => import('./forum-new-discussion-lazy.module').then(m => m.AddonModForumNewDiscussionLazyModule), - data: { discussionsPathPrefix: `${AddonModForumModuleHandlerService.PAGE_NAME}/` }, + path: `${ADDON_MOD_FORUM_PAGE_NAME}/new/:timeCreated`, + loadChildren: () => import('./forum-new-discussion-lazy.module'), + data: { discussionsPathPrefix: `${ADDON_MOD_FORUM_PAGE_NAME}/` }, }, { - path: `${AddonModForumModuleHandlerService.PAGE_NAME}/:discussionId`, - loadChildren: () => import('./forum-discussion-lazy.module').then(m => m.AddonModForumDiscussionLazyModule), - data: { discussionsPathPrefix: `${AddonModForumModuleHandlerService.PAGE_NAME}/` }, + path: `${ADDON_MOD_FORUM_PAGE_NAME}/:discussionId`, + loadChildren: () => import('./forum-discussion-lazy.module'), + data: { discussionsPathPrefix: `${ADDON_MOD_FORUM_PAGE_NAME}/` }, }, ], () => CoreScreen.isTablet, @@ -115,7 +114,7 @@ const courseContentsRoutes: Routes = conditionalRoutes( CoreTagAreaDelegate.registerHandler(AddonModForumTagAreaHandler.instance); CorePushNotificationsDelegate.registerClickHandler(AddonModForumPushClickHandler.instance); - CoreCourseHelper.registerModuleReminderClick(AddonModForumProvider.COMPONENT); + CoreCourseHelper.registerModuleReminderClick(ADDON_MOD_FORUM_COMPONENT); }, }, ], diff --git a/src/addons/mod/forum/pages/discussion/discussion.ts b/src/addons/mod/forum/pages/discussion/discussion.ts index a4635b9dd..e4d69c9fd 100644 --- a/src/addons/mod/forum/pages/discussion/discussion.ts +++ b/src/addons/mod/forum/pages/discussion/discussion.ts @@ -42,15 +42,22 @@ import { AddonModForumData, AddonModForumDiscussion, AddonModForumPost, - AddonModForumProvider, AddonModForumPostFormData, AddonModForumChangeDiscussionData, AddonModForumReplyDiscussionData, } from '../../services/forum'; import { AddonModForumHelper } from '../../services/forum-helper'; import { AddonModForumOffline } from '../../services/forum-offline'; -import { AddonModForumSync, AddonModForumSyncProvider } from '../../services/forum-sync'; +import { AddonModForumSync } from '../../services/forum-sync'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; +import { + ADDON_MOD_FORUM_AUTO_SYNCED, + ADDON_MOD_FORUM_CHANGE_DISCUSSION_EVENT, + ADDON_MOD_FORUM_COMPONENT, + ADDON_MOD_FORUM_MANUAL_SYNCED, + ADDON_MOD_FORUM_MARK_READ_EVENT, + ADDON_MOD_FORUM_REPLY_DISCUSSION_EVENT, +} from '../../constants'; type SortType = 'flat-newest' | 'flat-oldest' | 'nested'; @@ -101,7 +108,7 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes refreshIcon = CoreConstants.ICON_LOADING; syncIcon = CoreConstants.ICON_LOADING; discussionStr = ''; - component = AddonModForumProvider.COMPONENT; + component = ADDON_MOD_FORUM_COMPONENT; cmId?: number; canPin = false; availabilityMessage: string | null = null; @@ -216,7 +223,7 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes const discussion = this.discussion; // Refresh data if this discussion is synchronized automatically. - this.syncObserver = CoreEvents.on(AddonModForumSyncProvider.AUTO_SYNCED, data => { + this.syncObserver = CoreEvents.on(ADDON_MOD_FORUM_AUTO_SYNCED, data => { if (data.forumId == this.forumId && this.discussionId == data.discussionId && data.userId == CoreSites.getCurrentSiteUserId()) { // Refresh the data. @@ -226,7 +233,7 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes }, CoreSites.getCurrentSiteId()); // Refresh data if this forum discussion is synchronized from discussions list. - this.syncManualObserver = CoreEvents.on(AddonModForumSyncProvider.MANUAL_SYNCED, data => { + this.syncManualObserver = CoreEvents.on(ADDON_MOD_FORUM_MANUAL_SYNCED, data => { if (data.source != 'discussion' && data.forumId == this.forumId && data.userId == CoreSites.getCurrentSiteUserId()) { // Refresh the data. @@ -255,7 +262,7 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes } }); - this.changeDiscObserver = CoreEvents.on(AddonModForumProvider.CHANGE_DISCUSSION_EVENT, data => { + this.changeDiscObserver = CoreEvents.on(ADDON_MOD_FORUM_CHANGE_DISCUSSION_EVENT, data => { if (discussion && this.forumId && (this.forumId === data.forumId || data.cmId === this.cmId)) { AddonModForum.invalidateDiscussionsList(this.forumId).finally(() => { if (data.locked !== undefined) { @@ -607,7 +614,7 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes if (result && result.updated && this.forumId) { // Sync successful, send event. - CoreEvents.trigger(AddonModForumSyncProvider.MANUAL_SYNCED, { + CoreEvents.trigger(ADDON_MOD_FORUM_MANUAL_SYNCED, { forumId: this.forumId, userId: CoreSites.getCurrentSiteUserId(), source: 'discussion', @@ -719,7 +726,7 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes cmId: this.cmId, locked: this.discussion.locked, }; - CoreEvents.trigger(AddonModForumProvider.CHANGE_DISCUSSION_EVENT, data, CoreSites.getCurrentSiteId()); + CoreEvents.trigger(ADDON_MOD_FORUM_CHANGE_DISCUSSION_EVENT, data, CoreSites.getCurrentSiteId()); CoreDomUtils.showToast('addon.mod_forum.lockupdated', true); } catch (error) { @@ -752,7 +759,7 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes cmId: this.cmId, pinned: this.discussion.pinned, }; - CoreEvents.trigger(AddonModForumProvider.CHANGE_DISCUSSION_EVENT, data, CoreSites.getCurrentSiteId()); + CoreEvents.trigger(ADDON_MOD_FORUM_CHANGE_DISCUSSION_EVENT, data, CoreSites.getCurrentSiteId()); CoreDomUtils.showToast('addon.mod_forum.pinupdated', true); } catch (error) { @@ -785,7 +792,7 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes cmId: this.cmId, starred: this.discussion.starred, }; - CoreEvents.trigger(AddonModForumProvider.CHANGE_DISCUSSION_EVENT, data, CoreSites.getCurrentSiteId()); + CoreEvents.trigger(ADDON_MOD_FORUM_CHANGE_DISCUSSION_EVENT, data, CoreSites.getCurrentSiteId()); CoreDomUtils.showToast('addon.mod_forum.favouriteupdated', true); } catch (error) { @@ -809,7 +816,7 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes discussionId: this.discussionId, cmId: this.cmId, }; - CoreEvents.trigger(AddonModForumProvider.REPLY_DISCUSSION_EVENT, data, CoreSites.getCurrentSiteId()); + CoreEvents.trigger(ADDON_MOD_FORUM_REPLY_DISCUSSION_EVENT, data, CoreSites.getCurrentSiteId()); this.discussionLoaded = false; this.refreshPosts().finally(() => { @@ -868,7 +875,7 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes } // Trigger mark read posts. - CoreEvents.trigger(AddonModForumProvider.MARK_READ_EVENT, { + CoreEvents.trigger(ADDON_MOD_FORUM_MARK_READ_EVENT, { courseId: this.courseId, moduleId: this.cmId, }, CoreSites.getCurrentSiteId()); diff --git a/src/addons/mod/forum/pages/new-discussion/new-discussion.ts b/src/addons/mod/forum/pages/new-discussion/new-discussion.ts index 54e6512e7..a3ae2f2d4 100644 --- a/src/addons/mod/forum/pages/new-discussion/new-discussion.ts +++ b/src/addons/mod/forum/pages/new-discussion/new-discussion.ts @@ -23,10 +23,9 @@ import { AddonModForumAccessInformation, AddonModForumCanAddDiscussion, AddonModForumData, - AddonModForumProvider, } from '@addons/mod/forum/services/forum'; import { CoreEditorRichTextEditorComponent } from '@features/editor/components/rich-text-editor/rich-text-editor'; -import { AddonModForumSync, AddonModForumSyncProvider } from '@addons/mod/forum/services/forum-sync'; +import { AddonModForumSync } from '@addons/mod/forum/services/forum-sync'; import { CoreSites } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { Translate } from '@singletons'; @@ -45,6 +44,13 @@ import { AddonModForumDiscussionsSource } from '../../classes/forum-discussions- import { CoreRoutedItemsManagerSourcesTracker } from '@classes/items-management/routed-items-manager-sources-tracker'; import { CoreTime } from '@singletons/time'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; +import { + ADDON_MOD_FORUM_ALL_GROUPS, + ADDON_MOD_FORUM_ALL_PARTICIPANTS, + ADDON_MOD_FORUM_AUTO_SYNCED, + ADDON_MOD_FORUM_COMPONENT, + ADDON_MOD_FORUM_NEW_DISCUSSION_EVENT, +} from '../../constants'; type NewDiscussionData = { subject: string; @@ -69,7 +75,7 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea @ViewChild('newDiscFormEl') formElement!: ElementRef; @ViewChild(CoreEditorRichTextEditorComponent) messageEditor!: CoreEditorRichTextEditorComponent; - component = AddonModForumProvider.COMPONENT; + component = ADDON_MOD_FORUM_COMPONENT; messageControl = new FormControl(null); groupsLoaded = false; showGroups = false; @@ -133,7 +139,7 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea this.initialGroupId = CoreNavigator.getRouteNumberParam('groupId'); // Discussion list uses 0 for all participants, but this page WebServices use a different value. Convert it. - this.initialGroupId = this.initialGroupId === 0 ? AddonModForumProvider.ALL_PARTICIPANTS : this.initialGroupId; + this.initialGroupId = this.initialGroupId === 0 ? ADDON_MOD_FORUM_ALL_PARTICIPANTS : this.initialGroupId; if (this.timeCreated !== 0 && (routeData.swipeEnabled ?? true)) { const source = CoreRoutedItemsManagerSourcesTracker.getOrCreateSource( @@ -168,7 +174,7 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea } // Refresh data if this discussion is synchronized automatically. - this.syncObserver = CoreEvents.on(AddonModForumSyncProvider.AUTO_SYNCED, data => { + this.syncObserver = CoreEvents.on(ADDON_MOD_FORUM_AUTO_SYNCED, data => { if (data.forumId == this.forumId && data.userId == CoreSites.getCurrentSiteUserId()) { CoreDomUtils.showAlertTranslated('core.notice', 'core.contenteditingsynced'); this.returnToDiscussions(); @@ -262,7 +268,7 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea await AddonModForumSync.waitForSync(this.syncId).then(() => { // Do not block if the scope is already destroyed. if (!this.isDestroyed) { - CoreSync.blockOperation(AddonModForumProvider.COMPONENT, this.syncId); + CoreSync.blockOperation(ADDON_MOD_FORUM_COMPONENT, this.syncId); } return AddonModForumOffline.instance @@ -270,7 +276,7 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea .then(async (discussion) => { this.hasOffline = true; discussion.options = discussion.options || {}; - if (discussion.groupid == AddonModForumProvider.ALL_GROUPS) { + if (discussion.groupid == ADDON_MOD_FORUM_ALL_GROUPS) { this.newDiscussion.groupId = this.groups[0].id; this.newDiscussion.postToAllGroups = true; } else { @@ -438,7 +444,7 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea if (canAdd) { groups.unshift({ courseid: this.courseId, - id: AddonModForumProvider.ALL_PARTICIPANTS, + id: ADDON_MOD_FORUM_ALL_PARTICIPANTS, name: Translate.instant('core.allparticipants'), }); } @@ -479,7 +485,7 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea CoreFileUploader.clearTmpFiles(this.newDiscussion.files); CoreEvents.trigger( - AddonModForumProvider.NEW_DISCUSSION_EVENT, + ADDON_MOD_FORUM_NEW_DISCUSSION_EVENT, { forumId: this.forumId, cmId: this.cmId, @@ -683,7 +689,7 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea */ ngOnDestroy(): void { if (this.syncId) { - CoreSync.unblockOperation(AddonModForumProvider.COMPONENT, this.syncId); + CoreSync.unblockOperation(ADDON_MOD_FORUM_COMPONENT, this.syncId); } this.isDestroyed = true; this.discussions?.destroy(); diff --git a/src/addons/mod/forum/services/forum-helper.ts b/src/addons/mod/forum/services/forum-helper.ts index a3c45cd35..29d822ae4 100644 --- a/src/addons/mod/forum/services/forum-helper.ts +++ b/src/addons/mod/forum/services/forum-helper.ts @@ -28,10 +28,10 @@ import { AddonModForumData, AddonModForumDiscussion, AddonModForumPost, - AddonModForumProvider, } from './forum'; import { AddonModForumDiscussionOptions, AddonModForumOffline, AddonModForumOfflineReply } from './forum-offline'; import { CoreFileEntry } from '@services/file-helper'; +import { ADDON_MOD_FORUM_ALL_GROUPS, ADDON_MOD_FORUM_COMPONENT } from '../constants'; /** * Service that provides some features for forums. @@ -76,7 +76,7 @@ export class AddonModForumHelperProvider { // Convenience function to store a message to be synchronized later. const storeOffline = async (): Promise => { // Multiple groups, the discussion is being posted to all groups. - const groupId = groupIds.length > 1 ? AddonModForumProvider.ALL_GROUPS : groupIds[0]; + const groupId = groupIds.length > 1 ? ADDON_MOD_FORUM_ALL_GROUPS : groupIds[0]; if (offlineAttachments && options) { options.attachmentsid = offlineAttachments; @@ -502,7 +502,7 @@ export class AddonModForumHelperProvider { return this.storeNewDiscussionFiles(forumId, timecreated, files, siteId); } - return CoreFileUploader.uploadOrReuploadFiles(files, AddonModForumProvider.COMPONENT, forumId, siteId); + return CoreFileUploader.uploadOrReuploadFiles(files, ADDON_MOD_FORUM_COMPONENT, forumId, siteId); } /** @@ -544,7 +544,7 @@ export class AddonModForumHelperProvider { return this.storeReplyFiles(forumId, postId, files, siteId, userId); } - return CoreFileUploader.uploadOrReuploadFiles(files, AddonModForumProvider.COMPONENT, forumId, siteId); + return CoreFileUploader.uploadOrReuploadFiles(files, ADDON_MOD_FORUM_COMPONENT, forumId, siteId); } } diff --git a/src/addons/mod/forum/services/forum-offline.ts b/src/addons/mod/forum/services/forum-offline.ts index d586decca..3628192a4 100644 --- a/src/addons/mod/forum/services/forum-offline.ts +++ b/src/addons/mod/forum/services/forum-offline.ts @@ -18,7 +18,6 @@ import { CoreFile } from '@services/file'; import { CoreSites } from '@services/sites'; import { CoreTextUtils } from '@services/utils/text'; import { makeSingleton } from '@singletons'; -import { AddonModForumProvider } from './forum'; import { AddonModForumOfflineDiscussionDBRecord, AddonModForumOfflineReplyDBRecord, @@ -26,6 +25,7 @@ import { REPLIES_TABLE, } from './database/offline'; import { CorePath } from '@singletons/path'; +import { ADDON_MOD_FORUM_ALL_PARTICIPANTS } from '../constants'; /** * Service to handle offline forum. @@ -168,7 +168,7 @@ export class AddonModForumOfflineProvider { subject: subject, message: message, options: JSON.stringify(options || {}), - groupid: groupId || AddonModForumProvider.ALL_PARTICIPANTS, + groupid: groupId || ADDON_MOD_FORUM_ALL_PARTICIPANTS, userid: userId || site.getUserId(), timecreated: timeCreated || Date.now(), }; diff --git a/src/addons/mod/forum/services/forum-sync.ts b/src/addons/mod/forum/services/forum-sync.ts index b2324c12d..d7936d0a3 100644 --- a/src/addons/mod/forum/services/forum-sync.ts +++ b/src/addons/mod/forum/services/forum-sync.ts @@ -29,10 +29,15 @@ import { AddonModForum, AddonModForumAddDiscussionPostWSOptionsObject, AddonModForumAddDiscussionWSOptionsObject, - AddonModForumProvider, } from './forum'; import { AddonModForumHelper } from './forum-helper'; import { AddonModForumOffline, AddonModForumOfflineDiscussion, AddonModForumOfflineReply } from './forum-offline'; +import { + ADDON_MOD_FORUM_ALL_GROUPS, + ADDON_MOD_FORUM_AUTO_SYNCED, + ADDON_MOD_FORUM_COMPONENT, + ADDON_MOD_FORUM_MANUAL_SYNCED, +} from '../constants'; declare module '@singletons/events' { @@ -42,8 +47,8 @@ declare module '@singletons/events' { * @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation */ export interface CoreEventsData { - [AddonModForumSyncProvider.AUTO_SYNCED]: AddonModForumAutoSyncData; - [AddonModForumSyncProvider.MANUAL_SYNCED]: AddonModForumManualSyncData; + [ADDON_MOD_FORUM_AUTO_SYNCED]: AddonModForumAutoSyncData; + [ADDON_MOD_FORUM_MANUAL_SYNCED]: AddonModForumManualSyncData; } } @@ -54,9 +59,6 @@ declare module '@singletons/events' { @Injectable({ providedIn: 'root' }) export class AddonModForumSyncProvider extends CoreCourseActivitySyncBaseProvider { - static readonly AUTO_SYNCED = 'addon_mod_forum_autom_synced'; - static readonly MANUAL_SYNCED = 'addon_mod_forum_manual_synced'; - protected componentTranslatableString = 'forum'; constructor() { @@ -100,7 +102,7 @@ export class AddonModForumSyncProvider extends CoreCourseActivitySyncBaseProvide if (result && result.updated) { // Sync successful, send event. - CoreEvents.trigger(AddonModForumSyncProvider.AUTO_SYNCED, { + CoreEvents.trigger(ADDON_MOD_FORUM_AUTO_SYNCED, { forumId: discussion.forumid, userId: discussion.userid, warnings: result.warnings, @@ -134,7 +136,7 @@ export class AddonModForumSyncProvider extends CoreCourseActivitySyncBaseProvide if (result && result.updated) { // Sync successful, send event. - CoreEvents.trigger(AddonModForumSyncProvider.AUTO_SYNCED, { + CoreEvents.trigger(ADDON_MOD_FORUM_AUTO_SYNCED, { forumId: reply.forumid, discussionId: reply.discussionid, userId: reply.userid, @@ -207,7 +209,7 @@ export class AddonModForumSyncProvider extends CoreCourseActivitySyncBaseProvide } // Verify that forum isn't blocked. - if (CoreSync.isBlocked(AddonModForumProvider.COMPONENT, syncId, siteId)) { + if (CoreSync.isBlocked(ADDON_MOD_FORUM_COMPONENT, syncId, siteId)) { this.logger.debug('Cannot sync forum ' + forumId + ' because it is blocked.'); throw new Error(Translate.instant('core.errorsyncblocked', { $a: this.componentTranslate })); @@ -223,7 +225,7 @@ export class AddonModForumSyncProvider extends CoreCourseActivitySyncBaseProvide // Sync offline logs. const syncDiscussions = async (): Promise => { await CoreUtils.ignoreErrors( - CoreCourseLogHelper.syncActivity(AddonModForumProvider.COMPONENT, forumId, siteId), + CoreCourseLogHelper.syncActivity(ADDON_MOD_FORUM_COMPONENT, forumId, siteId), ); // Get offline responses to be sent. @@ -238,7 +240,7 @@ export class AddonModForumSyncProvider extends CoreCourseActivitySyncBaseProvide const promises = discussions.map(async discussion => { const errors: Error[] = []; - const groupIds = discussion.groupid === AddonModForumProvider.ALL_GROUPS + const groupIds = discussion.groupid === ADDON_MOD_FORUM_ALL_GROUPS ? await AddonModForum.instance .getForumById(discussion.courseid, discussion.forumid, { siteId }) .then(forum => CoreGroups.getActivityAllowedGroups(forum.cmid)) @@ -439,7 +441,7 @@ export class AddonModForumSyncProvider extends CoreCourseActivitySyncBaseProvide } // Verify that forum isn't blocked. - if (CoreSync.isBlocked(AddonModForumProvider.COMPONENT, syncId, siteId)) { + if (CoreSync.isBlocked(ADDON_MOD_FORUM_COMPONENT, syncId, siteId)) { this.logger.debug('Cannot sync forum discussion ' + discussionId + ' because it is blocked.'); throw new Error(Translate.instant('core.errorsyncblocked', { $a: this.componentTranslate })); @@ -607,7 +609,7 @@ export class AddonModForumSyncProvider extends CoreCourseActivitySyncBaseProvide } } - return CoreFileUploader.uploadOrReuploadFiles(files, AddonModForumProvider.COMPONENT, forumId, siteId); + return CoreFileUploader.uploadOrReuploadFiles(files, ADDON_MOD_FORUM_COMPONENT, forumId, siteId); } /** diff --git a/src/addons/mod/forum/services/forum.ts b/src/addons/mod/forum/services/forum.ts index 676b21b5b..21ad741b5 100644 --- a/src/addons/mod/forum/services/forum.ts +++ b/src/addons/mod/forum/services/forum.ts @@ -30,8 +30,18 @@ import { CoreStatusWithWarningsWSResponse, CoreWSExternalFile, CoreWSExternalWar import { makeSingleton, Translate } from '@singletons'; import { AddonModForumOffline, AddonModForumOfflineDiscussion, AddonModForumReplyOptions } from './forum-offline'; import { CoreSiteWSPreSets } from '@classes/sites/authenticated-site'; - -const ROOT_CACHE_KEY = 'mmaModForum:'; +import { + ADDON_MOD_FORUM_ALL_GROUPS, + ADDON_MOD_FORUM_ALL_PARTICIPANTS, + ADDON_MOD_FORUM_CHANGE_DISCUSSION_EVENT, + ADDON_MOD_FORUM_COMPONENT, + ADDON_MOD_FORUM_DISCUSSIONS_PER_PAGE, + ADDON_MOD_FORUM_MARK_READ_EVENT, + ADDON_MOD_FORUM_NEW_DISCUSSION_EVENT, + ADDON_MOD_FORUM_PREFERENCE_SORTORDER, + ADDON_MOD_FORUM_REPLY_DISCUSSION_EVENT, + AddonModForumSortorder, +} from '../constants'; declare module '@singletons/events' { @@ -41,10 +51,10 @@ declare module '@singletons/events' { * @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation */ export interface CoreEventsData { - [AddonModForumProvider.NEW_DISCUSSION_EVENT]: AddonModForumNewDiscussionData; - [AddonModForumProvider.REPLY_DISCUSSION_EVENT]: AddonModForumReplyDiscussionData; - [AddonModForumProvider.CHANGE_DISCUSSION_EVENT]: AddonModForumChangeDiscussionData; - [AddonModForumProvider.MARK_READ_EVENT]: AddonModForumMarkReadData; + [ADDON_MOD_FORUM_NEW_DISCUSSION_EVENT]: AddonModForumNewDiscussionData; + [ADDON_MOD_FORUM_REPLY_DISCUSSION_EVENT]: AddonModForumReplyDiscussionData; + [ADDON_MOD_FORUM_CHANGE_DISCUSSION_EVENT]: AddonModForumChangeDiscussionData; + [ADDON_MOD_FORUM_MARK_READ_EVENT]: AddonModForumMarkReadData; } } @@ -55,24 +65,7 @@ declare module '@singletons/events' { @Injectable({ providedIn: 'root' }) export class AddonModForumProvider { - static readonly COMPONENT = 'mmaModForum'; - static readonly DISCUSSIONS_PER_PAGE = 10; // Max of discussions per page. - static readonly NEW_DISCUSSION_EVENT = 'addon_mod_forum_new_discussion'; - static readonly REPLY_DISCUSSION_EVENT = 'addon_mod_forum_reply_discussion'; - static readonly CHANGE_DISCUSSION_EVENT = 'addon_mod_forum_change_discussion_status'; - static readonly MARK_READ_EVENT = 'addon_mod_forum_mark_read'; - static readonly LEAVING_POSTS_PAGE = 'addon_mod_forum_leaving_posts_page'; - - static readonly PREFERENCE_SORTORDER = 'forum_discussionlistsortorder'; - static readonly SORTORDER_LASTPOST_DESC = 1; - static readonly SORTORDER_LASTPOST_ASC = 2; - static readonly SORTORDER_CREATED_DESC = 3; - static readonly SORTORDER_CREATED_ASC = 4; - static readonly SORTORDER_REPLIES_DESC = 5; - static readonly SORTORDER_REPLIES_ASC = 6; - - static readonly ALL_PARTICIPANTS = -1; - static readonly ALL_GROUPS = -2; + protected static readonly ROOT_CACHE_KEY = 'mmaModForum:'; /** * Get cache key for can add discussion WS calls. @@ -93,7 +86,7 @@ export class AddonModForumProvider { * @returns Cache key. */ protected getCommonCanAddDiscussionCacheKey(forumId: number): string { - return ROOT_CACHE_KEY + 'canadddiscussion:' + forumId + ':'; + return AddonModForumProvider.ROOT_CACHE_KEY + 'canadddiscussion:' + forumId + ':'; } /** @@ -103,7 +96,7 @@ export class AddonModForumProvider { * @returns Cache key. */ protected getForumDataPrefixCacheKey(forumId: number): string { - return ROOT_CACHE_KEY + forumId; + return AddonModForumProvider.ROOT_CACHE_KEY + forumId; } /** @@ -136,7 +129,7 @@ export class AddonModForumProvider { * @returns Cache key. */ protected getForumDataCacheKey(courseId: number): string { - return ROOT_CACHE_KEY + 'forum:' + courseId; + return AddonModForumProvider.ROOT_CACHE_KEY + 'forum:' + courseId; } /** @@ -147,7 +140,7 @@ export class AddonModForumProvider { * @returns Cache key. */ protected getAccessInformationCacheKey(forumId: number): string { - return ROOT_CACHE_KEY + 'accessInformation:' + forumId; + return AddonModForumProvider.ROOT_CACHE_KEY + 'accessInformation:' + forumId; } /** @@ -158,7 +151,7 @@ export class AddonModForumProvider { * @returns Cache key. */ protected getDiscussionPostsCacheKey(discussionId: number): string { - return ROOT_CACHE_KEY + 'discussion:' + discussionId; + return AddonModForumProvider.ROOT_CACHE_KEY + 'discussion:' + discussionId; } /** @@ -168,7 +161,7 @@ export class AddonModForumProvider { * @returns Cache key. */ protected getDiscussionsListCommonCacheKey(forumId: number): string { - return ROOT_CACHE_KEY + 'discussions:' + forumId; + return AddonModForumProvider.ROOT_CACHE_KEY + 'discussions:' + forumId; } /** @@ -182,7 +175,7 @@ export class AddonModForumProvider { protected getDiscussionsListCacheKey(forumId: number, sortOrder: number, groupId?: number): string { let key = this.getDiscussionsListCommonCacheKey(forumId); - if (sortOrder != AddonModForumProvider.SORTORDER_LASTPOST_DESC) { + if (sortOrder !== AddonModForumSortorder.LASTPOST_DESC) { key += ':' + sortOrder; } if (groupId) { @@ -257,7 +250,7 @@ export class AddonModForumProvider { }; const preSets = { cacheKey: this.getCanAddDiscussionCacheKey(forumId, groupId), - component: AddonModForumProvider.COMPONENT, + component: ADDON_MOD_FORUM_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -292,7 +285,7 @@ export class AddonModForumProvider { * - cancreateattachment (boolean) */ canAddDiscussionToAll(forumId: number, options: CoreCourseCommonModWSOptions = {}): Promise { - return this.canAddDiscussion(forumId, AddonModForumProvider.ALL_PARTICIPANTS, options); + return this.canAddDiscussion(forumId, ADDON_MOD_FORUM_ALL_PARTICIPANTS, options); } /** @@ -394,9 +387,9 @@ export class AddonModForumProvider { // Format discussions. discussions.forEach((disc) => { - if (disc.groupid == AddonModForumProvider.ALL_PARTICIPANTS) { + if (disc.groupid == ADDON_MOD_FORUM_ALL_PARTICIPANTS) { disc.groupname = strAllParts; - } else if (disc.groupid == AddonModForumProvider.ALL_GROUPS) { + } else if (disc.groupid == ADDON_MOD_FORUM_ALL_GROUPS) { // Offline discussions only. disc.groupname = strAllGroups; } else { @@ -427,7 +420,7 @@ export class AddonModForumProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getForumDataCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, - component: AddonModForumProvider.COMPONENT, + component: ADDON_MOD_FORUM_COMPONENT, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), }; @@ -456,7 +449,7 @@ export class AddonModForumProvider { const preSets = { cacheKey: this.getDiscussionPostDataCacheKey(forumId, discussionId, postId), updateFrequency: CoreSite.FREQUENCY_USUALLY, - component: AddonModForumProvider.COMPONENT, + component: ADDON_MOD_FORUM_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -537,7 +530,7 @@ export class AddonModForumProvider { }; const preSets = { cacheKey: this.getAccessInformationCacheKey(forumId), - component: AddonModForumProvider.COMPONENT, + component: ADDON_MOD_FORUM_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -607,7 +600,7 @@ export class AddonModForumProvider { }; const preSets = { cacheKey: this.getDiscussionPostsCacheKey(discussionId), - component: AddonModForumProvider.COMPONENT, + component: ADDON_MOD_FORUM_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -684,7 +677,7 @@ export class AddonModForumProvider { const sortOrders = [ { label: 'addon.mod_forum.discussionlistsortbylastpostdesc', - value: AddonModForumProvider.SORTORDER_LASTPOST_DESC, + value: AddonModForumSortorder.LASTPOST_DESC, }, ]; @@ -692,23 +685,23 @@ export class AddonModForumProvider { sortOrders.push( { label: 'addon.mod_forum.discussionlistsortbylastpostasc', - value: AddonModForumProvider.SORTORDER_LASTPOST_ASC, + value: AddonModForumSortorder.LASTPOST_ASC, }, { label: 'addon.mod_forum.discussionlistsortbycreateddesc', - value: AddonModForumProvider.SORTORDER_CREATED_DESC, + value: AddonModForumSortorder.CREATED_DESC, }, { label: 'addon.mod_forum.discussionlistsortbycreatedasc', - value: AddonModForumProvider.SORTORDER_CREATED_ASC, + value: AddonModForumSortorder.CREATED_ASC, }, { label: 'addon.mod_forum.discussionlistsortbyrepliesdesc', - value: AddonModForumProvider.SORTORDER_REPLIES_DESC, + value: AddonModForumSortorder.REPLIES_DESC, }, { label: 'addon.mod_forum.discussionlistsortbyrepliesasc', - value: AddonModForumProvider.SORTORDER_REPLIES_ASC, + value: AddonModForumSortorder.REPLIES_ASC, }, ); } @@ -727,7 +720,7 @@ export class AddonModForumProvider { if (this.isDiscussionListSortingAvailable()) { const preferenceValue = await CoreUtils.ignoreErrors( - CoreUser.getUserPreference(AddonModForumProvider.PREFERENCE_SORTORDER), + CoreUser.getUserPreference(ADDON_MOD_FORUM_PREFERENCE_SORTORDER), ); sortOrderValue = preferenceValue ? parseInt(preferenceValue, 10) : null; @@ -750,7 +743,7 @@ export class AddonModForumProvider { forumId: number, options: AddonModForumGetDiscussionsOptions = {}, ): Promise<{ discussions: AddonModForumDiscussion[]; canLoadMore: boolean }> { - options.sortOrder = options.sortOrder || AddonModForumProvider.SORTORDER_LASTPOST_DESC; + options.sortOrder = options.sortOrder || AddonModForumSortorder.LASTPOST_DESC; options.page = options.page || 0; const site = await CoreSites.getSite(options.siteId); @@ -758,7 +751,7 @@ export class AddonModForumProvider { const params: AddonModForumGetForumDiscussionsPaginatedWSParams | AddonModForumGetForumDiscussionsWSParams = { forumid: forumId, page: options.page, - perpage: AddonModForumProvider.DISCUSSIONS_PER_PAGE, + perpage: ADDON_MOD_FORUM_DISCUSSIONS_PER_PAGE, }; if (site.wsAvailable('mod_forum_get_forum_discussions')) { @@ -767,7 +760,7 @@ export class AddonModForumProvider { (params as AddonModForumGetForumDiscussionsWSParams).sortorder = options.sortOrder; (params as AddonModForumGetForumDiscussionsWSParams).groupid = options.groupId; } else { - if (options.sortOrder !== AddonModForumProvider.SORTORDER_LASTPOST_DESC) { + if (options.sortOrder !== AddonModForumSortorder.LASTPOST_DESC) { throw new Error('Sorting not supported with the old WS method.'); } @@ -777,7 +770,7 @@ export class AddonModForumProvider { const preSets = { cacheKey: this.getDiscussionsListCacheKey(forumId, options.sortOrder), - component: AddonModForumProvider.COMPONENT, + component: ADDON_MOD_FORUM_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -795,7 +788,7 @@ export class AddonModForumProvider { if ( CoreNetwork.isOnline() || method !== 'mod_forum_get_forum_discussions' || - options.sortOrder !== AddonModForumProvider.SORTORDER_LASTPOST_DESC + options.sortOrder !== AddonModForumSortorder.LASTPOST_DESC ) { throw error; } @@ -803,7 +796,7 @@ export class AddonModForumProvider { const params: AddonModForumGetForumDiscussionsPaginatedWSParams = { forumid: forumId, page: options.page, - perpage: AddonModForumProvider.DISCUSSIONS_PER_PAGE, + perpage: ADDON_MOD_FORUM_DISCUSSIONS_PER_PAGE, sortby: 'timemodified', sortdirection: 'DESC', }; @@ -824,7 +817,7 @@ export class AddonModForumProvider { return { discussions: response.discussions, - canLoadMore: response.discussions.length >= AddonModForumProvider.DISCUSSIONS_PER_PAGE, + canLoadMore: response.discussions.length >= ADDON_MOD_FORUM_DISCUSSIONS_PER_PAGE, }; } @@ -930,7 +923,7 @@ export class AddonModForumProvider { }); if (this.isDiscussionListSortingAvailable()) { - promises.push(CoreUser.invalidateUserPreference(AddonModForumProvider.PREFERENCE_SORTORDER)); + promises.push(CoreUser.invalidateUserPreference(ADDON_MOD_FORUM_PREFERENCE_SORTORDER)); } return CoreUtils.allPromises(promises); @@ -1008,7 +1001,7 @@ export class AddonModForumProvider { return CoreCourseLogHelper.log( 'mod_forum_view_forum', params, - AddonModForumProvider.COMPONENT, + ADDON_MOD_FORUM_COMPONENT, id, siteId, ); @@ -1030,7 +1023,7 @@ export class AddonModForumProvider { return CoreCourseLogHelper.log( 'mod_forum_view_forum_discussion', params, - AddonModForumProvider.COMPONENT, + ADDON_MOD_FORUM_COMPONENT, forumId, siteId, ); diff --git a/src/addons/mod/forum/services/handlers/discussion-link.ts b/src/addons/mod/forum/services/handlers/discussion-link.ts index 4ca540b09..d35f86320 100644 --- a/src/addons/mod/forum/services/handlers/discussion-link.ts +++ b/src/addons/mod/forum/services/handlers/discussion-link.ts @@ -18,7 +18,7 @@ import { CoreContentLinksHandlerBase } from '@features/contentlinks/classes/base import { CoreContentLinksAction } from '@features/contentlinks/services/contentlinks-delegate'; import { CoreNavigator } from '@services/navigator'; import { makeSingleton } from '@singletons'; -import { AddonModForumModuleHandlerService } from './module'; +import { ADDON_MOD_FORUM_PAGE_NAME } from '../../constants'; /** * Handler to treat links to forum review. @@ -66,7 +66,7 @@ export class AddonModForumDiscussionLinkHandlerService extends CoreContentLinksH } await CoreNavigator.navigateToSitePath( - `${AddonModForumModuleHandlerService.PAGE_NAME}/discussion/${discussionId}`, + `${ADDON_MOD_FORUM_PAGE_NAME}/discussion/${discussionId}`, { siteId, params: pageParams }, ); }, diff --git a/src/addons/mod/forum/services/handlers/module.ts b/src/addons/mod/forum/services/handlers/module.ts index e6244665c..9335ce228 100644 --- a/src/addons/mod/forum/services/handlers/module.ts +++ b/src/addons/mod/forum/services/handlers/module.ts @@ -13,7 +13,7 @@ // limitations under the License. import { Injectable, Type } from '@angular/core'; -import { AddonModForum, AddonModForumProvider, AddonModForumTracking } from '../forum'; +import { AddonModForum, AddonModForumTracking } from '../forum'; import { makeSingleton, Translate } from '@singletons'; import { CoreEvents } from '@singletons/events'; import { CoreSites, CoreSitesReadingStrategy } from '@services/sites'; @@ -23,6 +23,7 @@ import { CoreModuleHandlerBase } from '@features/course/classes/module-base-hand import { CoreCourseModuleData } from '@features/course/services/course-helper'; import { CoreTextUtils } from '@services/utils/text'; import { CoreUser } from '@features/user/services/user'; +import { ADDON_MOD_FORUM_MARK_READ_EVENT, ADDON_MOD_FORUM_PAGE_NAME } from '../../constants'; /** * Handler to support forum modules. @@ -30,11 +31,9 @@ import { CoreUser } from '@features/user/services/user'; @Injectable({ providedIn: 'root' }) export class AddonModForumModuleHandlerService extends CoreModuleHandlerBase implements CoreCourseModuleHandler { - static readonly PAGE_NAME = 'mod_forum'; - name = 'AddonModForum'; modName = 'forum'; - protected pageName = AddonModForumModuleHandlerService.PAGE_NAME; + protected pageName = ADDON_MOD_FORUM_PAGE_NAME; supportedFeatures = { [CoreConstants.FEATURE_GROUPS]: true, @@ -88,7 +87,7 @@ export class AddonModForumModuleHandlerService extends CoreModuleHandlerBase imp } const event = CoreEvents.on( - AddonModForumProvider.MARK_READ_EVENT, + ADDON_MOD_FORUM_MARK_READ_EVENT, eventData => { if (eventData.courseId !== courseId || eventData.moduleId !== module.id) { return; diff --git a/src/addons/mod/forum/services/handlers/post-link.ts b/src/addons/mod/forum/services/handlers/post-link.ts index 8376524bc..c972ff703 100644 --- a/src/addons/mod/forum/services/handlers/post-link.ts +++ b/src/addons/mod/forum/services/handlers/post-link.ts @@ -20,7 +20,7 @@ import { CoreNavigator } from '@services/navigator'; import { CoreSitesReadingStrategy } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { makeSingleton } from '@singletons'; -import { AddonModForumModuleHandlerService } from './module'; +import { ADDON_MOD_FORUM_PAGE_NAME } from '../../constants'; /** * Content links handler for forum new discussion. @@ -54,7 +54,7 @@ export class AddonModForumPostLinkHandlerService extends CoreContentLinksHandler ); await CoreNavigator.navigateToSitePath( - `${AddonModForumModuleHandlerService.PAGE_NAME}/${module.course}/${module.id}/new/0`, + `${ADDON_MOD_FORUM_PAGE_NAME}/${module.course}/${module.id}/new/0`, { siteId, params: { forumId: module.instance } }, ); } finally { diff --git a/src/addons/mod/forum/services/handlers/prefetch.ts b/src/addons/mod/forum/services/handlers/prefetch.ts index 29124b40e..d9aa37500 100644 --- a/src/addons/mod/forum/services/handlers/prefetch.ts +++ b/src/addons/mod/forum/services/handlers/prefetch.ts @@ -14,7 +14,7 @@ import { Injectable } from '@angular/core'; import { CoreCourseActivityPrefetchHandlerBase } from '@features/course/classes/activity-prefetch-handler'; -import { AddonModForum, AddonModForumData, AddonModForumPost, AddonModForumProvider } from '../forum'; +import { AddonModForum, AddonModForumData, AddonModForumPost } from '../forum'; import { CoreSitesReadingStrategy } from '@services/sites'; import { CoreFilepool } from '@services/filepool'; import { CoreWSFile } from '@services/ws'; @@ -25,6 +25,7 @@ import { CoreUtils } from '@services/utils/utils'; import { AddonModForumSync, AddonModForumSyncResult } from '../forum-sync'; import { makeSingleton } from '@singletons'; import { CoreCourses } from '@features/courses/services/courses'; +import { ADDON_MOD_FORUM_COMPONENT } from '../../constants'; /** * Handler to prefetch forums. @@ -34,7 +35,7 @@ export class AddonModForumPrefetchHandlerService extends CoreCourseActivityPrefe name = 'AddonModForum'; modName = 'forum'; - component = AddonModForumProvider.COMPONENT; + component = ADDON_MOD_FORUM_COMPONENT; updatesNames = /^configuration$|^.*files$|^discussions$/; /** diff --git a/src/addons/mod/forum/services/handlers/push-click.ts b/src/addons/mod/forum/services/handlers/push-click.ts index d57275e23..34f9a9662 100644 --- a/src/addons/mod/forum/services/handlers/push-click.ts +++ b/src/addons/mod/forum/services/handlers/push-click.ts @@ -23,8 +23,8 @@ import { CoreUrlUtils } from '@services/utils/url'; import { CoreUtils } from '@services/utils/utils'; import { makeSingleton } from '@singletons'; -import { AddonModForumModuleHandlerService } from './module'; import { isSafeNumber } from '@/core/utils/types'; +import { ADDON_MOD_FORUM_PAGE_NAME } from '../../constants'; /** * Handler for forum push notifications clicks. @@ -80,7 +80,7 @@ export class AddonModForumPushClickHandlerService implements CorePushNotificatio ); await CoreNavigator.navigateToSitePath( - `${AddonModForumModuleHandlerService.PAGE_NAME}/discussion/${discussionId}`, + `${ADDON_MOD_FORUM_PAGE_NAME}/discussion/${discussionId}`, { siteId: notification.site, params: pageParams }, ); } From 8236f1c38b2790d64896b412cca303aad481ec83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Thu, 11 Jul 2024 22:41:46 +0200 Subject: [PATCH 11/26] MOBILE-4616 h5p: Move h5p constants to a file --- .../mod/h5pactivity/components/index/index.ts | 29 +++++----- src/addons/mod/h5pactivity/constants.ts | 33 +++++++++++ .../h5pactivity/h5pactivity-lazy.module.ts | 2 +- .../mod/h5pactivity/h5pactivity.module.ts | 7 ++- .../pages/attempt-results/attempt-results.ts | 4 +- .../pages/users-attempts/users-attempts.ts | 6 +- .../h5pactivity/services/h5pactivity-sync.ts | 14 +++-- .../mod/h5pactivity/services/h5pactivity.ts | 55 ++++++++----------- .../h5pactivity/services/handlers/module.ts | 5 +- .../h5pactivity/services/handlers/prefetch.ts | 21 ++++--- .../services/handlers/report-link.ts | 8 +-- 11 files changed, 109 insertions(+), 75 deletions(-) create mode 100644 src/addons/mod/h5pactivity/constants.ts diff --git a/src/addons/mod/h5pactivity/components/index/index.ts b/src/addons/mod/h5pactivity/components/index/index.ts index 4c1fc4335..542a2b366 100644 --- a/src/addons/mod/h5pactivity/components/index/index.ts +++ b/src/addons/mod/h5pactivity/components/index/index.ts @@ -35,21 +35,24 @@ import { AddonModH5PActivity, AddonModH5PActivityAccessInfo, AddonModH5PActivityData, - AddonModH5PActivityProvider, AddonModH5PActivityXAPIPostStateData, AddonModH5PActivityXAPIStateData, AddonModH5PActivityXAPIStatementsData, - MOD_H5PACTIVITY_STATE_ID, } from '../../services/h5pactivity'; import { AddonModH5PActivitySync, - AddonModH5PActivitySyncProvider, AddonModH5PActivitySyncResult, } from '../../services/h5pactivity-sync'; import { CoreFileHelper } from '@services/file-helper'; -import { AddonModH5PActivityModuleHandlerService } from '../../services/handlers/module'; import { CoreTextUtils } from '@services/utils/text'; import { CoreUtils } from '@services/utils/utils'; +import { + ADDON_MOD_H5PACTIVITY_AUTO_SYNCED, + ADDON_MOD_H5PACTIVITY_COMPONENT, + ADDON_MOD_H5PACTIVITY_PAGE_NAME, + ADDON_MOD_H5PACTIVITY_STATE_ID, + ADDON_MOD_H5PACTIVITY_TRACK_COMPONENT, +} from '../../constants'; /** * Component that displays an H5P activity entry page. @@ -62,7 +65,7 @@ export class AddonModH5PActivityIndexComponent extends CoreCourseModuleMainActiv @Output() onActivityFinish = new EventEmitter(); - component = AddonModH5PActivityProvider.COMPONENT; + component = ADDON_MOD_H5PACTIVITY_COMPONENT; pluginName = 'h5pactivity'; h5pActivity?: AddonModH5PActivityData; // The H5P activity object. @@ -90,7 +93,7 @@ export class AddonModH5PActivityIndexComponent extends CoreCourseModuleMainActiv contentState?: string; protected fetchContentDefaultError = 'addon.mod_h5pactivity.errorgetactivity'; - protected syncEventName = AddonModH5PActivitySyncProvider.AUTO_SYNCED; + protected syncEventName = ADDON_MOD_H5PACTIVITY_AUTO_SYNCED; protected site: CoreSite; protected observer?: CoreEventObserver; protected messageListenerFunction: (event: MessageEvent) => Promise; @@ -147,7 +150,7 @@ export class AddonModH5PActivityIndexComponent extends CoreCourseModuleMainActiv await this.loadContentState(); // Loading the state requires the access info. - this.trackComponent = this.accessInfo?.cansubmit ? AddonModH5PActivityProvider.TRACK_COMPONENT : ''; + this.trackComponent = this.accessInfo?.cansubmit ? ADDON_MOD_H5PACTIVITY_TRACK_COMPONENT : ''; this.canViewAllAttempts = !!this.h5pActivity.enabletracking && !!this.accessInfo?.canreviewattempts && AddonModH5PActivity.canGetUsersAttemptsInSite(); @@ -250,11 +253,11 @@ export class AddonModH5PActivityIndexComponent extends CoreCourseModuleMainActiv this.saveFreq = this.h5pActivity.savestatefreq; const contentState = await CoreXAPI.getState( - AddonModH5PActivityProvider.TRACK_COMPONENT, + ADDON_MOD_H5PACTIVITY_TRACK_COMPONENT, this.h5pActivity.context, - MOD_H5PACTIVITY_STATE_ID, + ADDON_MOD_H5PACTIVITY_STATE_ID, { - appComponent: AddonModH5PActivityProvider.COMPONENT, + appComponent: ADDON_MOD_H5PACTIVITY_COMPONENT, appComponentId: this.h5pActivity.coursemodule, readingStrategy: CoreSitesReadingStrategy.PREFER_NETWORK, }, @@ -464,7 +467,7 @@ export class AddonModH5PActivityIndexComponent extends CoreCourseModuleMainActiv try { await CoreNavigator.navigateToSitePath( - `${AddonModH5PActivityModuleHandlerService.PAGE_NAME}/${this.courseId}/${this.module.id}/userattempts/${userId}`, + `${ADDON_MOD_H5PACTIVITY_PAGE_NAME}/${this.courseId}/${this.module.id}/userattempts/${userId}`, ); } finally { this.isOpeningPage = false; @@ -479,7 +482,7 @@ export class AddonModH5PActivityIndexComponent extends CoreCourseModuleMainActiv try { await CoreNavigator.navigateToSitePath( - `${AddonModH5PActivityModuleHandlerService.PAGE_NAME}/${this.courseId}/${this.module.id}/users`, + `${ADDON_MOD_H5PACTIVITY_PAGE_NAME}/${this.courseId}/${this.module.id}/users`, ); } finally { this.isOpeningPage = false; @@ -696,7 +699,7 @@ export class AddonModH5PActivityIndexComponent extends CoreCourseModuleMainActiv return; } - await CoreUtils.ignoreErrors(CoreXAPIOffline.deleteStates(AddonModH5PActivityProvider.TRACK_COMPONENT, { + await CoreUtils.ignoreErrors(CoreXAPIOffline.deleteStates(ADDON_MOD_H5PACTIVITY_TRACK_COMPONENT, { itemId: this.h5pActivity.context, })); } diff --git a/src/addons/mod/h5pactivity/constants.ts b/src/addons/mod/h5pactivity/constants.ts new file mode 100644 index 000000000..fa0dc2d06 --- /dev/null +++ b/src/addons/mod/h5pactivity/constants.ts @@ -0,0 +1,33 @@ +// (C) Copyright 2015 Moodle Pty Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export const ADDON_MOD_H5PACTIVITY_COMPONENT = 'mmaModH5PActivity'; + +export const ADDON_MOD_H5PACTIVITY_PAGE_NAME = 'mod_h5pactivity'; + +export const ADDON_MOD_H5PACTIVITY_TRACK_COMPONENT = 'mod_h5pactivity'; // Component for tracking. +export const ADDON_MOD_H5PACTIVITY_USERS_PER_PAGE = 20; + +// Grade type constants. +export const enum AddonModH5PActivityGradeMethod { + GRADEMANUAL = 0, // No automatic grading using attempt results. + GRADEHIGHESTATTEMPT = 1, // Use highest attempt results for grading. + GRADEAVERAGEATTEMPT = 2, // Use average attempt results for grading. + GRADELASTATTEMPT = 3, // Use last attempt results for grading. + GRADEFIRSTATTEMPT = 4, // Use first attempt results for grading. +} + +export const ADDON_MOD_H5PACTIVITY_STATE_ID = 'state'; + +export const ADDON_MOD_H5PACTIVITY_AUTO_SYNCED = 'addon_mod_h5pactivity_autom_synced'; diff --git a/src/addons/mod/h5pactivity/h5pactivity-lazy.module.ts b/src/addons/mod/h5pactivity/h5pactivity-lazy.module.ts index fe4312444..a4c5c2aef 100644 --- a/src/addons/mod/h5pactivity/h5pactivity-lazy.module.ts +++ b/src/addons/mod/h5pactivity/h5pactivity-lazy.module.ts @@ -56,4 +56,4 @@ const routes: Routes = [ AddonModH5PActivityUsersAttemptsPage, ], }) -export class AddonModH5PActivityLazyModule {} +export default class AddonModH5PActivityLazyModule {} diff --git a/src/addons/mod/h5pactivity/h5pactivity.module.ts b/src/addons/mod/h5pactivity/h5pactivity.module.ts index a5a411de0..efd806e28 100644 --- a/src/addons/mod/h5pactivity/h5pactivity.module.ts +++ b/src/addons/mod/h5pactivity/h5pactivity.module.ts @@ -20,15 +20,16 @@ import { CoreCourseModulePrefetchDelegate } from '@features/course/services/modu import { CoreMainMenuTabRoutingModule } from '@features/mainmenu/mainmenu-tab-routing.module'; import { CoreCronDelegate } from '@services/cron'; import { AddonModH5PActivityIndexLinkHandler } from './services/handlers/index-link'; -import { AddonModH5PActivityModuleHandler, AddonModH5PActivityModuleHandlerService } from './services/handlers/module'; +import { AddonModH5PActivityModuleHandler } from './services/handlers/module'; import { AddonModH5PActivityPrefetchHandler } from './services/handlers/prefetch'; import { AddonModH5PActivityReportLinkHandler } from './services/handlers/report-link'; import { AddonModH5PActivitySyncCronHandler } from './services/handlers/sync-cron'; +import { ADDON_MOD_H5PACTIVITY_PAGE_NAME } from './constants'; const routes: Routes = [ { - path: AddonModH5PActivityModuleHandlerService.PAGE_NAME, - loadChildren: () => import('./h5pactivity-lazy.module').then(m => m.AddonModH5PActivityLazyModule), + path: ADDON_MOD_H5PACTIVITY_PAGE_NAME, + loadChildren: () => import('./h5pactivity-lazy.module'), }, ]; diff --git a/src/addons/mod/h5pactivity/pages/attempt-results/attempt-results.ts b/src/addons/mod/h5pactivity/pages/attempt-results/attempt-results.ts index 6e43c7092..f10fce516 100644 --- a/src/addons/mod/h5pactivity/pages/attempt-results/attempt-results.ts +++ b/src/addons/mod/h5pactivity/pages/attempt-results/attempt-results.ts @@ -20,12 +20,12 @@ import { CoreDomUtils } from '@services/utils/dom'; import { CoreUtils } from '@services/utils/utils'; import { AddonModH5PActivity, - AddonModH5PActivityProvider, AddonModH5PActivityData, AddonModH5PActivityAttemptResults, } from '../../services/h5pactivity'; import { CoreTime } from '@singletons/time'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; +import { ADDON_MOD_H5PACTIVITY_COMPONENT } from '../../constants'; /** * Page that displays results of an attempt. @@ -41,7 +41,7 @@ export class AddonModH5PActivityAttemptResultsPage implements OnInit { h5pActivity?: AddonModH5PActivityData; attempt?: AddonModH5PActivityAttemptResults; user?: CoreUserProfile; - component = AddonModH5PActivityProvider.COMPONENT; + component = ADDON_MOD_H5PACTIVITY_COMPONENT; courseId!: number; cmId!: number; diff --git a/src/addons/mod/h5pactivity/pages/users-attempts/users-attempts.ts b/src/addons/mod/h5pactivity/pages/users-attempts/users-attempts.ts index f9b2369cb..6e1d0bf85 100644 --- a/src/addons/mod/h5pactivity/pages/users-attempts/users-attempts.ts +++ b/src/addons/mod/h5pactivity/pages/users-attempts/users-attempts.ts @@ -21,11 +21,11 @@ import { CoreUtils } from '@services/utils/utils'; import { AddonModH5PActivity, AddonModH5PActivityData, - AddonModH5PActivityProvider, AddonModH5PActivityUserAttempts, } from '../../services/h5pactivity'; import { CoreTime } from '@singletons/time'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; +import { AddonModH5PActivityGradeMethod } from '../../constants'; /** * Page that displays all users that can attempt an H5P activity. @@ -164,9 +164,9 @@ export class AddonModH5PActivityUsersAttemptsPage implements OnInit { user.user = await CoreUser.getProfile(user.userid, this.courseId, true); // Calculate the score of the user. - if (h5pActivity.grademethod === AddonModH5PActivityProvider.GRADEMANUAL) { + if (h5pActivity.grademethod === AddonModH5PActivityGradeMethod.GRADEMANUAL) { // No score. - } else if (h5pActivity.grademethod === AddonModH5PActivityProvider.GRADEAVERAGEATTEMPT) { + } else if (h5pActivity.grademethod === AddonModH5PActivityGradeMethod.GRADEAVERAGEATTEMPT) { if (user.attempts.length) { // Calculate the average. const sumScores = user.attempts.reduce((sumScores, attempt) => diff --git a/src/addons/mod/h5pactivity/services/h5pactivity-sync.ts b/src/addons/mod/h5pactivity/services/h5pactivity-sync.ts index d9132942c..dc822ba76 100644 --- a/src/addons/mod/h5pactivity/services/h5pactivity-sync.ts +++ b/src/addons/mod/h5pactivity/services/h5pactivity-sync.ts @@ -29,7 +29,6 @@ import { AddonModH5PActivity, AddonModH5PActivityAttempt, AddonModH5PActivityData, - AddonModH5PActivityProvider, } from './h5pactivity'; import { CoreXAPIStateDBRecord, CoreXAPIStatementDBRecord } from '@features/xapi/services/database/xapi'; import { CoreTextUtils } from '@services/utils/text'; @@ -37,6 +36,11 @@ import { CoreXAPIIRI } from '@features/xapi/classes/iri'; import { CoreXAPIItemAgent } from '@features/xapi/classes/item-agent'; import { CoreWSError } from '@classes/errors/wserror'; import { CoreArray } from '@singletons/array'; +import { + ADDON_MOD_H5PACTIVITY_AUTO_SYNCED, + ADDON_MOD_H5PACTIVITY_COMPONENT, + ADDON_MOD_H5PACTIVITY_TRACK_COMPONENT, +} from '../constants'; /** * Service to sync H5P activities. @@ -44,8 +48,6 @@ import { CoreArray } from '@singletons/array'; @Injectable({ providedIn: 'root' }) export class AddonModH5PActivitySyncProvider extends CoreCourseActivitySyncBaseProvider { - static readonly AUTO_SYNCED = 'addon_mod_h5pactivity_autom_synced'; - protected componentTranslatableString = 'h5pactivity'; constructor() { @@ -86,7 +88,7 @@ export class AddonModH5PActivitySyncProvider extends CoreCourseActivitySyncBaseP if (result?.updated) { // Sync successful, send event. - CoreEvents.trigger(AddonModH5PActivitySyncProvider.AUTO_SYNCED, { + CoreEvents.trigger(ADDON_MOD_H5PACTIVITY_AUTO_SYNCED, { contextId, warnings: result.warnings, }, siteId); @@ -161,7 +163,7 @@ export class AddonModH5PActivitySyncProvider extends CoreCourseActivitySyncBaseP const deleteOfflineData = async (): Promise => { await Promise.all([ statements.length ? CoreXAPIOffline.deleteStatementsForContext(contextId, siteId) : undefined, - states.length ? CoreXAPIOffline.deleteStates(AddonModH5PActivityProvider.TRACK_COMPONENT, { + states.length ? CoreXAPIOffline.deleteStates(ADDON_MOD_H5PACTIVITY_TRACK_COMPONENT, { itemId: contextId, siteId, }) : undefined, @@ -207,7 +209,7 @@ export class AddonModH5PActivitySyncProvider extends CoreCourseActivitySyncBaseP // Sync offline logs. await CoreUtils.ignoreErrors( - CoreCourseLogHelper.syncActivity(AddonModH5PActivityProvider.COMPONENT, h5pActivity.id, siteId), + CoreCourseLogHelper.syncActivity(ADDON_MOD_H5PACTIVITY_COMPONENT, h5pActivity.id, siteId), ); const results = await Promise.all([ diff --git a/src/addons/mod/h5pactivity/services/h5pactivity.ts b/src/addons/mod/h5pactivity/services/h5pactivity.ts index 561a5e37b..753ffd994 100644 --- a/src/addons/mod/h5pactivity/services/h5pactivity.ts +++ b/src/addons/mod/h5pactivity/services/h5pactivity.ts @@ -25,13 +25,15 @@ import { CoreCourseCommonModWSOptions } from '@features/course/services/course'; import { makeSingleton, Translate } from '@singletons/index'; import { CoreWSError } from '@classes/errors/wserror'; import { CoreError } from '@classes/errors/error'; -import { AddonModH5PActivityAutoSyncData, AddonModH5PActivitySyncProvider } from './h5pactivity-sync'; +import { AddonModH5PActivityAutoSyncData } from './h5pactivity-sync'; import { CoreTime } from '@singletons/time'; import { CoreSiteWSPreSets } from '@classes/sites/authenticated-site'; - -export const MOD_H5PACTIVITY_STATE_ID = 'state'; - -const ROOT_CACHE_KEY = 'mmaModH5PActivity:'; +import { + ADDON_MOD_H5PACTIVITY_AUTO_SYNCED, + ADDON_MOD_H5PACTIVITY_COMPONENT, + ADDON_MOD_H5PACTIVITY_USERS_PER_PAGE, + AddonModH5PActivityGradeMethod, +} from '../constants'; /** * Service that provides some features for H5P activity. @@ -39,16 +41,7 @@ const ROOT_CACHE_KEY = 'mmaModH5PActivity:'; @Injectable({ providedIn: 'root' }) export class AddonModH5PActivityProvider { - static readonly COMPONENT = 'mmaModH5PActivity'; - static readonly TRACK_COMPONENT = 'mod_h5pactivity'; // Component for tracking. - static readonly USERS_PER_PAGE = 20; - - // Grade type constants. - static readonly GRADEMANUAL = 0; // No automathic grading using attempt results. - static readonly GRADEHIGHESTATTEMPT = 1; // Use highest attempt results for grading. - static readonly GRADEAVERAGEATTEMPT = 2; // Use average attempt results for grading. - static readonly GRADELASTATTEMPT = 3; // Use last attempt results for grading. - static readonly GRADEFIRSTATTEMPT = 4; // Use first attempt results for grading. + protected static readonly ROOT_CACHE_KEY = 'mmaModH5PActivity:'; /** * Check if a certain site allows viewing list of users and their attempts. @@ -151,7 +144,7 @@ export class AddonModH5PActivityProvider { * @returns Cache key. */ protected getAccessInformationCacheKey(id: number): string { - return ROOT_CACHE_KEY + 'accessInfo:' + id; + return AddonModH5PActivityProvider.ROOT_CACHE_KEY + 'accessInfo:' + id; } /** @@ -170,7 +163,7 @@ export class AddonModH5PActivityProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getAccessInformationCacheKey(id), updateFrequency: CoreSite.FREQUENCY_OFTEN, - component: AddonModH5PActivityProvider.COMPONENT, + component: ADDON_MOD_H5PACTIVITY_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -259,7 +252,7 @@ export class AddonModH5PActivityProvider { ): Promise<{users: AddonModH5PActivityUserAttempts[]; canLoadMore: boolean}> { options = options || {}; options.page = options.page || 0; - options.perPage = options.perPage ?? AddonModH5PActivityProvider.USERS_PER_PAGE; + options.perPage = options.perPage ?? ADDON_MOD_H5PACTIVITY_USERS_PER_PAGE; const site = await CoreSites.getSite(options.siteId); @@ -274,7 +267,7 @@ export class AddonModH5PActivityProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getUsersAttemptsCacheKey(id, options), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, - component: AddonModH5PActivityProvider.COMPONENT, + component: ADDON_MOD_H5PACTIVITY_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -320,7 +313,7 @@ export class AddonModH5PActivityProvider { * @returns Cache key. */ protected getUsersAttemptsCommonCacheKey(id: number): string { - return ROOT_CACHE_KEY + 'userAttempts:' + id; + return AddonModH5PActivityProvider.ROOT_CACHE_KEY + 'userAttempts:' + id; } /** @@ -341,7 +334,7 @@ export class AddonModH5PActivityProvider { * @returns Cache key. */ protected getAttemptResultsCommonCacheKey(id: number): string { - return ROOT_CACHE_KEY + 'results:' + id; + return AddonModH5PActivityProvider.ROOT_CACHE_KEY + 'results:' + id; } /** @@ -370,7 +363,7 @@ export class AddonModH5PActivityProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getAttemptResultsCacheKey(id, params.attemptids), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, - component: AddonModH5PActivityProvider.COMPONENT, + component: ADDON_MOD_H5PACTIVITY_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -435,7 +428,7 @@ export class AddonModH5PActivityProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getAttemptResultsCommonCacheKey(id), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, - component: AddonModH5PActivityProvider.COMPONENT, + component: ADDON_MOD_H5PACTIVITY_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -491,7 +484,7 @@ export class AddonModH5PActivityProvider { * @returns Cache key. */ protected getH5PActivityDataCacheKey(courseId: number): string { - return ROOT_CACHE_KEY + 'h5pactivity:' + courseId; + return AddonModH5PActivityProvider.ROOT_CACHE_KEY + 'h5pactivity:' + courseId; } /** @@ -518,7 +511,7 @@ export class AddonModH5PActivityProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getH5PActivityDataCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, - component: AddonModH5PActivityProvider.COMPONENT, + component: ADDON_MOD_H5PACTIVITY_COMPONENT, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -598,7 +591,7 @@ export class AddonModH5PActivityProvider { * @returns Cache key. */ protected getUserAttemptsCommonCacheKey(id: number): string { - return ROOT_CACHE_KEY + 'attempts:' + id; + return AddonModH5PActivityProvider.ROOT_CACHE_KEY + 'attempts:' + id; } /** @@ -625,7 +618,7 @@ export class AddonModH5PActivityProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getUserAttemptsCacheKey(id, params.userids), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, - component: AddonModH5PActivityProvider.COMPONENT, + component: ADDON_MOD_H5PACTIVITY_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -788,7 +781,7 @@ export class AddonModH5PActivityProvider { return CoreCourseLogHelper.log( 'mod_h5pactivity_view_h5pactivity', params, - AddonModH5PActivityProvider.COMPONENT, + ADDON_MOD_H5PACTIVITY_COMPONENT, id, siteId, ); @@ -818,7 +811,7 @@ export class AddonModH5PActivityProvider { return CoreCourseLogHelper.log( 'mod_h5pactivity_log_report_viewed', params, - AddonModH5PActivityProvider.COMPONENT, + ADDON_MOD_H5PACTIVITY_COMPONENT, id, site.getId(), ); @@ -842,7 +835,7 @@ export type AddonModH5PActivityWSData = { grade?: number; // The maximum grade for submission. displayoptions: number; // H5P Button display options. enabletracking: number; // Enable xAPI tracking. - grademethod: number; // Which H5P attempt is used for grading. + grademethod: AddonModH5PActivityGradeMethod; // Which H5P attempt is used for grading. contenthash?: string; // Sha1 hash of file content. coursemodule: number; // Coursemodule. context: number; // Context ID. @@ -1151,7 +1144,7 @@ declare module '@singletons/events' { * @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation */ export interface CoreEventsData { - [AddonModH5PActivitySyncProvider.AUTO_SYNCED]: AddonModH5PActivityAutoSyncData; + [ADDON_MOD_H5PACTIVITY_AUTO_SYNCED]: AddonModH5PActivityAutoSyncData; } } diff --git a/src/addons/mod/h5pactivity/services/handlers/module.ts b/src/addons/mod/h5pactivity/services/handlers/module.ts index 1470169cd..1c09f274c 100644 --- a/src/addons/mod/h5pactivity/services/handlers/module.ts +++ b/src/addons/mod/h5pactivity/services/handlers/module.ts @@ -18,6 +18,7 @@ import { CoreModuleHandlerBase } from '@features/course/classes/module-base-hand import { CoreCourseModuleHandler } from '@features/course/services/module-delegate'; import { makeSingleton } from '@singletons'; import { AddonModH5PActivity } from '../h5pactivity'; +import { ADDON_MOD_H5PACTIVITY_PAGE_NAME } from '../../constants'; /** * Handler to support H5P activities. @@ -25,11 +26,9 @@ import { AddonModH5PActivity } from '../h5pactivity'; @Injectable({ providedIn: 'root' }) export class AddonModH5PActivityModuleHandlerService extends CoreModuleHandlerBase implements CoreCourseModuleHandler { - static readonly PAGE_NAME = 'mod_h5pactivity'; - name = 'AddonModH5PActivity'; modName = 'h5pactivity'; - protected pageName = AddonModH5PActivityModuleHandlerService.PAGE_NAME; + protected pageName = ADDON_MOD_H5PACTIVITY_PAGE_NAME; supportedFeatures = { [CoreConstants.FEATURE_GROUPS]: true, diff --git a/src/addons/mod/h5pactivity/services/handlers/prefetch.ts b/src/addons/mod/h5pactivity/services/handlers/prefetch.ts index 97a25f59b..9463f41cf 100644 --- a/src/addons/mod/h5pactivity/services/handlers/prefetch.ts +++ b/src/addons/mod/h5pactivity/services/handlers/prefetch.ts @@ -32,9 +32,12 @@ import { AddonModH5PActivity, AddonModH5PActivityAccessInfo, AddonModH5PActivityData, - AddonModH5PActivityProvider, - MOD_H5PACTIVITY_STATE_ID, } from '../h5pactivity'; +import { + ADDON_MOD_H5PACTIVITY_COMPONENT, + ADDON_MOD_H5PACTIVITY_STATE_ID, + ADDON_MOD_H5PACTIVITY_TRACK_COMPONENT, +} from '../../constants'; /** * Handler to prefetch h5p activity. @@ -44,7 +47,7 @@ export class AddonModH5PActivityPrefetchHandlerService extends CoreCourseActivit name = 'AddonModH5PActivity'; modName = 'h5pactivity'; - component = AddonModH5PActivityProvider.COMPONENT; + component = ADDON_MOD_H5PACTIVITY_COMPONENT; updatesNames = /^configuration$|^.*files$|^tracks$|^usertracks$/; /** @@ -113,7 +116,7 @@ export class AddonModH5PActivityPrefetchHandlerService extends CoreCourseActivit await Promise.all([ this.prefetchWSData(h5pActivity, siteId), - CoreFilepool.addFilesToQueue(siteId, introFiles, AddonModH5PActivityProvider.COMPONENT, module.id), + CoreFilepool.addFilesToQueue(siteId, introFiles, ADDON_MOD_H5PACTIVITY_COMPONENT, module.id), this.prefetchMainFile(module, h5pActivity, siteId), CoreH5P.getCustomCssSrc(siteId), ]); @@ -146,14 +149,14 @@ export class AddonModH5PActivityPrefetchHandlerService extends CoreCourseActivit const fileState = await CoreFilepool.getFileStateByUrl(siteId, CoreFileHelper.getFileUrl(deployedFile)); if (fileState !== DownloadStatus.DOWNLOADED) { - await CoreUtils.ignoreErrors(CoreXAPIOffline.deleteStates(AddonModH5PActivityProvider.TRACK_COMPONENT, { + await CoreUtils.ignoreErrors(CoreXAPIOffline.deleteStates(ADDON_MOD_H5PACTIVITY_TRACK_COMPONENT, { itemId: h5pActivity.context, siteId, })); } } - await CoreFilepool.addFilesToQueue(siteId, [deployedFile], AddonModH5PActivityProvider.COMPONENT, module.id); + await CoreFilepool.addFilesToQueue(siteId, [deployedFile], ADDON_MOD_H5PACTIVITY_COMPONENT, module.id); } /** @@ -239,11 +242,11 @@ export class AddonModH5PActivityPrefetchHandlerService extends CoreCourseActivit } await CoreXAPI.getStateFromServer( - AddonModH5PActivityProvider.TRACK_COMPONENT, + ADDON_MOD_H5PACTIVITY_TRACK_COMPONENT, h5pActivity.context, - MOD_H5PACTIVITY_STATE_ID, + ADDON_MOD_H5PACTIVITY_STATE_ID, { - appComponent: AddonModH5PActivityProvider.COMPONENT, + appComponent: ADDON_MOD_H5PACTIVITY_COMPONENT, appComponentId: h5pActivity.coursemodule, readingStrategy: CoreSitesReadingStrategy.ONLY_NETWORK, siteId, diff --git a/src/addons/mod/h5pactivity/services/handlers/report-link.ts b/src/addons/mod/h5pactivity/services/handlers/report-link.ts index a2dc36862..c92418b90 100644 --- a/src/addons/mod/h5pactivity/services/handlers/report-link.ts +++ b/src/addons/mod/h5pactivity/services/handlers/report-link.ts @@ -23,7 +23,7 @@ import { CoreDomUtils } from '@services/utils/dom'; import { CoreUtils } from '@services/utils/utils'; import { makeSingleton } from '@singletons'; import { AddonModH5PActivity } from '../h5pactivity'; -import { AddonModH5PActivityModuleHandlerService } from './module'; +import { ADDON_MOD_H5PACTIVITY_PAGE_NAME } from '../../constants'; /** * Handler to treat links to H5P activity report. @@ -88,7 +88,7 @@ export class AddonModH5PActivityReportLinkHandlerService extends CoreContentLink * @param siteId Site ID. */ protected async openAttemptResults(cmId: number, attemptId: number, courseId: number, siteId: string): Promise { - const path = AddonModH5PActivityModuleHandlerService.PAGE_NAME + `/${courseId}/${cmId}/attemptresults/${attemptId}`; + const path = ADDON_MOD_H5PACTIVITY_PAGE_NAME + `/${courseId}/${cmId}/attemptresults/${attemptId}`; await CoreNavigator.navigateToSitePath(path, { siteId, @@ -125,9 +125,9 @@ export class AddonModH5PActivityReportLinkHandlerService extends CoreContentLink let path: string; if (canViewAllAttempts) { - path = `${AddonModH5PActivityModuleHandlerService.PAGE_NAME}/${courseId}/${cmId}/users`; + path = `${ADDON_MOD_H5PACTIVITY_PAGE_NAME}/${courseId}/${cmId}/users`; } else { - path = `${AddonModH5PActivityModuleHandlerService.PAGE_NAME}/${courseId}/${cmId}/userattempts/${userId}`; + path = `${ADDON_MOD_H5PACTIVITY_PAGE_NAME}/${courseId}/${cmId}/userattempts/${userId}`; } CoreNavigator.navigateToSitePath(path, { From 70507ce604038b68c924e9df83a88aa067d762b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Thu, 11 Jul 2024 22:42:02 +0200 Subject: [PATCH 12/26] MOBILE-4616 imscp: Move imscp constants to a file --- src/addons/mod/imscp/components/index/index.ts | 5 +++-- src/addons/mod/imscp/constants.ts | 16 ++++++++++++++++ src/addons/mod/imscp/imscp-lazy.module.ts | 2 +- src/addons/mod/imscp/imscp.module.ts | 7 ++++--- .../mod/imscp/services/handlers/module.ts | 5 ++--- .../mod/imscp/services/handlers/prefetch.ts | 5 +++-- src/addons/mod/imscp/services/imscp.ts | 17 ++++++++--------- 7 files changed, 37 insertions(+), 20 deletions(-) create mode 100644 src/addons/mod/imscp/constants.ts diff --git a/src/addons/mod/imscp/components/index/index.ts b/src/addons/mod/imscp/components/index/index.ts index 29e111c8a..9cd2303af 100644 --- a/src/addons/mod/imscp/components/index/index.ts +++ b/src/addons/mod/imscp/components/index/index.ts @@ -17,8 +17,9 @@ import { CoreCourseModuleMainResourceComponent } from '@features/course/classes/ import { CoreCourseContentsPage } from '@features/course/pages/contents/contents'; import { CoreCourse } from '@features/course/services/course'; import { CoreNavigator } from '@services/navigator'; -import { AddonModImscpProvider, AddonModImscp, AddonModImscpTocItem } from '../../services/imscp'; +import { AddonModImscp, AddonModImscpTocItem } from '../../services/imscp'; import { CoreUtils } from '@services/utils/utils'; +import { ADDON_MOD_IMSCP_COMPONENT } from '../../constants'; /** * Component that displays a IMSCP. @@ -30,7 +31,7 @@ import { CoreUtils } from '@services/utils/utils'; }) export class AddonModImscpIndexComponent extends CoreCourseModuleMainResourceComponent implements OnInit { - component = AddonModImscpProvider.COMPONENT; + component = ADDON_MOD_IMSCP_COMPONENT; pluginName = 'imscp'; items: AddonModImscpTocItem[] = []; diff --git a/src/addons/mod/imscp/constants.ts b/src/addons/mod/imscp/constants.ts new file mode 100644 index 000000000..a2c990326 --- /dev/null +++ b/src/addons/mod/imscp/constants.ts @@ -0,0 +1,16 @@ +// (C) Copyright 2015 Moodle Pty Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export const ADDON_MOD_IMSCP_COMPONENT = 'mmaModImscp'; +export const ADDON_MOD_IMSCP_PAGE_NAME = 'mod_imscp'; diff --git a/src/addons/mod/imscp/imscp-lazy.module.ts b/src/addons/mod/imscp/imscp-lazy.module.ts index 1ef464bb7..1bcde4c27 100644 --- a/src/addons/mod/imscp/imscp-lazy.module.ts +++ b/src/addons/mod/imscp/imscp-lazy.module.ts @@ -42,4 +42,4 @@ const routes: Routes = [ AddonModImscpViewPage, ], }) -export class AddonModImscpLazyModule {} +export default class AddonModImscpLazyModule {} diff --git a/src/addons/mod/imscp/imscp.module.ts b/src/addons/mod/imscp/imscp.module.ts index 6014981a1..83ce09f8b 100644 --- a/src/addons/mod/imscp/imscp.module.ts +++ b/src/addons/mod/imscp/imscp.module.ts @@ -21,14 +21,15 @@ import { CoreMainMenuTabRoutingModule } from '@features/mainmenu/mainmenu-tab-ro import { CorePluginFileDelegate } from '@services/plugin-file-delegate'; import { AddonModImscpIndexLinkHandler } from './services/handlers/index-link'; import { AddonModImscpListLinkHandler } from './services/handlers/list-link'; -import { AddonModImscpModuleHandler, AddonModImscpModuleHandlerService } from './services/handlers/module'; +import { AddonModImscpModuleHandler } from './services/handlers/module'; import { AddonModImscpPluginFileHandler } from './services/handlers/pluginfile'; import { AddonModImscpPrefetchHandler } from './services/handlers/prefetch'; +import { ADDON_MOD_IMSCP_PAGE_NAME } from './constants'; const routes: Routes = [ { - path: AddonModImscpModuleHandlerService.PAGE_NAME, - loadChildren: () => import('./imscp-lazy.module').then(m => m.AddonModImscpLazyModule), + path: ADDON_MOD_IMSCP_PAGE_NAME, + loadChildren: () => import('./imscp-lazy.module'), }, ]; diff --git a/src/addons/mod/imscp/services/handlers/module.ts b/src/addons/mod/imscp/services/handlers/module.ts index 180381380..e328ba0ec 100644 --- a/src/addons/mod/imscp/services/handlers/module.ts +++ b/src/addons/mod/imscp/services/handlers/module.ts @@ -18,6 +18,7 @@ import { CoreModuleHandlerBase } from '@features/course/classes/module-base-hand import { CoreCourseModuleHandler } from '@features/course/services/module-delegate'; import { makeSingleton } from '@singletons'; import { AddonModImscp } from '../imscp'; +import { ADDON_MOD_IMSCP_PAGE_NAME } from '../../constants'; /** * Handler to support IMSCP modules. @@ -25,11 +26,9 @@ import { AddonModImscp } from '../imscp'; @Injectable( { providedIn: 'root' }) export class AddonModImscpModuleHandlerService extends CoreModuleHandlerBase implements CoreCourseModuleHandler { - static readonly PAGE_NAME = 'mod_imscp'; - name = 'AddonModImscp'; modName = 'imscp'; - protected pageName = AddonModImscpModuleHandlerService.PAGE_NAME; + protected pageName = ADDON_MOD_IMSCP_PAGE_NAME; supportedFeatures = { [CoreConstants.FEATURE_MOD_ARCHETYPE]: CoreConstants.MOD_ARCHETYPE_RESOURCE, diff --git a/src/addons/mod/imscp/services/handlers/prefetch.ts b/src/addons/mod/imscp/services/handlers/prefetch.ts index 667603fed..5aa83b35a 100644 --- a/src/addons/mod/imscp/services/handlers/prefetch.ts +++ b/src/addons/mod/imscp/services/handlers/prefetch.ts @@ -25,7 +25,8 @@ import { CoreSites, CoreSitesReadingStrategy } from '@services/sites'; import { CoreUtils } from '@services/utils/utils'; import { CoreWSFile } from '@services/ws'; import { makeSingleton } from '@singletons'; -import { AddonModImscp, AddonModImscpProvider } from '../imscp'; +import { AddonModImscp } from '../imscp'; +import { ADDON_MOD_IMSCP_COMPONENT } from '../../constants'; /** * Handler to prefetch IMSCPs. @@ -35,7 +36,7 @@ export class AddonModImscpPrefetchHandlerService extends CoreCourseResourcePrefe name = 'AddonModImscp'; modName = 'imscp'; - component = AddonModImscpProvider.COMPONENT; + component = ADDON_MOD_IMSCP_COMPONENT; /** * @inheritdoc diff --git a/src/addons/mod/imscp/services/imscp.ts b/src/addons/mod/imscp/services/imscp.ts index d756a88ce..caa1cab77 100644 --- a/src/addons/mod/imscp/services/imscp.ts +++ b/src/addons/mod/imscp/services/imscp.ts @@ -27,8 +27,7 @@ import { CoreWSExternalFile, CoreWSExternalWarning } from '@services/ws'; import { makeSingleton, Translate } from '@singletons'; import { CorePath } from '@singletons/path'; import { CoreSiteWSPreSets } from '@classes/sites/authenticated-site'; - -const ROOT_CACHE_KEY = 'mmaModImscp:'; +import { ADDON_MOD_IMSCP_COMPONENT } from '../constants'; /** * Service that provides some features for IMSCP. @@ -36,7 +35,7 @@ const ROOT_CACHE_KEY = 'mmaModImscp:'; @Injectable( { providedIn: 'root' }) export class AddonModImscpProvider { - static readonly COMPONENT = 'mmaModImscp'; + protected static readonly ROOT_CACHE_KEY = 'mmaModImscp:'; /** * Get the IMSCP toc as an array. @@ -89,7 +88,7 @@ export class AddonModImscpProvider { * @returns Cache key. */ protected getImscpDataCacheKey(courseId: number): string { - return ROOT_CACHE_KEY + 'imscp:' + courseId; + return AddonModImscpProvider.ROOT_CACHE_KEY + 'imscp:' + courseId; } /** @@ -116,7 +115,7 @@ export class AddonModImscpProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getImscpDataCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, - component: AddonModImscpProvider.COMPONENT, + component: ADDON_MOD_IMSCP_COMPONENT, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), }; @@ -207,7 +206,7 @@ export class AddonModImscpProvider { */ async getLastItemViewed(id: number, siteId?: string): Promise { const site = await CoreSites.getSite(siteId); - const entry = await site.getLastViewed(AddonModImscpProvider.COMPONENT, id); + const entry = await site.getLastViewed(ADDON_MOD_IMSCP_COMPONENT, id); return entry?.value; } @@ -226,7 +225,7 @@ export class AddonModImscpProvider { const promises: Promise[] = []; promises.push(this.invalidateImscpData(courseId, siteId)); - promises.push(CoreFilepool.invalidateFilesByComponent(siteId, AddonModImscpProvider.COMPONENT, moduleId)); + promises.push(CoreFilepool.invalidateFilesByComponent(siteId, ADDON_MOD_IMSCP_COMPONENT, moduleId)); promises.push(CoreCourse.invalidateModule(moduleId, siteId)); await CoreUtils.allPromises(promises); @@ -283,7 +282,7 @@ export class AddonModImscpProvider { await CoreCourseLogHelper.log( 'mod_imscp_view_imscp', params, - AddonModImscpProvider.COMPONENT, + ADDON_MOD_IMSCP_COMPONENT, id, siteId, ); @@ -301,7 +300,7 @@ export class AddonModImscpProvider { async storeLastItemViewed(id: number, href: string, courseId: number, siteId?: string): Promise { const site = await CoreSites.getSite(siteId); - await site.storeLastViewed(AddonModImscpProvider.COMPONENT, id, href, { data: String(courseId) }); + await site.storeLastViewed(ADDON_MOD_IMSCP_COMPONENT, id, href, { data: String(courseId) }); } } From 7e37b47fd40d9e8b59f6a08e28ee5ccdd3bf21eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Thu, 11 Jul 2024 22:42:15 +0200 Subject: [PATCH 13/26] MOBILE-4616 label: Move label constants to a file --- src/addons/mod/label/constants.ts | 15 +++++++++++++++ .../mod/label/services/handlers/prefetch.ts | 5 +++-- src/addons/mod/label/services/label.ts | 11 +++++------ 3 files changed, 23 insertions(+), 8 deletions(-) create mode 100644 src/addons/mod/label/constants.ts diff --git a/src/addons/mod/label/constants.ts b/src/addons/mod/label/constants.ts new file mode 100644 index 000000000..c5a39b836 --- /dev/null +++ b/src/addons/mod/label/constants.ts @@ -0,0 +1,15 @@ +// (C) Copyright 2015 Moodle Pty Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export const ADDON_MOD_LABEL_COMPONENT = 'mmaModLabel'; diff --git a/src/addons/mod/label/services/handlers/prefetch.ts b/src/addons/mod/label/services/handlers/prefetch.ts index 72f153fa5..bd65a972c 100644 --- a/src/addons/mod/label/services/handlers/prefetch.ts +++ b/src/addons/mod/label/services/handlers/prefetch.ts @@ -19,7 +19,8 @@ import { CoreSitesReadingStrategy } from '@services/sites'; import { CoreUtils } from '@services/utils/utils'; import { CoreWSFile } from '@services/ws'; import { makeSingleton } from '@singletons'; -import { AddonModLabel, AddonModLabelProvider } from '../label'; +import { AddonModLabel } from '../label'; +import { ADDON_MOD_LABEL_COMPONENT } from '../../constants'; /** * Handler to prefetch labels. @@ -29,7 +30,7 @@ export class AddonModLabelPrefetchHandlerService extends CoreCourseResourcePrefe name = 'AddonModLabel'; modName = 'label'; - component = AddonModLabelProvider.COMPONENT; + component = ADDON_MOD_LABEL_COMPONENT; updatesNames = /^.*files$/; /** diff --git a/src/addons/mod/label/services/label.ts b/src/addons/mod/label/services/label.ts index 07f3c0767..f4a5e8260 100644 --- a/src/addons/mod/label/services/label.ts +++ b/src/addons/mod/label/services/label.ts @@ -21,8 +21,7 @@ import { CoreSites, CoreSitesCommonWSOptions } from '@services/sites'; import { CoreUtils } from '@services/utils/utils'; import { CoreWSExternalFile, CoreWSExternalWarning } from '@services/ws'; import { makeSingleton, Translate } from '@singletons'; - -const ROOT_CACHE_KEY = 'mmaModLabel:'; +import { ADDON_MOD_LABEL_COMPONENT } from '../constants'; /** * Service that provides some features for labels. @@ -30,7 +29,7 @@ const ROOT_CACHE_KEY = 'mmaModLabel:'; @Injectable({ providedIn: 'root' }) export class AddonModLabelProvider { - static readonly COMPONENT = 'mmaModLabel'; + protected static readonly ROOT_CACHE_KEY = 'mmaModLabel:'; /** * Get cache key for label data WS calls. @@ -39,7 +38,7 @@ export class AddonModLabelProvider { * @returns Cache key. */ protected getLabelDataCacheKey(courseId: number): string { - return ROOT_CACHE_KEY + 'label:' + courseId; + return AddonModLabelProvider.ROOT_CACHE_KEY + 'label:' + courseId; } /** @@ -66,7 +65,7 @@ export class AddonModLabelProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getLabelDataCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, - component: AddonModLabelProvider.COMPONENT, + component: ADDON_MOD_LABEL_COMPONENT, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), }; @@ -132,7 +131,7 @@ export class AddonModLabelProvider { const promises: Promise[] = []; promises.push(this.invalidateLabelData(courseId, siteId)); - promises.push(CoreFilepool.invalidateFilesByComponent(siteId, AddonModLabelProvider.COMPONENT, moduleId, true)); + promises.push(CoreFilepool.invalidateFilesByComponent(siteId, ADDON_MOD_LABEL_COMPONENT, moduleId, true)); await CoreUtils.allPromises(promises); } From df814d022cca0ab01f8c201094957843b658965f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Thu, 11 Jul 2024 22:42:34 +0200 Subject: [PATCH 14/26] MOBILE-4616 lti: Move lti constants to a file --- src/addons/mod/lti/components/index/index.ts | 5 +++-- src/addons/mod/lti/constants.ts | 16 ++++++++++++++++ src/addons/mod/lti/lti-lazy.module.ts | 2 +- src/addons/mod/lti/lti.module.ts | 7 ++++--- .../mod/lti/services/handlers/module.ts | 5 ++--- .../mod/lti/services/handlers/prefetch.ts | 5 +++-- src/addons/mod/lti/services/lti.ts | 19 +++++++++---------- 7 files changed, 38 insertions(+), 21 deletions(-) create mode 100644 src/addons/mod/lti/constants.ts diff --git a/src/addons/mod/lti/components/index/index.ts b/src/addons/mod/lti/components/index/index.ts index c1870a741..5cae00a74 100644 --- a/src/addons/mod/lti/components/index/index.ts +++ b/src/addons/mod/lti/components/index/index.ts @@ -17,8 +17,9 @@ import { IonContent } from '@ionic/angular'; import { CoreCourseModuleMainActivityComponent } from '@features/course/classes/main-activity-component'; import { CoreCourseContentsPage } from '@features/course/pages/contents/contents'; -import { AddonModLti, AddonModLtiLti, AddonModLtiProvider } from '../../services/lti'; +import { AddonModLti, AddonModLtiLti } from '../../services/lti'; import { AddonModLtiHelper } from '../../services/lti-helper'; +import { ADDON_MOD_LTI_COMPONENT } from '../../constants'; /** * Component that displays an LTI entry page. @@ -29,7 +30,7 @@ import { AddonModLtiHelper } from '../../services/lti-helper'; }) export class AddonModLtiIndexComponent extends CoreCourseModuleMainActivityComponent implements OnInit { - component = AddonModLtiProvider.COMPONENT; + component = ADDON_MOD_LTI_COMPONENT; pluginName = 'lti'; displayDescription = false; diff --git a/src/addons/mod/lti/constants.ts b/src/addons/mod/lti/constants.ts new file mode 100644 index 000000000..c576c5638 --- /dev/null +++ b/src/addons/mod/lti/constants.ts @@ -0,0 +1,16 @@ +// (C) Copyright 2015 Moodle Pty Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export const ADDON_MOD_LTI_COMPONENT = 'mmaModLti'; +export const ADDON_MOD_LTI_PAGE_NAME = 'mod_lti'; diff --git a/src/addons/mod/lti/lti-lazy.module.ts b/src/addons/mod/lti/lti-lazy.module.ts index 8e172a28c..e1419e852 100644 --- a/src/addons/mod/lti/lti-lazy.module.ts +++ b/src/addons/mod/lti/lti-lazy.module.ts @@ -35,4 +35,4 @@ const routes: Routes = [ AddonModLtiIndexPage, ], }) -export class AddonModLtiLazyModule {} +export default class AddonModLtiLazyModule {} diff --git a/src/addons/mod/lti/lti.module.ts b/src/addons/mod/lti/lti.module.ts index 27cd783da..6e300ddad 100644 --- a/src/addons/mod/lti/lti.module.ts +++ b/src/addons/mod/lti/lti.module.ts @@ -20,14 +20,15 @@ import { CoreCourseModulePrefetchDelegate } from '@features/course/services/modu import { CoreMainMenuTabRoutingModule } from '@features/mainmenu/mainmenu-tab-routing.module'; import { AddonModLtiIndexLinkHandler } from './services/handlers/index-link'; import { AddonModLtiListLinkHandler } from './services/handlers/list-link'; -import { AddonModLtiModuleHandler, AddonModLtiModuleHandlerService } from './services/handlers/module'; +import { AddonModLtiModuleHandler } from './services/handlers/module'; import { AddonModLtiPrefetchHandler } from './services/handlers/prefetch'; import { AddonModLtiHelper } from './services/lti-helper'; +import { ADDON_MOD_LTI_PAGE_NAME } from './constants'; const routes: Routes = [ { - path: AddonModLtiModuleHandlerService.PAGE_NAME, - loadChildren: () => import('./lti-lazy.module').then(m => m.AddonModLtiLazyModule), + path: ADDON_MOD_LTI_PAGE_NAME, + loadChildren: () => import('./lti-lazy.module'), }, ]; diff --git a/src/addons/mod/lti/services/handlers/module.ts b/src/addons/mod/lti/services/handlers/module.ts index 2b0eb973c..ed14c1a71 100644 --- a/src/addons/mod/lti/services/handlers/module.ts +++ b/src/addons/mod/lti/services/handlers/module.ts @@ -21,6 +21,7 @@ import { makeSingleton } from '@singletons'; import { AddonModLtiHelper } from '../lti-helper'; import { CoreModuleHandlerBase } from '@features/course/classes/module-base-handler'; import { CoreCourse } from '@features/course/services/course'; +import { ADDON_MOD_LTI_PAGE_NAME } from '../../constants'; /** * Handler to support LTI modules. @@ -28,11 +29,9 @@ import { CoreCourse } from '@features/course/services/course'; @Injectable({ providedIn: 'root' }) export class AddonModLtiModuleHandlerService extends CoreModuleHandlerBase implements CoreCourseModuleHandler { - static readonly PAGE_NAME = 'mod_lti'; - name = 'AddonModLti'; modName = 'lti'; - protected pageName = AddonModLtiModuleHandlerService.PAGE_NAME; + protected pageName = ADDON_MOD_LTI_PAGE_NAME; supportedFeatures = { [CoreConstants.FEATURE_GROUPS]: false, diff --git a/src/addons/mod/lti/services/handlers/prefetch.ts b/src/addons/mod/lti/services/handlers/prefetch.ts index b8682bb6a..4b4e24880 100644 --- a/src/addons/mod/lti/services/handlers/prefetch.ts +++ b/src/addons/mod/lti/services/handlers/prefetch.ts @@ -17,7 +17,8 @@ import { Injectable } from '@angular/core'; import { CoreCourseActivityPrefetchHandlerBase } from '@features/course/classes/activity-prefetch-handler'; import { CoreCourseAnyModuleData } from '@features/course/services/course'; import { makeSingleton } from '@singletons'; -import { AddonModLti, AddonModLtiProvider } from '../lti'; +import { AddonModLti } from '../lti'; +import { ADDON_MOD_LTI_COMPONENT } from '../../constants'; /** * Handler to prefetch LTIs. LTIs cannot be prefetched, but the handler will be used to invalidate some data on course PTR. @@ -27,7 +28,7 @@ export class AddonModLtiPrefetchHandlerService extends CoreCourseActivityPrefetc name = 'AddonModLti'; modName = 'lti'; - component = AddonModLtiProvider.COMPONENT; + component = ADDON_MOD_LTI_COMPONENT; /** * @inheritdoc diff --git a/src/addons/mod/lti/services/lti.ts b/src/addons/mod/lti/services/lti.ts index dfb411098..ab3ca0547 100644 --- a/src/addons/mod/lti/services/lti.ts +++ b/src/addons/mod/lti/services/lti.ts @@ -26,9 +26,7 @@ import { CoreUrlUtils } from '@services/utils/url'; import { CoreUtils } from '@services/utils/utils'; import { CoreWSExternalFile, CoreWSExternalWarning } from '@services/ws'; import { makeSingleton, Translate } from '@singletons'; - -const ROOT_CACHE_KEY = 'mmaModLti:'; -const LAUNCHER_FILE_NAME = 'lti_launcher.html'; +import { ADDON_MOD_LTI_COMPONENT } from '../constants'; /** * Service that provides some features for LTI. @@ -36,7 +34,8 @@ const LAUNCHER_FILE_NAME = 'lti_launcher.html'; @Injectable({ providedIn: 'root' }) export class AddonModLtiProvider { - static readonly COMPONENT = 'mmaModLti'; + protected static readonly ROOT_CACHE_KEY = 'mmaModLti:'; + protected static readonly LAUNCHER_FILE_NAME = 'lti_launcher.html'; /** * Delete launcher. @@ -44,7 +43,7 @@ export class AddonModLtiProvider { * @returns Promise resolved when the launcher file is deleted. */ deleteLauncher(): Promise { - return CoreFile.removeFile(LAUNCHER_FILE_NAME); + return CoreFile.removeFile(AddonModLtiProvider.LAUNCHER_FILE_NAME); } /** @@ -78,7 +77,7 @@ export class AddonModLtiProvider { ' }; \n' + ' \n'; - const entry = await CoreFile.writeFile(LAUNCHER_FILE_NAME, text); + const entry = await CoreFile.writeFile(AddonModLtiProvider.LAUNCHER_FILE_NAME, text); return CoreFile.getFileEntryURL(entry); } @@ -98,7 +97,7 @@ export class AddonModLtiProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getLtiCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, - component: AddonModLtiProvider.COMPONENT, + component: ADDON_MOD_LTI_COMPONENT, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -121,7 +120,7 @@ export class AddonModLtiProvider { * @returns Cache key. */ protected getLtiCacheKey(courseId: number): string { - return ROOT_CACHE_KEY + 'lti:' + courseId; + return AddonModLtiProvider.ROOT_CACHE_KEY + 'lti:' + courseId; } /** @@ -156,7 +155,7 @@ export class AddonModLtiProvider { * @returns Cache key. */ protected getLtiLaunchDataCacheKey(id: number): string { - return `${ROOT_CACHE_KEY}launch:${id}`; + return `${AddonModLtiProvider.ROOT_CACHE_KEY}launch:${id}`; } /** @@ -276,7 +275,7 @@ export class AddonModLtiProvider { return CoreCourseLogHelper.log( 'mod_lti_view_lti', params, - AddonModLtiProvider.COMPONENT, + ADDON_MOD_LTI_COMPONENT, id, siteId, ); From ba80f1ce05707031021850b19cf27759547e06dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Thu, 11 Jul 2024 22:43:17 +0200 Subject: [PATCH 15/26] MOBILE-4616 wiki: Move wiki constants to a file --- src/addons/mod/wiki/components/index/index.ts | 28 +++++++----- src/addons/mod/wiki/constants.ts | 23 ++++++++++ src/addons/mod/wiki/pages/edit/edit.ts | 9 ++-- .../mod/wiki/services/handlers/create-link.ts | 4 +- .../mod/wiki/services/handlers/edit-link.ts | 4 +- .../mod/wiki/services/handlers/module.ts | 5 +-- .../services/handlers/page-or-map-link.ts | 4 +- .../mod/wiki/services/handlers/prefetch.ts | 5 ++- src/addons/mod/wiki/services/wiki-sync.ts | 12 +++-- src/addons/mod/wiki/services/wiki.ts | 44 ++++++++++--------- src/addons/mod/wiki/wiki-lazy.module.ts | 2 +- src/addons/mod/wiki/wiki.module.ts | 10 ++--- 12 files changed, 89 insertions(+), 61 deletions(-) create mode 100644 src/addons/mod/wiki/constants.ts diff --git a/src/addons/mod/wiki/components/index/index.ts b/src/addons/mod/wiki/components/index/index.ts index 0697049ff..57fdb29e2 100644 --- a/src/addons/mod/wiki/components/index/index.ts +++ b/src/addons/mod/wiki/components/index/index.ts @@ -33,11 +33,9 @@ import { CorePath } from '@singletons/path'; import { Subscription } from 'rxjs'; import { Md5 } from 'ts-md5'; import { AddonModWikiPageDBRecord } from '../../services/database/wiki'; -import { AddonModWikiModuleHandlerService } from '../../services/handlers/module'; import { AddonModWiki, AddonModWikiPageContents, - AddonModWikiProvider, AddonModWikiSubwiki, AddonModWikiSubwikiListData, AddonModWikiSubwikiListGrouping, @@ -49,12 +47,18 @@ import { AddonModWikiOffline } from '../../services/wiki-offline'; import { AddonModWikiAutoSyncData, AddonModWikiSync, - AddonModWikiSyncProvider, AddonModWikiSyncWikiResult, AddonModWikiSyncWikiSubwiki, } from '../../services/wiki-sync'; import { AddonModWikiMapModalComponent, AddonModWikiMapModalReturn } from '../map/map'; import { AddonModWikiSubwikiPickerComponent } from '../subwiki-picker/subwiki-picker'; +import { + ADDON_MOD_WIKI_AUTO_SYNCED, + ADDON_MOD_WIKI_COMPONENT, + ADDON_MOD_WIKI_MANUAL_SYNCED, + ADDON_MOD_WIKI_PAGE_CREATED_EVENT, + ADDON_MOD_WIKI_PAGE_NAME, +} from '../../constants'; /** * Component that displays a wiki entry page. @@ -73,7 +77,7 @@ export class AddonModWikiIndexComponent extends CoreCourseModuleMainActivityComp @Input() userId?: number; @Input() groupId?: number; - component = AddonModWikiProvider.COMPONENT; + component = ADDON_MOD_WIKI_COMPONENT; componentId?: number; pluginName = 'wiki'; groupWiki = false; @@ -99,7 +103,7 @@ export class AddonModWikiIndexComponent extends CoreCourseModuleMainActivityComp count: 0, }; - protected syncEventName = AddonModWikiSyncProvider.AUTO_SYNCED; + protected syncEventName = ADDON_MOD_WIKI_AUTO_SYNCED; protected currentSubwiki?: AddonModWikiSubwiki; // Current selected subwiki. protected currentPage?: number; // Current loaded page ID. protected subwikiPages?: (AddonModWikiSubwikiPage | AddonModWikiPageDBRecord)[]; // List of subwiki pages. @@ -155,7 +159,7 @@ export class AddonModWikiIndexComponent extends CoreCourseModuleMainActivityComp */ protected listenEvents(): void { // Listen for manual sync events. - this.manualSyncObserver = CoreEvents.on(AddonModWikiSyncProvider.MANUAL_SYNCED, (data) => { + this.manualSyncObserver = CoreEvents.on(ADDON_MOD_WIKI_MANUAL_SYNCED, (data) => { if (!data || !this.wiki || data.wikiId != this.wiki.id) { return; } @@ -313,7 +317,7 @@ export class AddonModWikiIndexComponent extends CoreCourseModuleMainActivityComp this.pageIsOffline = true; if (!this.newPageObserver) { // It's an offline page, listen for new pages event to detect if the user goes to Edit and submits the page. - this.newPageObserver = CoreEvents.on(AddonModWikiProvider.PAGE_CREATED_EVENT, async (data) => { + this.newPageObserver = CoreEvents.on(ADDON_MOD_WIKI_PAGE_CREATED_EVENT, async (data) => { if (data.subwikiId != this.currentSubwiki?.id || data.pageTitle != title) { return; } @@ -528,7 +532,7 @@ export class AddonModWikiIndexComponent extends CoreCourseModuleMainActivityComp */ protected goToCreateFirstPage(): void { CoreNavigator.navigateToSitePath( - `${AddonModWikiModuleHandlerService.PAGE_NAME}/${this.courseId}/${this.module.id}/edit`, + `${ADDON_MOD_WIKI_PAGE_NAME}/${this.courseId}/${this.module.id}/edit`, { params: { pageTitle: this.wiki?.firstpagetitle ?? '', @@ -566,7 +570,7 @@ export class AddonModWikiIndexComponent extends CoreCourseModuleMainActivityComp } CoreNavigator.navigateToSitePath( - `${AddonModWikiModuleHandlerService.PAGE_NAME}/${this.courseId}/${this.module.id}/edit`, + `${ADDON_MOD_WIKI_PAGE_NAME}/${this.courseId}/${this.module.id}/edit`, { params: pageParams }, ); } else if (this.currentSubwiki) { @@ -596,7 +600,7 @@ export class AddonModWikiIndexComponent extends CoreCourseModuleMainActivityComp } CoreNavigator.navigateToSitePath( - `${AddonModWikiModuleHandlerService.PAGE_NAME}/${this.courseId}/${this.module.id}/edit`, + `${ADDON_MOD_WIKI_PAGE_NAME}/${this.courseId}/${this.module.id}/edit`, { params: pageParams }, ); } else if (this.currentSubwiki) { @@ -644,7 +648,7 @@ export class AddonModWikiIndexComponent extends CoreCourseModuleMainActivityComp })); CoreNavigator.navigateToSitePath( - `${AddonModWikiModuleHandlerService.PAGE_NAME}/${this.courseId}/${this.module.id}/page/${hash}`, + `${ADDON_MOD_WIKI_PAGE_NAME}/${this.courseId}/${this.module.id}/page/${hash}`, { params: { module: this.module, @@ -771,7 +775,7 @@ export class AddonModWikiIndexComponent extends CoreCourseModuleMainActivityComp if (result.updated && this.wiki) { // Trigger event. this.ignoreManualSyncEvent = true; - CoreEvents.trigger(AddonModWikiSyncProvider.MANUAL_SYNCED, { + CoreEvents.trigger(ADDON_MOD_WIKI_MANUAL_SYNCED, { ...result, wikiId: this.wiki.id, }); diff --git a/src/addons/mod/wiki/constants.ts b/src/addons/mod/wiki/constants.ts new file mode 100644 index 000000000..2272f0dcc --- /dev/null +++ b/src/addons/mod/wiki/constants.ts @@ -0,0 +1,23 @@ +// (C) Copyright 2015 Moodle Pty Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export const ADDON_MOD_WIKI_COMPONENT = 'mmaModWiki'; + +export const ADDON_MOD_WIKI_PAGE_NAME = 'mod_wiki'; + +export const ADDON_MOD_WIKI_AUTO_SYNCED = 'addon_mod_wiki_autom_synced'; +export const ADDON_MOD_WIKI_MANUAL_SYNCED = 'addon_mod_wiki_manual_synced'; + +export const ADDON_MOD_WIKI_PAGE_CREATED_EVENT = 'addon_mod_wiki_page_created'; +export const ADDON_MOD_WIKI_RENEW_LOCK_TIME = 30000; // Milliseconds. diff --git a/src/addons/mod/wiki/pages/edit/edit.ts b/src/addons/mod/wiki/pages/edit/edit.ts index 816bd2ffa..0e8795775 100644 --- a/src/addons/mod/wiki/pages/edit/edit.ts +++ b/src/addons/mod/wiki/pages/edit/edit.ts @@ -27,10 +27,11 @@ import { CoreWSFile } from '@services/ws'; import { Translate } from '@singletons'; import { CoreEvents } from '@singletons/events'; import { CoreForms } from '@singletons/form'; -import { AddonModWiki, AddonModWikiProvider } from '../../services/wiki'; +import { AddonModWiki } from '../../services/wiki'; import { AddonModWikiOffline } from '../../services/wiki-offline'; import { AddonModWikiSync } from '../../services/wiki-sync'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; +import { ADDON_MOD_WIKI_COMPONENT, ADDON_MOD_WIKI_PAGE_CREATED_EVENT, ADDON_MOD_WIKI_RENEW_LOCK_TIME } from '../../constants'; /** * Page that allows adding or editing a wiki page. @@ -50,7 +51,7 @@ export class AddonModWikiEditPage implements OnInit, OnDestroy, CanLeave { contentControl: FormControl; // The FormControl for the page content. canEditTitle = false; // Whether title can be edited. loaded = false; // Whether the data has been loaded. - component = AddonModWikiProvider.COMPONENT; // Component to link the files to. + component = ADDON_MOD_WIKI_COMPONENT; // Component to link the files to. wrongVersionLock = false; // Whether the page lock doesn't match the initial one. editorExtraParams: Record = {}; @@ -190,7 +191,7 @@ export class AddonModWikiEditPage implements OnInit, OnDestroy, CanLeave { // Renew the lock every certain time. this.renewLockInterval = window.setInterval(() => { this.renewLock(); - }, AddonModWikiProvider.RENEW_LOCK_TIME); + }, ADDON_MOD_WIKI_RENEW_LOCK_TIME); } } else { const pageTitle = this.pageForm.controls.title.value; @@ -442,7 +443,7 @@ export class AddonModWikiEditPage implements OnInit, OnDestroy, CanLeave { await CoreUtils.ignoreErrors(Promise.all(promises)); // Notify page created. - CoreEvents.trigger(AddonModWikiProvider.PAGE_CREATED_EVENT, { + CoreEvents.trigger(ADDON_MOD_WIKI_PAGE_CREATED_EVENT, { pageId: this.pageId, subwikiId: this.subwikiId, pageTitle: title, diff --git a/src/addons/mod/wiki/services/handlers/create-link.ts b/src/addons/mod/wiki/services/handlers/create-link.ts index 25f604ef9..baf13ab5b 100644 --- a/src/addons/mod/wiki/services/handlers/create-link.ts +++ b/src/addons/mod/wiki/services/handlers/create-link.ts @@ -23,7 +23,7 @@ import { CoreDomUtils } from '@services/utils/dom'; import { makeSingleton } from '@singletons'; import { AddonModWikiIndexPage } from '../../pages/index'; import { AddonModWiki } from '../wiki'; -import { AddonModWikiModuleHandlerService } from './module'; +import { ADDON_MOD_WIKI_PAGE_NAME } from '../../constants'; /** * Handler to treat links to create a wiki page. @@ -109,7 +109,7 @@ export class AddonModWikiCreateLinkHandlerService extends CoreContentLinksHandle } const subwikiId = parseInt(params.swid, 10); const wikiId = parseInt(params.wid, 10); - let path = AddonModWikiModuleHandlerService.PAGE_NAME; + let path = ADDON_MOD_WIKI_PAGE_NAME; // Check if the link is inside the same wiki. const isSameWiki = await this.currentStateIsSameWiki(route, subwikiId, siteId); diff --git a/src/addons/mod/wiki/services/handlers/edit-link.ts b/src/addons/mod/wiki/services/handlers/edit-link.ts index 6a252a795..16cd102c0 100644 --- a/src/addons/mod/wiki/services/handlers/edit-link.ts +++ b/src/addons/mod/wiki/services/handlers/edit-link.ts @@ -21,7 +21,7 @@ import { CoreSitesReadingStrategy } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { makeSingleton } from '@singletons'; import { AddonModWiki } from '../wiki'; -import { AddonModWikiModuleHandlerService } from './module'; +import { ADDON_MOD_WIKI_PAGE_NAME } from '../../constants'; /** * Handler to treat links to edit a wiki page. @@ -63,7 +63,7 @@ export class AddonModWikiEditLinkHandlerService extends CoreContentLinksHandlerB } await CoreNavigator.navigateToSitePath( - AddonModWikiModuleHandlerService.PAGE_NAME + `/${module.course}/${module.id}/edit`, + `${ADDON_MOD_WIKI_PAGE_NAME}/${module.course}/${module.id}/edit`, { params: { section: section, diff --git a/src/addons/mod/wiki/services/handlers/module.ts b/src/addons/mod/wiki/services/handlers/module.ts index 682a3f398..3997758a9 100644 --- a/src/addons/mod/wiki/services/handlers/module.ts +++ b/src/addons/mod/wiki/services/handlers/module.ts @@ -17,6 +17,7 @@ import { Injectable, Type } from '@angular/core'; import { CoreModuleHandlerBase } from '@features/course/classes/module-base-handler'; import { CoreCourseModuleHandler } from '@features/course/services/module-delegate'; import { makeSingleton } from '@singletons'; +import { ADDON_MOD_WIKI_PAGE_NAME } from '../../constants'; /** * Handler to support wiki modules. @@ -24,11 +25,9 @@ import { makeSingleton } from '@singletons'; @Injectable({ providedIn: 'root' }) export class AddonModWikiModuleHandlerService extends CoreModuleHandlerBase implements CoreCourseModuleHandler { - static readonly PAGE_NAME = 'mod_wiki'; - name = 'AddonModWiki'; modName = 'wiki'; - protected pageName = AddonModWikiModuleHandlerService.PAGE_NAME; + protected pageName = ADDON_MOD_WIKI_PAGE_NAME; supportedFeatures = { [CoreConstants.FEATURE_GROUPS]: true, diff --git a/src/addons/mod/wiki/services/handlers/page-or-map-link.ts b/src/addons/mod/wiki/services/handlers/page-or-map-link.ts index c6b9f0835..d7f0e3dd4 100644 --- a/src/addons/mod/wiki/services/handlers/page-or-map-link.ts +++ b/src/addons/mod/wiki/services/handlers/page-or-map-link.ts @@ -22,7 +22,7 @@ import { CoreDomUtils } from '@services/utils/dom'; import { makeSingleton } from '@singletons'; import { Md5 } from 'ts-md5'; import { AddonModWiki } from '../wiki'; -import { AddonModWikiModuleHandlerService } from './module'; +import { ADDON_MOD_WIKI_PAGE_NAME } from '../../constants'; /** * Handler to treat links to a wiki page or the wiki map. @@ -68,7 +68,7 @@ export class AddonModWikiPageOrMapLinkHandlerService extends CoreContentLinksHan })); await CoreNavigator.navigateToSitePath( - AddonModWikiModuleHandlerService.PAGE_NAME + `/${module.course}/${module.id}/page/${hash}`, + `${ADDON_MOD_WIKI_PAGE_NAME}/${module.course}/${module.id}/page/${hash}`, { params: { module, diff --git a/src/addons/mod/wiki/services/handlers/prefetch.ts b/src/addons/mod/wiki/services/handlers/prefetch.ts index 5fd8a396a..69feb6614 100644 --- a/src/addons/mod/wiki/services/handlers/prefetch.ts +++ b/src/addons/mod/wiki/services/handlers/prefetch.ts @@ -22,8 +22,9 @@ import { CoreSites, CoreSitesCommonWSOptions, CoreSitesReadingStrategy } from '@ import { CoreUtils } from '@services/utils/utils'; import { CoreWSFile } from '@services/ws'; import { makeSingleton } from '@singletons'; -import { AddonModWiki, AddonModWikiProvider, AddonModWikiSubwikiPage } from '../wiki'; +import { AddonModWiki, AddonModWikiSubwikiPage } from '../wiki'; import { AddonModWikiSync, AddonModWikiSyncWikiResult } from '../wiki-sync'; +import { ADDON_MOD_WIKI_COMPONENT } from '../../constants'; /** * Handler to prefetch wikis. @@ -33,7 +34,7 @@ export class AddonModWikiPrefetchHandlerService extends CoreCourseActivityPrefet name = 'AddonModWiki'; modName = 'wiki'; - component = AddonModWikiProvider.COMPONENT; + component = ADDON_MOD_WIKI_COMPONENT; updatesNames = /^.*files$|^pages$/; /** diff --git a/src/addons/mod/wiki/services/wiki-sync.ts b/src/addons/mod/wiki/services/wiki-sync.ts index 0ba10b7f2..c79f614f9 100644 --- a/src/addons/mod/wiki/services/wiki-sync.ts +++ b/src/addons/mod/wiki/services/wiki-sync.ts @@ -24,8 +24,9 @@ import { CoreUtils } from '@services/utils/utils'; import { makeSingleton, Translate } from '@singletons'; import { CoreEvents } from '@singletons/events'; import { AddonModWikiPageDBRecord } from './database/wiki'; -import { AddonModWiki, AddonModWikiProvider } from './wiki'; +import { AddonModWiki } from './wiki'; import { AddonModWikiOffline } from './wiki-offline'; +import { ADDON_MOD_WIKI_AUTO_SYNCED, ADDON_MOD_WIKI_COMPONENT } from '../constants'; /** * Service to sync wikis. @@ -33,9 +34,6 @@ import { AddonModWikiOffline } from './wiki-offline'; @Injectable({ providedIn: 'root' }) export class AddonModWikiSyncProvider extends CoreSyncBaseProvider { - static readonly AUTO_SYNCED = 'addon_mod_wiki_autom_synced'; - static readonly MANUAL_SYNCED = 'addon_mod_wiki_manual_synced'; - protected componentTranslatableString = 'wiki'; constructor() { @@ -106,7 +104,7 @@ export class AddonModWikiSyncProvider extends CoreSyncBaseProvider> = {}; @@ -137,7 +139,7 @@ export class AddonModWikiProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getPageContentsCacheKey(pageId), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, - component: AddonModWikiProvider.COMPONENT, + component: ADDON_MOD_WIKI_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -154,7 +156,7 @@ export class AddonModWikiProvider { * @returns Cache key. */ protected getPageContentsCacheKey(pageId: number): string { - return ROOT_CACHE_KEY + 'page:' + pageId; + return AddonModWikiProvider.ROOT_CACHE_KEY + 'page:' + pageId; } /** @@ -210,7 +212,7 @@ export class AddonModWikiProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getSubwikiFilesCacheKey(wikiId, groupId, userId), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, - component: AddonModWikiProvider.COMPONENT, + component: ADDON_MOD_WIKI_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -239,7 +241,7 @@ export class AddonModWikiProvider { * @returns Cache key. */ protected getSubwikiFilesCacheKeyPrefix(wikiId: number): string { - return ROOT_CACHE_KEY + 'subwikifiles:' + wikiId; + return AddonModWikiProvider.ROOT_CACHE_KEY + 'subwikifiles:' + wikiId; } /** @@ -280,7 +282,7 @@ export class AddonModWikiProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getSubwikiPagesCacheKey(wikiId, groupId, userId), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, - component: AddonModWikiProvider.COMPONENT, + component: ADDON_MOD_WIKI_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -309,7 +311,7 @@ export class AddonModWikiProvider { * @returns Cache key. */ protected getSubwikiPagesCacheKeyPrefix(wikiId: number): string { - return ROOT_CACHE_KEY + 'subwikipages:' + wikiId; + return AddonModWikiProvider.ROOT_CACHE_KEY + 'subwikipages:' + wikiId; } /** @@ -328,7 +330,7 @@ export class AddonModWikiProvider { const preSets = { cacheKey: this.getSubwikisCacheKey(wikiId), updateFrequency: CoreSite.FREQUENCY_RARELY, - component: AddonModWikiProvider.COMPONENT, + component: ADDON_MOD_WIKI_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -348,7 +350,7 @@ export class AddonModWikiProvider { * @returns Cache key. */ protected getSubwikisCacheKey(wikiId: number): string { - return ROOT_CACHE_KEY + 'subwikis:' + wikiId; + return AddonModWikiProvider.ROOT_CACHE_KEY + 'subwikis:' + wikiId; } /** @@ -386,7 +388,7 @@ export class AddonModWikiProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getWikiDataCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, - component: AddonModWikiProvider.COMPONENT, + component: ADDON_MOD_WIKI_COMPONENT, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -419,7 +421,7 @@ export class AddonModWikiProvider { * @returns Cache key. */ protected getWikiDataCacheKey(courseId: number): string { - return ROOT_CACHE_KEY + 'wiki:' + courseId; + return AddonModWikiProvider.ROOT_CACHE_KEY + 'wiki:' + courseId; } /** @@ -633,7 +635,7 @@ export class AddonModWikiProvider { return CoreCourseLogHelper.log( 'mod_wiki_view_page', params, - AddonModWikiProvider.COMPONENT, + ADDON_MOD_WIKI_COMPONENT, wikiId, siteId, ); @@ -654,7 +656,7 @@ export class AddonModWikiProvider { return CoreCourseLogHelper.log( 'mod_wiki_view_wiki', params, - AddonModWikiProvider.COMPONENT, + ADDON_MOD_WIKI_COMPONENT, id, siteId, ); @@ -895,9 +897,9 @@ declare module '@singletons/events' { * @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation */ export interface CoreEventsData { - [AddonModWikiProvider.PAGE_CREATED_EVENT]: AddonModWikiPageCreatedData; - [AddonModWikiSyncProvider.AUTO_SYNCED]: AddonModWikiAutoSyncData; - [AddonModWikiSyncProvider.MANUAL_SYNCED]: AddonModWikiManualSyncData; + [ADDON_MOD_WIKI_PAGE_CREATED_EVENT]: AddonModWikiPageCreatedData; + [ADDON_MOD_WIKI_AUTO_SYNCED]: AddonModWikiAutoSyncData; + [ADDON_MOD_WIKI_MANUAL_SYNCED]: AddonModWikiManualSyncData; } } diff --git a/src/addons/mod/wiki/wiki-lazy.module.ts b/src/addons/mod/wiki/wiki-lazy.module.ts index 354ad83aa..268c9f6b1 100644 --- a/src/addons/mod/wiki/wiki-lazy.module.ts +++ b/src/addons/mod/wiki/wiki-lazy.module.ts @@ -49,4 +49,4 @@ const routes: Routes = [ AddonModWikiEditPage, ], }) -export class AddonModWikiLazyModule {} +export default class AddonModWikiLazyModule {} diff --git a/src/addons/mod/wiki/wiki.module.ts b/src/addons/mod/wiki/wiki.module.ts index 7625d9987..de4817400 100644 --- a/src/addons/mod/wiki/wiki.module.ts +++ b/src/addons/mod/wiki/wiki.module.ts @@ -27,17 +27,17 @@ import { AddonModWikiCreateLinkHandler } from './services/handlers/create-link'; import { AddonModWikiEditLinkHandler } from './services/handlers/edit-link'; import { AddonModWikiIndexLinkHandler } from './services/handlers/index-link'; import { AddonModWikiListLinkHandler } from './services/handlers/list-link'; -import { AddonModWikiModuleHandler, AddonModWikiModuleHandlerService } from './services/handlers/module'; +import { AddonModWikiModuleHandler } from './services/handlers/module'; import { AddonModWikiPageOrMapLinkHandler } from './services/handlers/page-or-map-link'; import { AddonModWikiPrefetchHandler } from './services/handlers/prefetch'; import { AddonModWikiSyncCronHandler } from './services/handlers/sync-cron'; import { AddonModWikiTagAreaHandler } from './services/handlers/tag-area'; -import { AddonModWikiProvider } from './services/wiki'; +import { ADDON_MOD_WIKI_COMPONENT, ADDON_MOD_WIKI_PAGE_NAME } from './constants'; const routes: Routes = [ { - path: AddonModWikiModuleHandlerService.PAGE_NAME, - loadChildren: () => import('./wiki-lazy.module').then(m => m.AddonModWikiLazyModule), + path: ADDON_MOD_WIKI_PAGE_NAME, + loadChildren: () => import('./wiki-lazy.module'), }, ]; @@ -65,7 +65,7 @@ const routes: Routes = [ CoreContentLinksDelegate.registerHandler(AddonModWikiPageOrMapLinkHandler.instance); CoreTagAreaDelegate.registerHandler(AddonModWikiTagAreaHandler.instance); - CoreCourseHelper.registerModuleReminderClick(AddonModWikiProvider.COMPONENT); + CoreCourseHelper.registerModuleReminderClick(ADDON_MOD_WIKI_COMPONENT); }, }, ], From 65a5659d47706eeb43777120a44aa23fb19ac25b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Thu, 11 Jul 2024 22:43:26 +0200 Subject: [PATCH 16/26] MOBILE-4616 workshop: Move workshop constants to a file --- .../assessment-strategy.ts | 13 +-- .../mod/workshop/components/index/index.ts | 25 +++--- .../mod/workshop/components/phase/phase.ts | 3 +- .../components/submission/submission.ts | 3 +- src/addons/mod/workshop/constants.ts | 45 ++++++++++ .../workshop/pages/assessment/assessment.ts | 17 ++-- .../pages/edit-submission/edit-submission.ts | 12 +-- .../workshop/pages/submission/submission.ts | 27 +++--- .../workshop/services/database/workshop.ts | 2 +- .../services/handlers/prefetch-lazy.ts | 2 +- .../mod/workshop/services/workshop-helper.ts | 12 +-- .../mod/workshop/services/workshop-offline.ts | 2 +- .../mod/workshop/services/workshop-sync.ts | 14 ++-- src/addons/mod/workshop/services/workshop.ts | 82 ++++++------------- .../mod/workshop/workshop-lazy.module.ts | 2 +- src/addons/mod/workshop/workshop.module.ts | 2 +- 16 files changed, 149 insertions(+), 114 deletions(-) diff --git a/src/addons/mod/workshop/components/assessment-strategy/assessment-strategy.ts b/src/addons/mod/workshop/components/assessment-strategy/assessment-strategy.ts index c3656705a..503174cf5 100644 --- a/src/addons/mod/workshop/components/assessment-strategy/assessment-strategy.ts +++ b/src/addons/mod/workshop/components/assessment-strategy/assessment-strategy.ts @@ -29,8 +29,6 @@ import { CoreEventObserver, CoreEvents } from '@singletons/events'; import { CoreFormFields, CoreForms } from '@singletons/form'; import { AddonWorkshopAssessmentStrategyDelegate } from '../../services/assessment-strategy-delegate'; import { - AddonModWorkshopProvider, - AddonModWorkshopOverallFeedbackMode, AddonModWorkshop, AddonModWorkshopData, AddonModWorkshopGetWorkshopAccessInformationWSResponse, @@ -38,7 +36,12 @@ import { } from '../../services/workshop'; import { AddonModWorkshopHelper, AddonModWorkshopSubmissionAssessmentWithFormData } from '../../services/workshop-helper'; import { AddonModWorkshopOffline } from '../../services/workshop-offline'; -import { ADDON_MOD_WORKSHOP_COMPONENT } from '@addons/mod/workshop/constants'; +import { + ADDON_MOD_WORKSHOP_ASSESSMENT_INVALIDATED, + ADDON_MOD_WORKSHOP_ASSESSMENT_SAVED, + ADDON_MOD_WORKSHOP_COMPONENT, + AddonModWorkshopOverallFeedbackMode, +} from '@addons/mod/workshop/constants'; /** * Component that displays workshop assessment strategy form. @@ -135,7 +138,7 @@ export class AddonModWorkshopAssessmentStrategyComponent implements OnInit, OnDe try { await this.load(); this.obsInvalidated = CoreEvents.on( - AddonModWorkshopProvider.ASSESSMENT_INVALIDATED, + ADDON_MOD_WORKSHOP_ASSESSMENT_INVALIDATED, () => this.load(), CoreSites.getCurrentSiteId(), ); @@ -382,7 +385,7 @@ export class AddonModWorkshopAssessmentStrategyComponent implements OnInit, OnDe await CoreUtils.ignoreErrors(Promise.all(promises)); - CoreEvents.trigger(AddonModWorkshopProvider.ASSESSMENT_SAVED, { + CoreEvents.trigger(ADDON_MOD_WORKSHOP_ASSESSMENT_SAVED, { workshopId: this.workshop.id, assessmentId: this.assessmentId, userId: CoreSites.getCurrentSiteUserId(), diff --git a/src/addons/mod/workshop/components/index/index.ts b/src/addons/mod/workshop/components/index/index.ts index 382a796c0..b86e774ea 100644 --- a/src/addons/mod/workshop/components/index/index.ts +++ b/src/addons/mod/workshop/components/index/index.ts @@ -26,8 +26,6 @@ import { CoreUtils } from '@services/utils/utils'; import { CoreEventObserver, CoreEvents } from '@singletons/events'; import { Subscription } from 'rxjs'; import { - AddonModWorkshopProvider, - AddonModWorkshopPhase, AddonModWorkshop, AddonModWorkshopData, AddonModWorkshopGetWorkshopAccessInformationWSResponse, @@ -46,13 +44,20 @@ import { } from '../../services/workshop-helper'; import { AddonModWorkshopOffline, AddonModWorkshopOfflineSubmission } from '../../services/workshop-offline'; import { - AddonModWorkshopSyncProvider, AddonModWorkshopSync, AddonModWorkshopAutoSyncData, AddonModWorkshopSyncResult, } from '../../services/workshop-sync'; import { AddonModWorkshopPhaseInfoComponent } from '../phase/phase'; -import { ADDON_MOD_WORKSHOP_COMPONENT, ADDON_MOD_WORKSHOP_PAGE_NAME } from '@addons/mod/workshop/constants'; +import { + ADDON_MOD_WORKSHOP_ASSESSMENT_SAVED, + ADDON_MOD_WORKSHOP_AUTO_SYNCED, + ADDON_MOD_WORKSHOP_COMPONENT, + ADDON_MOD_WORKSHOP_PAGE_NAME, + ADDON_MOD_WORKSHOP_PER_PAGE, + ADDON_MOD_WORKSHOP_SUBMISSION_CHANGED, + AddonModWorkshopPhase, +} from '@addons/mod/workshop/constants'; /** * Component that displays a workshop index page. @@ -101,7 +106,7 @@ export class AddonModWorkshopIndexComponent extends CoreCourseModuleMainActivity protected obsAssessmentSaved: CoreEventObserver; protected appResumeSubscription: Subscription; protected syncObserver?: CoreEventObserver; - protected syncEventName = AddonModWorkshopSyncProvider.AUTO_SYNCED; + protected syncEventName = ADDON_MOD_WORKSHOP_AUTO_SYNCED; constructor ( @Optional() content: IonContent, @@ -110,12 +115,12 @@ export class AddonModWorkshopIndexComponent extends CoreCourseModuleMainActivity super('AddonModWorkshopIndexComponent', content, courseContentsPage); // Listen to submission and assessment changes. - this.obsSubmissionChanged = CoreEvents.on(AddonModWorkshopProvider.SUBMISSION_CHANGED, (data) => { + this.obsSubmissionChanged = CoreEvents.on(ADDON_MOD_WORKSHOP_SUBMISSION_CHANGED, (data) => { this.eventReceived(data); }, this.siteId); // Listen to submission and assessment changes. - this.obsAssessmentSaved = CoreEvents.on(AddonModWorkshopProvider.ASSESSMENT_SAVED, (data) => { + this.obsAssessmentSaved = CoreEvents.on(ADDON_MOD_WORKSHOP_ASSESSMENT_SAVED, (data) => { this.eventReceived(data); }, this.siteId); @@ -125,7 +130,7 @@ export class AddonModWorkshopIndexComponent extends CoreCourseModuleMainActivity }); // Refresh workshop on sync. - this.syncObserver = CoreEvents.on(AddonModWorkshopSyncProvider.AUTO_SYNCED, (data) => { + this.syncObserver = CoreEvents.on(ADDON_MOD_WORKSHOP_AUTO_SYNCED, (data) => { // Update just when all database is synced. this.eventReceived(data); }, this.siteId); @@ -282,8 +287,8 @@ export class AddonModWorkshopIndexComponent extends CoreCourseModuleMainActivity this.page = page; - this.hasNextPage = numEntries >= AddonModWorkshopProvider.PER_PAGE && ((this.page + 1) * - AddonModWorkshopProvider.PER_PAGE) < report.totalcount; + this.hasNextPage = numEntries >= ADDON_MOD_WORKSHOP_PER_PAGE && ((this.page + 1) * + ADDON_MOD_WORKSHOP_PER_PAGE) < report.totalcount; const grades: AddonModWorkshopGradesData[] = report.grades || []; diff --git a/src/addons/mod/workshop/components/phase/phase.ts b/src/addons/mod/workshop/components/phase/phase.ts index fb0030a84..5fa88c08b 100644 --- a/src/addons/mod/workshop/components/phase/phase.ts +++ b/src/addons/mod/workshop/components/phase/phase.ts @@ -15,7 +15,8 @@ import { Component, Input, OnInit } from '@angular/core'; import { CoreUtils } from '@services/utils/utils'; import { ModalController } from '@singletons'; -import { AddonModWorkshopPhaseData, AddonModWorkshopPhase, AddonModWorkshopPhaseTaskData } from '../../services/workshop'; +import { AddonModWorkshopPhaseData, AddonModWorkshopPhaseTaskData } from '../../services/workshop'; +import { AddonModWorkshopPhase } from '../../constants'; /** * Page that displays the phase info modal. diff --git a/src/addons/mod/workshop/components/submission/submission.ts b/src/addons/mod/workshop/components/submission/submission.ts index 8d49a967c..53ae4a891 100644 --- a/src/addons/mod/workshop/components/submission/submission.ts +++ b/src/addons/mod/workshop/components/submission/submission.ts @@ -20,7 +20,6 @@ import { CoreNavigator } from '@services/navigator'; import { CoreSites } from '@services/sites'; import { AddonModWorkshopSubmissionPage } from '../../pages/submission/submission'; import { - AddonModWorkshopPhase, AddonModWorkshopData, AddonModWorkshopGetWorkshopAccessInformationWSResponse, } from '../../services/workshop'; @@ -30,7 +29,7 @@ import { AddonModWorkshopSubmissionDataWithOfflineData, } from '../../services/workshop-helper'; import { AddonModWorkshopOffline } from '../../services/workshop-offline'; -import { ADDON_MOD_WORKSHOP_COMPONENT, ADDON_MOD_WORKSHOP_PAGE_NAME } from '@addons/mod/workshop/constants'; +import { ADDON_MOD_WORKSHOP_COMPONENT, ADDON_MOD_WORKSHOP_PAGE_NAME, AddonModWorkshopPhase } from '@addons/mod/workshop/constants'; /** * Component that displays workshop submission. diff --git a/src/addons/mod/workshop/constants.ts b/src/addons/mod/workshop/constants.ts index 24ba9d6ff..e164c112f 100644 --- a/src/addons/mod/workshop/constants.ts +++ b/src/addons/mod/workshop/constants.ts @@ -14,6 +14,8 @@ export const ADDON_MOD_WORKSHOP_COMPONENT = 'mmaModWorkshop'; +export const ADDON_MOD_WORKSHOP_PER_PAGE = 10; + // Routing. export const ADDON_MOD_WORKSHOP_PAGE_NAME = 'mod_workshop'; @@ -41,3 +43,46 @@ export const ADDON_MOD_WORKSHOP_PREFETCH_UPDATE_NAMES = new RegExp( export const ADDON_MOD_WORKSHOP_SYNC_CRON_NAME = 'AddonModWorkshopSyncCronHandler'; export const ADDON_MOD_WORKSHOP_FEATURE_NAME = 'CoreCourseModuleDelegate_AddonModWorkshop'; + +// Events. +export const ADDON_MOD_WORKSHOP_SUBMISSION_CHANGED = 'addon_mod_workshop_submission_changed'; +export const ADDON_MOD_WORKSHOP_ASSESSMENT_SAVED = 'addon_mod_workshop_assessment_saved'; +export const ADDON_MOD_WORKSHOP_ASSESSMENT_INVALIDATED = 'addon_mod_workshop_assessment_invalidated'; +export const ADDON_MOD_WORKSHOP_AUTO_SYNCED = 'addon_mod_workshop_autom_synced'; + +export const enum AddonModWorkshopPhase { + PHASE_SETUP = 10, + PHASE_SUBMISSION = 20, + PHASE_ASSESSMENT = 30, + PHASE_EVALUATION = 40, + PHASE_CLOSED = 50, +} + +export const enum AddonModWorkshopSubmissionType { + SUBMISSION_TYPE_DISABLED = 0, + SUBMISSION_TYPE_AVAILABLE = 1, + SUBMISSION_TYPE_REQUIRED = 2, +} + +export const enum AddonModWorkshopExampleMode { + EXAMPLES_VOLUNTARY = 0, + EXAMPLES_BEFORE_SUBMISSION = 1, + EXAMPLES_BEFORE_ASSESSMENT = 2, +} + +export const enum AddonModWorkshopAction { + ADD = 'add', + DELETE = 'delete', + UPDATE = 'update', +} + +export const enum AddonModWorkshopAssessmentMode { + ASSESSMENT = 'assessment', + PREVIEW = 'preview', +} + +export const enum AddonModWorkshopOverallFeedbackMode { + DISABLED = 0, + ENABLED_OPTIONAL = 1, + ENABLED_REQUIRED = 2, +} diff --git a/src/addons/mod/workshop/pages/assessment/assessment.ts b/src/addons/mod/workshop/pages/assessment/assessment.ts index 61fded7ba..080ac4155 100644 --- a/src/addons/mod/workshop/pages/assessment/assessment.ts +++ b/src/addons/mod/workshop/pages/assessment/assessment.ts @@ -31,16 +31,19 @@ import { AddonModWorkshopAssessmentSavedChangedEventData, AddonModWorkshopData, AddonModWorkshopGetWorkshopAccessInformationWSResponse, - AddonModWorkshopPhase, - AddonModWorkshopProvider, AddonModWorkshopSubmissionData, } from '../../services/workshop'; import { AddonModWorkshopHelper, AddonModWorkshopSubmissionAssessmentWithFormData } from '../../services/workshop-helper'; import { AddonModWorkshopOffline } from '../../services/workshop-offline'; -import { AddonModWorkshopSyncProvider } from '../../services/workshop-sync'; import { CoreTime } from '@singletons/time'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; -import { ADDON_MOD_WORKSHOP_COMPONENT } from '@addons/mod/workshop/constants'; +import { + ADDON_MOD_WORKSHOP_ASSESSMENT_INVALIDATED, + ADDON_MOD_WORKSHOP_ASSESSMENT_SAVED, + ADDON_MOD_WORKSHOP_AUTO_SYNCED, + ADDON_MOD_WORKSHOP_COMPONENT, + AddonModWorkshopPhase, +} from '@addons/mod/workshop/constants'; /** * Page that displays a workshop assessment. @@ -107,7 +110,7 @@ export class AddonModWorkshopAssessmentPage implements OnInit, OnDestroy, CanLea this.evaluateForm.addControl('text', this.fb.control('')); // Refresh workshop on sync. - this.syncObserver = CoreEvents.on(AddonModWorkshopSyncProvider.AUTO_SYNCED, (data) => { + this.syncObserver = CoreEvents.on(ADDON_MOD_WORKSHOP_AUTO_SYNCED, (data) => { // Update just when all database is synced. if (this.workshopId === data.workshopId) { this.loaded = false; @@ -331,7 +334,7 @@ export class AddonModWorkshopAssessmentPage implements OnInit, OnDestroy, CanLea try { await Promise.all(promises); } finally { - CoreEvents.trigger(AddonModWorkshopProvider.ASSESSMENT_INVALIDATED, null, this.siteId); + CoreEvents.trigger(ADDON_MOD_WORKSHOP_ASSESSMENT_INVALIDATED, null, this.siteId); await this.fetchAssessmentData(); } @@ -396,7 +399,7 @@ export class AddonModWorkshopAssessmentPage implements OnInit, OnDestroy, CanLea }; return AddonModWorkshop.invalidateAssessmentData(this.workshopId, this.assessmentId).finally(() => { - CoreEvents.trigger(AddonModWorkshopProvider.ASSESSMENT_SAVED, data, this.siteId); + CoreEvents.trigger(ADDON_MOD_WORKSHOP_ASSESSMENT_SAVED, data, this.siteId); }); } catch (error) { CoreDomUtils.showErrorModalDefault(error, 'Cannot save assessment evaluation'); diff --git a/src/addons/mod/workshop/pages/edit-submission/edit-submission.ts b/src/addons/mod/workshop/pages/edit-submission/edit-submission.ts index 5d7b73734..26a5a40b7 100644 --- a/src/addons/mod/workshop/pages/edit-submission/edit-submission.ts +++ b/src/addons/mod/workshop/pages/edit-submission/edit-submission.ts @@ -30,18 +30,20 @@ import { Translate } from '@singletons'; import { CoreEvents } from '@singletons/events'; import { CoreForms } from '@singletons/form'; import { - AddonModWorkshopProvider, AddonModWorkshop, - AddonModWorkshopSubmissionType, AddonModWorkshopSubmissionChangedEventData, - AddonModWorkshopAction, AddonModWorkshopGetWorkshopAccessInformationWSResponse, AddonModWorkshopData, } from '../../services/workshop'; import { AddonModWorkshopHelper, AddonModWorkshopSubmissionDataWithOfflineData } from '../../services/workshop-helper'; import { AddonModWorkshopOffline } from '../../services/workshop-offline'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; -import { ADDON_MOD_WORKSHOP_COMPONENT } from '@addons/mod/workshop/constants'; +import { + ADDON_MOD_WORKSHOP_COMPONENT, + ADDON_MOD_WORKSHOP_SUBMISSION_CHANGED, + AddonModWorkshopAction, + AddonModWorkshopSubmissionType, +} from '@addons/mod/workshop/constants'; /** * Page that displays the workshop edit submission. @@ -473,7 +475,7 @@ export class AddonModWorkshopEditSubmissionPage implements OnInit, OnDestroy, Ca Promise.resolve(); await promise.finally(() => { - CoreEvents.trigger(AddonModWorkshopProvider.SUBMISSION_CHANGED, data, this.siteId); + CoreEvents.trigger(ADDON_MOD_WORKSHOP_SUBMISSION_CHANGED, data, this.siteId); // Delete the local files from the tmp folder. CoreFileUploader.clearTmpFiles(inputData.attachmentfiles); diff --git a/src/addons/mod/workshop/pages/submission/submission.ts b/src/addons/mod/workshop/pages/submission/submission.ts index 08fda91ba..ba743b49b 100644 --- a/src/addons/mod/workshop/pages/submission/submission.ts +++ b/src/addons/mod/workshop/pages/submission/submission.ts @@ -31,11 +31,8 @@ import { CoreEventObserver, CoreEvents } from '@singletons/events'; import { CoreForms } from '@singletons/form'; import { AddonModWorkshopAssessmentStrategyComponent } from '../../components/assessment-strategy/assessment-strategy'; import { - AddonModWorkshopProvider, AddonModWorkshop, - AddonModWorkshopPhase, AddonModWorkshopSubmissionChangedEventData, - AddonModWorkshopAction, AddonModWorkshopData, AddonModWorkshopGetWorkshopAccessInformationWSResponse, AddonModWorkshopAssessmentSavedChangedEventData, @@ -46,10 +43,18 @@ import { AddonModWorkshopSubmissionDataWithOfflineData, } from '../../services/workshop-helper'; import { AddonModWorkshopOffline } from '../../services/workshop-offline'; -import { AddonModWorkshopSyncProvider, AddonModWorkshopAutoSyncData } from '../../services/workshop-sync'; +import { AddonModWorkshopAutoSyncData } from '../../services/workshop-sync'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; import { CoreTime } from '@singletons/time'; -import { ADDON_MOD_WORKSHOP_COMPONENT } from '@addons/mod/workshop/constants'; +import { + ADDON_MOD_WORKSHOP_ASSESSMENT_INVALIDATED, + ADDON_MOD_WORKSHOP_ASSESSMENT_SAVED, + ADDON_MOD_WORKSHOP_AUTO_SYNCED, + ADDON_MOD_WORKSHOP_COMPONENT, + ADDON_MOD_WORKSHOP_SUBMISSION_CHANGED, + AddonModWorkshopAction, + AddonModWorkshopPhase, +} from '@addons/mod/workshop/constants'; /** * Page that displays a workshop submission. @@ -119,12 +124,12 @@ export class AddonModWorkshopSubmissionPage implements OnInit, OnDestroy, CanLea this.feedbackForm.addControl('grade', this.fb.control('')); this.feedbackForm.addControl('text', this.fb.control('')); - this.obsAssessmentSaved = CoreEvents.on(AddonModWorkshopProvider.ASSESSMENT_SAVED, (data) => { + this.obsAssessmentSaved = CoreEvents.on(ADDON_MOD_WORKSHOP_ASSESSMENT_SAVED, (data) => { this.eventReceived(data); }, this.siteId); // Refresh workshop on sync. - this.syncObserver = CoreEvents.on(AddonModWorkshopSyncProvider.AUTO_SYNCED, (data) => { + this.syncObserver = CoreEvents.on(ADDON_MOD_WORKSHOP_AUTO_SYNCED, (data) => { // Update just when all database is synced. this.eventReceived(data); }, this.siteId); @@ -447,7 +452,7 @@ export class AddonModWorkshopSubmissionPage implements OnInit, OnDestroy, CanLea try { await Promise.all(promises); } finally { - CoreEvents.trigger(AddonModWorkshopProvider.ASSESSMENT_INVALIDATED, null, this.siteId); + CoreEvents.trigger(ADDON_MOD_WORKSHOP_ASSESSMENT_INVALIDATED, null, this.siteId); await this.fetchSubmissionData(); @@ -535,7 +540,7 @@ export class AddonModWorkshopSubmissionPage implements OnInit, OnDestroy, CanLea submissionId: this.submissionId, }; - CoreEvents.trigger(AddonModWorkshopProvider.SUBMISSION_CHANGED, data, this.siteId); + CoreEvents.trigger(ADDON_MOD_WORKSHOP_SUBMISSION_CHANGED, data, this.siteId); }); } catch (message) { CoreDomUtils.showErrorModalDefault(message, 'Cannot save submission evaluation'); @@ -572,7 +577,7 @@ export class AddonModWorkshopSubmissionPage implements OnInit, OnDestroy, CanLea submissionId: this.submissionId, }; - CoreEvents.trigger(AddonModWorkshopProvider.SUBMISSION_CHANGED, data, this.siteId); + CoreEvents.trigger(ADDON_MOD_WORKSHOP_SUBMISSION_CHANGED, data, this.siteId); this.forceLeavePage(); } @@ -595,7 +600,7 @@ export class AddonModWorkshopSubmissionPage implements OnInit, OnDestroy, CanLea submissionId: this.submissionId, }; - CoreEvents.trigger(AddonModWorkshopProvider.SUBMISSION_CHANGED, data, this.siteId); + CoreEvents.trigger(ADDON_MOD_WORKSHOP_SUBMISSION_CHANGED, data, this.siteId); await this.refreshAllData(); }); diff --git a/src/addons/mod/workshop/services/database/workshop.ts b/src/addons/mod/workshop/services/database/workshop.ts index 346f168c2..b3f3ed5a4 100644 --- a/src/addons/mod/workshop/services/database/workshop.ts +++ b/src/addons/mod/workshop/services/database/workshop.ts @@ -13,7 +13,7 @@ // limitations under the License. import { CoreSiteSchema } from '@services/sites'; -import { AddonModWorkshopAction } from '../workshop'; +import { AddonModWorkshopAction } from '../../constants'; /** * Database variables for AddonModWorkshopOfflineProvider. diff --git a/src/addons/mod/workshop/services/handlers/prefetch-lazy.ts b/src/addons/mod/workshop/services/handlers/prefetch-lazy.ts index b48227563..0e69b40aa 100644 --- a/src/addons/mod/workshop/services/handlers/prefetch-lazy.ts +++ b/src/addons/mod/workshop/services/handlers/prefetch-lazy.ts @@ -25,7 +25,6 @@ import { CoreWSExternalFile, CoreWSFile } from '@services/ws'; import { makeSingleton } from '@singletons'; import { AddonModWorkshop, - AddonModWorkshopPhase, AddonModWorkshopGradesData, AddonModWorkshopData, AddonModWorkshopGetWorkshopAccessInformationWSResponse, @@ -33,6 +32,7 @@ import { import { AddonModWorkshopHelper } from '../workshop-helper'; import { AddonModWorkshopSync } from '../workshop-sync'; import { AddonModWorkshopPrefetchHandlerService } from '@addons/mod/workshop/services/handlers/prefetch'; +import { AddonModWorkshopPhase } from '../../constants'; /** * Handler to prefetch workshops. diff --git a/src/addons/mod/workshop/services/workshop-helper.ts b/src/addons/mod/workshop/services/workshop-helper.ts index 898ab0166..7dec857eb 100644 --- a/src/addons/mod/workshop/services/workshop-helper.ts +++ b/src/addons/mod/workshop/services/workshop-helper.ts @@ -26,8 +26,6 @@ import { CoreFormFields } from '@singletons/form'; import { AddonModWorkshopAssessmentStrategyFieldErrors } from '../components/assessment-strategy/assessment-strategy'; import { AddonWorkshopAssessmentStrategyDelegate } from './assessment-strategy-delegate'; import { - AddonModWorkshopExampleMode, - AddonModWorkshopPhase, AddonModWorkshopUserOptions, AddonModWorkshopData, AddonModWorkshop, @@ -36,12 +34,16 @@ import { AddonModWorkshopPhaseTaskData, AddonModWorkshopSubmissionAssessmentData, AddonModWorkshopGetAssessmentFormDefinitionData, - AddonModWorkshopAction, - AddonModWorkshopOverallFeedbackMode, AddonModWorkshopGetAssessmentFormFieldsParsedData, } from './workshop'; import { AddonModWorkshopOffline, AddonModWorkshopOfflineSubmission } from './workshop-offline'; -import { ADDON_MOD_WORKSHOP_COMPONENT } from '@addons/mod/workshop/constants'; +import { + ADDON_MOD_WORKSHOP_COMPONENT, + AddonModWorkshopAction, + AddonModWorkshopExampleMode, + AddonModWorkshopOverallFeedbackMode, + AddonModWorkshopPhase, +} from '@addons/mod/workshop/constants'; /** * Helper to gather some common functions for workshop. diff --git a/src/addons/mod/workshop/services/workshop-offline.ts b/src/addons/mod/workshop/services/workshop-offline.ts index 370da3e28..c88c06e68 100644 --- a/src/addons/mod/workshop/services/workshop-offline.ts +++ b/src/addons/mod/workshop/services/workshop-offline.ts @@ -31,7 +31,7 @@ import { EVALUATE_SUBMISSIONS_TABLE, SUBMISSIONS_TABLE, } from './database/workshop'; -import { AddonModWorkshopAction } from './workshop'; +import { AddonModWorkshopAction } from '../constants'; /** * Service to handle offline workshop. diff --git a/src/addons/mod/workshop/services/workshop-sync.ts b/src/addons/mod/workshop/services/workshop-sync.ts index ea7495a7e..a666badd4 100644 --- a/src/addons/mod/workshop/services/workshop-sync.ts +++ b/src/addons/mod/workshop/services/workshop-sync.ts @@ -26,9 +26,7 @@ import { CoreUtils } from '@services/utils/utils'; import { Translate, makeSingleton } from '@singletons'; import { CoreEvents } from '@singletons/events'; import { AddonModWorkshop, - AddonModWorkshopAction, AddonModWorkshopData, - AddonModWorkshopSubmissionType, } from './workshop'; import { AddonModWorkshopHelper } from './workshop-helper'; import { AddonModWorkshopOffline, @@ -37,7 +35,12 @@ import { AddonModWorkshopOffline, AddonModWorkshopOfflineEvaluateSubmission, AddonModWorkshopOfflineSubmission, } from './workshop-offline'; -import { ADDON_MOD_WORKSHOP_COMPONENT } from '@addons/mod/workshop/constants'; +import { + ADDON_MOD_WORKSHOP_AUTO_SYNCED, + ADDON_MOD_WORKSHOP_COMPONENT, + AddonModWorkshopAction, + AddonModWorkshopSubmissionType, +} from '@addons/mod/workshop/constants'; /** * Service to sync workshops. @@ -45,9 +48,6 @@ import { ADDON_MOD_WORKSHOP_COMPONENT } from '@addons/mod/workshop/constants'; @Injectable({ providedIn: 'root' }) export class AddonModWorkshopSyncProvider extends CoreSyncBaseProvider { - static readonly AUTO_SYNCED = 'addon_mod_workshop_autom_synced'; - static readonly MANUAL_SYNCED = 'addon_mod_workshop_manual_synced'; - protected componentTranslatableString = 'workshop'; constructor() { @@ -94,7 +94,7 @@ export class AddonModWorkshopSyncProvider extends CoreSyncBaseProvider { options.page = options.page ?? 0; - options.perPage = options.perPage ?? AddonModWorkshopProvider.PER_PAGE; + options.perPage = options.perPage ?? ADDON_MOD_WORKSHOP_PER_PAGE; const report = await this.getGradesReport(workshopId, options); @@ -1933,7 +1903,7 @@ export type AddonModWorkshopGetSubmissionsOptions = AddonModWorkshopUserOptions * Options to pass to fetchAllGradeReports. */ export type AddonModWorkshopFetchAllGradesReportOptions = AddonModWorkshopGroupOptions & { - perPage?: number; // Records per page to return. Default AddonModWorkshopProvider.PER_PAGE. + perPage?: number; // Records per page to return. Default ADDON_MOD_WORKSHOP_PER_PAGE. }; /** diff --git a/src/addons/mod/workshop/workshop-lazy.module.ts b/src/addons/mod/workshop/workshop-lazy.module.ts index a49cddae5..1e7f038af 100644 --- a/src/addons/mod/workshop/workshop-lazy.module.ts +++ b/src/addons/mod/workshop/workshop-lazy.module.ts @@ -60,4 +60,4 @@ const routes: Routes = [ AddonModWorkshopEditSubmissionPage, ], }) -export class AddonModWorkshopLazyModule {} +export default class AddonModWorkshopLazyModule {} diff --git a/src/addons/mod/workshop/workshop.module.ts b/src/addons/mod/workshop/workshop.module.ts index 6bc3fabb6..63653ee8f 100644 --- a/src/addons/mod/workshop/workshop.module.ts +++ b/src/addons/mod/workshop/workshop.module.ts @@ -66,7 +66,7 @@ export async function getModWorkshopComponentModules(): Promise { const routes: Routes = [ { path: ADDON_MOD_WORKSHOP_PAGE_NAME, - loadChildren: () => import('./workshop-lazy.module').then(m => m.AddonModWorkshopLazyModule), + loadChildren: () => import('./workshop-lazy.module'), }, ]; From c2caa151751b9bfdbf423ddad4d729f4e83801c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Thu, 11 Jul 2024 22:43:36 +0200 Subject: [PATCH 17/26] MOBILE-4616 url: Move url constants to a file --- src/addons/mod/url/services/url.ts | 1 - src/addons/mod/url/url-lazy.module.ts | 2 +- src/addons/mod/url/url.module.ts | 2 +- 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/addons/mod/url/services/url.ts b/src/addons/mod/url/services/url.ts index 80825678b..cec979f77 100644 --- a/src/addons/mod/url/services/url.ts +++ b/src/addons/mod/url/services/url.ts @@ -33,7 +33,6 @@ import { ADDON_MOD_URL_COMPONENT } from '../constants'; export class AddonModUrlProvider { protected static readonly ROOT_CACHE_KEY = 'mmaModUrl:'; - static readonly COMPONENT = ADDON_MOD_URL_COMPONENT; /** * Get the final display type for a certain URL. Based on Moodle's url_get_final_display_type. diff --git a/src/addons/mod/url/url-lazy.module.ts b/src/addons/mod/url/url-lazy.module.ts index b6f4141c7..3fa447aff 100644 --- a/src/addons/mod/url/url-lazy.module.ts +++ b/src/addons/mod/url/url-lazy.module.ts @@ -35,4 +35,4 @@ const routes: Routes = [ AddonModUrlIndexPage, ], }) -export class AddonModUrlLazyModule {} +export default class AddonModUrlLazyModule {} diff --git a/src/addons/mod/url/url.module.ts b/src/addons/mod/url/url.module.ts index 2699d006b..563daf9c4 100644 --- a/src/addons/mod/url/url.module.ts +++ b/src/addons/mod/url/url.module.ts @@ -27,7 +27,7 @@ import { ADDON_MOD_URL_PAGE_NAME } from './constants'; const routes: Routes = [ { path: ADDON_MOD_URL_PAGE_NAME, - loadChildren: () => import('./url-lazy.module').then(m => m.AddonModUrlLazyModule), + loadChildren: () => import('./url-lazy.module'), }, ]; From c0856c0c970ca4b264920b667d029e950eda08d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Thu, 11 Jul 2024 22:43:55 +0200 Subject: [PATCH 18/26] MOBILE-4616 scorm: Move scorm constants to a file --- src/addons/mod/scorm/classes/data-model-12.ts | 30 ++-- .../mod/scorm/components/index/index.ts | 30 ++-- src/addons/mod/scorm/components/toc/toc.ts | 7 +- src/addons/mod/scorm/constants.ts | 67 ++++++++ src/addons/mod/scorm/pages/player/player.ts | 25 ++- src/addons/mod/scorm/scorm-lazy.module.ts | 2 +- src/addons/mod/scorm/scorm.module.ts | 10 +- .../mod/scorm/services/handlers/module.ts | 5 +- .../mod/scorm/services/handlers/prefetch.ts | 5 +- src/addons/mod/scorm/services/scorm-helper.ts | 6 +- .../mod/scorm/services/scorm-offline.ts | 14 +- src/addons/mod/scorm/services/scorm-sync.ts | 12 +- src/addons/mod/scorm/services/scorm.ts | 154 ++++++++---------- 13 files changed, 217 insertions(+), 150 deletions(-) create mode 100644 src/addons/mod/scorm/constants.ts diff --git a/src/addons/mod/scorm/classes/data-model-12.ts b/src/addons/mod/scorm/classes/data-model-12.ts index 3be16edf6..9e1bfa443 100644 --- a/src/addons/mod/scorm/classes/data-model-12.ts +++ b/src/addons/mod/scorm/classes/data-model-12.ts @@ -19,10 +19,16 @@ import { AddonModScormCommonEventData, AddonModScormDataEntry, AddonModScormDataValue, - AddonModScormProvider, AddonModScormScorm, AddonModScormUserDataMap, } from '../services/scorm'; +import { + ADDON_MOD_SCORM_UPDATE_TOC_EVENT, + ADDON_MOD_SCORM_LAUNCH_NEXT_SCO_EVENT, + ADDON_MOD_SCORM_LAUNCH_PREV_SCO_EVENT, + ADDON_MOD_SCORM_GO_OFFLINE_EVENT, + AddonModScormMode, +} from '../constants'; // Standard Data Type Definition. let CMI_STRING_256 = '^[\\u0000-\\uFFFF]{0,255}$'; @@ -110,7 +116,7 @@ export class AddonModScormDataModel12 { protected scoId: number, protected attempt: number, protected userData: AddonModScormUserDataMap, - protected mode = AddonModScormProvider.MODENORMAL, + protected mode = AddonModScormMode.NORMAL, protected offline = false, protected canSaveTracks = true, ) { @@ -595,7 +601,7 @@ export class AddonModScormDataModel12 { } // Define mode and credit. - this.currentUserData[scoId].userdata['cmi.core.credit'] = this.mode == AddonModScormProvider.MODENORMAL ? + this.currentUserData[scoId].userdata['cmi.core.credit'] = this.mode === AddonModScormMode.NORMAL ? 'credit' : 'no-credit'; this.currentUserData[scoId].userdata['cmi.core.lesson_mode'] = this.mode; @@ -620,7 +626,7 @@ export class AddonModScormDataModel12 { const result = this.storeData(false); // Trigger TOC update. - this.triggerEvent(AddonModScormProvider.UPDATE_TOC_EVENT); + this.triggerEvent(ADDON_MOD_SCORM_UPDATE_TOC_EVENT); this.errorCode = result ? '0' : '101'; @@ -652,20 +658,20 @@ export class AddonModScormDataModel12 { const result = this.storeData(true); if (this.getEl('nav.event') != '') { if (this.getEl('nav.event') == 'continue') { - this.triggerEvent(AddonModScormProvider.LAUNCH_NEXT_SCO_EVENT); + this.triggerEvent(ADDON_MOD_SCORM_LAUNCH_NEXT_SCO_EVENT); } else { - this.triggerEvent(AddonModScormProvider.LAUNCH_PREV_SCO_EVENT); + this.triggerEvent(ADDON_MOD_SCORM_LAUNCH_PREV_SCO_EVENT); } } else { if (this.scorm.auto) { - this.triggerEvent(AddonModScormProvider.LAUNCH_NEXT_SCO_EVENT); + this.triggerEvent(ADDON_MOD_SCORM_LAUNCH_NEXT_SCO_EVENT); } } this.errorCode = result ? '0' : '101'; // Trigger TOC update. - this.triggerEvent(AddonModScormProvider.UPDATE_TOC_EVENT); + this.triggerEvent(ADDON_MOD_SCORM_UPDATE_TOC_EVENT); // Conver to string representing a boolean. return result ? 'true' : 'false'; @@ -986,8 +992,8 @@ export class AddonModScormDataModel12 { this.setEl('cmi.core.lesson_status', 'completed'); } - if (this.getEl('cmi.core.lesson_mode') == AddonModScormProvider.MODENORMAL) { - if (this.getEl('cmi.core.credit') == 'credit') { + if (this.getEl('cmi.core.lesson_mode') === AddonModScormMode.NORMAL) { + if (this.getEl('cmi.core.credit') === 'credit') { if (this.getEl('cmi.student_data.mastery_score') !== '' && this.getEl('cmi.core.score.raw') !== '') { if (parseFloat( this.getEl('cmi.core.score.raw')) >= parseFloat( this.getEl('cmi.student_data.mastery_score'))) { @@ -999,7 +1005,7 @@ export class AddonModScormDataModel12 { } } - if (this.getEl('cmi.core.lesson_mode') == AddonModScormProvider.MODEBROWSE) { + if (this.getEl('cmi.core.lesson_mode') === AddonModScormMode.BROWSE) { if (this.dataModel[this.scoId]['cmi.core.lesson_status'].defaultvalue == '' && this.getEl('cmi.core.lesson_status') == 'not attempted') { this.setEl('cmi.core.lesson_status', 'browsed'); @@ -1020,7 +1026,7 @@ export class AddonModScormDataModel12 { // Failure storing data in online. Go offline. this.offline = true; - this.triggerEvent(AddonModScormProvider.GO_OFFLINE_EVENT); + this.triggerEvent(ADDON_MOD_SCORM_GO_OFFLINE_EVENT); return AddonModScorm.saveTracksSync(this.scoId, this.attempt, tracks, this.scorm, this.offline, this.currentUserData); diff --git a/src/addons/mod/scorm/components/index/index.ts b/src/addons/mod/scorm/components/index/index.ts index 81154f711..4c8e7ee63 100644 --- a/src/addons/mod/scorm/components/index/index.ts +++ b/src/addons/mod/scorm/components/index/index.ts @@ -25,7 +25,6 @@ import { CoreDomUtils } from '@services/utils/dom'; import { CoreUtils } from '@services/utils/utils'; import { Translate } from '@singletons'; import { CoreEventObserver, CoreEvents } from '@singletons/events'; -import { AddonModScormModuleHandlerService } from '../../services/handlers/module'; import { AddonModScormPrefetchHandler } from '../../services/handlers/prefetch'; import { AddonModScorm, @@ -33,16 +32,23 @@ import { AddonModScormGetScormAccessInformationWSResponse, AddonModScormAttemptGrade, AddonModScormOrganization, - AddonModScormProvider, AddonModScormScorm, } from '../../services/scorm'; import { AddonModScormHelper, AddonModScormTOCScoWithIcon } from '../../services/scorm-helper'; import { AddonModScormAutoSyncEventData, AddonModScormSync, - AddonModScormSyncProvider, AddonModScormSyncResult, } from '../../services/scorm-sync'; +import { + ADDON_MOD_SCORM_COMPONENT, + AddonModScormForceAttempt, + AddonModScormMode, + AddonModScormSkipView, + ADDON_MOD_SCORM_DATA_SENT_EVENT, + ADDON_MOD_SCORM_DATA_AUTO_SYNCED, + ADDON_MOD_SCORM_PAGE_NAME, +} from '../../constants'; /** * Component that displays a SCORM entry page. @@ -56,7 +62,7 @@ export class AddonModScormIndexComponent extends CoreCourseModuleMainActivityCom @Input() autoPlayData?: AddonModScormAutoPlayData; // Data to use to play the SCORM automatically. - component = AddonModScormProvider.COMPONENT; + component = ADDON_MOD_SCORM_COMPONENT; pluginName = 'scorm'; scorm?: AddonModScormScorm; // The SCORM object. @@ -90,7 +96,7 @@ export class AddonModScormIndexComponent extends CoreCourseModuleMainActivityCom gradesExpanded = false; protected fetchContentDefaultError = 'addon.mod_scorm.errorgetscorm'; // Default error to show when loading contents. - protected syncEventName = AddonModScormSyncProvider.AUTO_SYNCED; + protected syncEventName = ADDON_MOD_SCORM_DATA_AUTO_SYNCED; protected attempts?: AddonModScormAttemptCountResult; // Data about online and offline attempts. protected lastAttempt?: number; // Last attempt. protected lastIsOffline = false; // Whether the last attempt is offline. @@ -201,8 +207,8 @@ export class AddonModScormIndexComponent extends CoreCourseModuleMainActivityCom || ( this.accessInfo.canskipview && !this.accessInfo.canviewreport && - (this.scorm.skipview ?? 0) >= AddonModScormProvider.SKIPVIEW_FIRST && - (this.scorm.skipview === AddonModScormProvider.SKIPVIEW_ALWAYS || this.lastAttempt === 0) + (this.scorm.skipview ?? 0) >= AddonModScormSkipView.FIRST && + (this.scorm.skipview === AddonModScormSkipView.ALWAYS || this.lastAttempt === 0) ) ); } @@ -241,7 +247,7 @@ export class AddonModScormIndexComponent extends CoreCourseModuleMainActivityCom this.gradeMethodReadable = AddonModScorm.getScormGradeMethod(scorm); this.attemptsLeft = AddonModScorm.countAttemptsLeft(scorm, this.attempts.lastAttempt.num); - if (scorm.forcenewattempt === AddonModScormProvider.SCORM_FORCEATTEMPT_ALWAYS || + if (scorm.forcenewattempt === AddonModScormForceAttempt.ALWAYS || (scorm.forcenewattempt && !this.incomplete)) { this.startNewAttempt = true; } @@ -550,7 +556,7 @@ export class AddonModScormIndexComponent extends CoreCourseModuleMainActivityCom // Detect if anything was sent to server. this.dataSentObserver?.off(); - this.dataSentObserver = CoreEvents.on(AddonModScormProvider.DATA_SENT_EVENT, (data) => { + this.dataSentObserver = CoreEvents.on(ADDON_MOD_SCORM_DATA_SENT_EVENT, (data) => { if (data.scormId === this.scorm?.id) { this.dataSent = true; @@ -562,10 +568,10 @@ export class AddonModScormIndexComponent extends CoreCourseModuleMainActivityCom }, this.siteId); CoreNavigator.navigateToSitePath( - `${AddonModScormModuleHandlerService.PAGE_NAME}/${this.courseId}/${this.module.id}/player`, + `${ADDON_MOD_SCORM_PAGE_NAME}/${this.courseId}/${this.module.id}/player`, { params: { - mode: autoPlayData?.mode ?? (preview ? AddonModScormProvider.MODEBROWSE : AddonModScormProvider.MODENORMAL), + mode: autoPlayData?.mode ?? (preview ? AddonModScormMode.BROWSE : AddonModScormMode.NORMAL), moduleUrl: this.module.url, newAttempt: autoPlayData?.newAttempt ?? this.startNewAttempt, organizationId: autoPlayData?.organizationId ?? this.currentOrganization.identifier, @@ -608,7 +614,7 @@ export class AddonModScormIndexComponent extends CoreCourseModuleMainActivityCom throw new CoreError('Cannot sync without a scorm.'); } - if (CoreSync.isBlocked(AddonModScormProvider.COMPONENT, this.scorm.id) && retries < 5) { + if (CoreSync.isBlocked(ADDON_MOD_SCORM_COMPONENT, this.scorm.id) && retries < 5) { // Sync is currently blocked, this can happen when SCORM player is left. Retry in a bit. await CoreUtils.wait(400); diff --git a/src/addons/mod/scorm/components/toc/toc.ts b/src/addons/mod/scorm/components/toc/toc.ts index 1d1ca3b47..d1b48186f 100644 --- a/src/addons/mod/scorm/components/toc/toc.ts +++ b/src/addons/mod/scorm/components/toc/toc.ts @@ -14,8 +14,9 @@ import { Component, Input, OnInit } from '@angular/core'; import { ModalController } from '@singletons'; -import { AddonModScormGetScormAccessInformationWSResponse, AddonModScormProvider } from '../../services/scorm'; +import { AddonModScormGetScormAccessInformationWSResponse } from '../../services/scorm'; import { AddonModScormTOCScoWithIcon } from '../../services/scorm-helper'; +import { AddonModScormMode } from '../../constants'; /** * Modal to display the TOC of a SCORM. @@ -41,8 +42,8 @@ export class AddonModScormTocComponent implements OnInit { * @inheritdoc */ ngOnInit(): void { - this.isBrowse = this.mode === AddonModScormProvider.MODEBROWSE; - this.isReview = this.mode === AddonModScormProvider.MODEREVIEW; + this.isBrowse = this.mode === AddonModScormMode.BROWSE; + this.isReview = this.mode === AddonModScormMode.REVIEW; } /** diff --git a/src/addons/mod/scorm/constants.ts b/src/addons/mod/scorm/constants.ts new file mode 100644 index 000000000..c7d73f0a9 --- /dev/null +++ b/src/addons/mod/scorm/constants.ts @@ -0,0 +1,67 @@ +// (C) Copyright 2015 Moodle Pty Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export const ADDON_MOD_SCORM_COMPONENT = 'mmaModScorm'; +export const ADDON_MOD_SCORM_PAGE_NAME = 'mod_scorm'; + +// Public constants. + +/** + * Grading method. + * The grading method defines how the grade for a single attempt of the activity is determined. + */ +export const enum AddonModScormGradingMethod { + GRADESCOES = 0, + GRADEHIGHEST = 1, + GRADEAVERAGE = 2, + GRADESUM = 3, +} + +/** + * Attempts grading methods. + * If multiple attempts are allowed, this setting specifies whether the highest, average (mean), first or last completed attempt + * is recorded in the gradebook. + */ +export const enum AddonModScormAttemptsGradingMethod { + HIGHESTATTEMPT = 0, + AVERAGEATTEMPT = 1, + FIRSTATTEMPT = 2, + LASTATTEMPT = 3, +} + +export const enum AddonModScormMode { + BROWSE = 'browse', + NORMAL = 'normal', + REVIEW = 'review', +} + +export const enum AddonModScormForceAttempt { + NO = 0, + ONCOMPLETE = 1, + ALWAYS = 2, +} + +export const enum AddonModScormSkipView { + NEVER = 0, + FIRST = 1, + ALWAYS = 2, +} + +// Events. +export const ADDON_MOD_SCORM_LAUNCH_NEXT_SCO_EVENT = 'addon_mod_scorm_launch_next_sco'; +export const ADDON_MOD_SCORM_LAUNCH_PREV_SCO_EVENT = 'addon_mod_scorm_launch_prev_sco'; +export const ADDON_MOD_SCORM_UPDATE_TOC_EVENT = 'addon_mod_scorm_update_toc'; +export const ADDON_MOD_SCORM_GO_OFFLINE_EVENT = 'addon_mod_scorm_go_offline'; +export const ADDON_MOD_SCORM_DATA_SENT_EVENT = 'addon_mod_scorm_data_sent'; +export const ADDON_MOD_SCORM_DATA_AUTO_SYNCED = 'addon_mod_scorm_autom_synced'; diff --git a/src/addons/mod/scorm/pages/player/player.ts b/src/addons/mod/scorm/pages/player/player.ts index f98f6547e..be6162944 100644 --- a/src/addons/mod/scorm/pages/player/player.ts +++ b/src/addons/mod/scorm/pages/player/player.ts @@ -28,7 +28,6 @@ import { AddonModScorm, AddonModScormAttemptCountResult, AddonModScormGetScormAccessInformationWSResponse, - AddonModScormProvider, AddonModScormScorm, AddonModScormScoWithData, AddonModScormUserDataMap, @@ -36,6 +35,14 @@ import { import { AddonModScormHelper, AddonModScormTOCScoWithIcon } from '../../services/scorm-helper'; import { AddonModScormSync } from '../../services/scorm-sync'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; +import { + ADDON_MOD_SCORM_COMPONENT, + AddonModScormMode, + ADDON_MOD_SCORM_GO_OFFLINE_EVENT, + ADDON_MOD_SCORM_LAUNCH_NEXT_SCO_EVENT, + ADDON_MOD_SCORM_LAUNCH_PREV_SCO_EVENT, + ADDON_MOD_SCORM_UPDATE_TOC_EVENT, +} from '../../constants'; /** * Page that allows playing a SCORM. @@ -63,7 +70,7 @@ export class AddonModScormPlayerPage implements OnInit, OnDestroy { navigationItems: CoreNavigationBarItem[] = []; protected siteId!: string; - protected mode!: string; // Mode to play the SCORM. + protected mode!: AddonModScormMode; // Mode to play the SCORM. protected moduleUrl!: string; // Module URL. protected newAttempt = false; // Whether to start a new attempt. protected organizationId?: string; // Organization ID to load. @@ -92,7 +99,7 @@ export class AddonModScormPlayerPage implements OnInit, OnDestroy { try { this.cmId = CoreNavigator.getRequiredRouteNumberParam('cmId'); this.courseId = CoreNavigator.getRequiredRouteNumberParam('courseId'); - this.mode = CoreNavigator.getRouteParam('mode') || AddonModScormProvider.MODENORMAL; + this.mode = CoreNavigator.getRouteParam('mode') || AddonModScormMode.NORMAL; this.moduleUrl = CoreNavigator.getRouteParam('moduleUrl') || ''; this.newAttempt = !!CoreNavigator.getRouteBooleanParam('newAttempt'); this.organizationId = CoreNavigator.getRouteParam('organizationId'); @@ -150,7 +157,7 @@ export class AddonModScormPlayerPage implements OnInit, OnDestroy { }); // Block the SCORM so it cannot be synchronized. - CoreSync.blockOperation(AddonModScormProvider.COMPONENT, this.scorm.id, 'player'); + CoreSync.blockOperation(ADDON_MOD_SCORM_COMPONENT, this.scorm.id, 'player'); // We use SCORM name at start, later we'll use the SCO title. this.title = this.scorm.name; @@ -169,7 +176,7 @@ export class AddonModScormPlayerPage implements OnInit, OnDestroy { } // Listen for events to update the TOC, navigate through SCOs and go offline. - this.tocObserver = CoreEvents.on(AddonModScormProvider.UPDATE_TOC_EVENT, (data) => { + this.tocObserver = CoreEvents.on(ADDON_MOD_SCORM_UPDATE_TOC_EVENT, (data) => { if (data.scormId !== this.scorm.id) { return; } @@ -182,7 +189,7 @@ export class AddonModScormPlayerPage implements OnInit, OnDestroy { } }, this.siteId); - this.launchNextObserver = CoreEvents.on(AddonModScormProvider.LAUNCH_NEXT_SCO_EVENT, (data) => { + this.launchNextObserver = CoreEvents.on(ADDON_MOD_SCORM_LAUNCH_NEXT_SCO_EVENT, (data) => { if (data.scormId === this.scorm.id && this.currentSco) { const nextSco = AddonModScormHelper.getNextScoFromToc(this.toc, this.currentSco.id); if (nextSco) { @@ -191,7 +198,7 @@ export class AddonModScormPlayerPage implements OnInit, OnDestroy { } }, this.siteId); - this.launchPrevObserver = CoreEvents.on(AddonModScormProvider.LAUNCH_PREV_SCO_EVENT, (data) => { + this.launchPrevObserver = CoreEvents.on(ADDON_MOD_SCORM_LAUNCH_PREV_SCO_EVENT, (data) => { if (data.scormId === this.scorm.id && this.currentSco) { const previousSco = AddonModScormHelper.getPreviousScoFromToc(this.toc, this.currentSco.id); if (previousSco) { @@ -200,7 +207,7 @@ export class AddonModScormPlayerPage implements OnInit, OnDestroy { } }, this.siteId); - this.goOfflineObserver = CoreEvents.on(AddonModScormProvider.GO_OFFLINE_EVENT, (data) => { + this.goOfflineObserver = CoreEvents.on(ADDON_MOD_SCORM_GO_OFFLINE_EVENT, (data) => { if (data.scormId !== this.scorm.id || this.offline) { return; } @@ -605,7 +612,7 @@ export class AddonModScormPlayerPage implements OnInit, OnDestroy { }, 500); // Unblock the SCORM so it can be synced. - CoreSync.unblockOperation(AddonModScormProvider.COMPONENT, this.scorm.id, 'player'); + CoreSync.unblockOperation(ADDON_MOD_SCORM_COMPONENT, this.scorm.id, 'player'); } } diff --git a/src/addons/mod/scorm/scorm-lazy.module.ts b/src/addons/mod/scorm/scorm-lazy.module.ts index a0e05b611..cc234484c 100644 --- a/src/addons/mod/scorm/scorm-lazy.module.ts +++ b/src/addons/mod/scorm/scorm-lazy.module.ts @@ -42,4 +42,4 @@ const routes: Routes = [ AddonModScormPlayerPage, ], }) -export class AddonModScormLazyModule {} +export default class AddonModScormLazyModule {} diff --git a/src/addons/mod/scorm/scorm.module.ts b/src/addons/mod/scorm/scorm.module.ts index 559edea16..a66b61e2c 100644 --- a/src/addons/mod/scorm/scorm.module.ts +++ b/src/addons/mod/scorm/scorm.module.ts @@ -26,17 +26,17 @@ import { OFFLINE_SITE_SCHEMA } from './services/database/scorm'; import { AddonModScormGradeLinkHandler } from './services/handlers/grade-link'; import { AddonModScormIndexLinkHandler } from './services/handlers/index-link'; import { AddonModScormListLinkHandler } from './services/handlers/list-link'; -import { AddonModScormModuleHandler, AddonModScormModuleHandlerService } from './services/handlers/module'; +import { AddonModScormModuleHandler } from './services/handlers/module'; import { AddonModScormPlayerLinkHandler } from './services/handlers/player-link'; import { AddonModScormPluginFileHandler } from './services/handlers/pluginfile'; import { AddonModScormPrefetchHandler } from './services/handlers/prefetch'; import { AddonModScormSyncCronHandler } from './services/handlers/sync-cron'; -import { AddonModScormProvider } from './services/scorm'; +import { ADDON_MOD_SCORM_COMPONENT, ADDON_MOD_SCORM_PAGE_NAME } from './constants'; const routes: Routes = [ { - path: AddonModScormModuleHandlerService.PAGE_NAME, - loadChildren: () => import('./scorm-lazy.module').then(m => m.AddonModScormLazyModule), + path: ADDON_MOD_SCORM_PAGE_NAME, + loadChildren: () => import('./scorm-lazy.module'), }, ]; @@ -63,7 +63,7 @@ const routes: Routes = [ CoreContentLinksDelegate.registerHandler(AddonModScormPlayerLinkHandler.instance); CorePluginFileDelegate.registerHandler(AddonModScormPluginFileHandler.instance); - CoreCourseHelper.registerModuleReminderClick(AddonModScormProvider.COMPONENT); + CoreCourseHelper.registerModuleReminderClick(ADDON_MOD_SCORM_COMPONENT); }, }, ], diff --git a/src/addons/mod/scorm/services/handlers/module.ts b/src/addons/mod/scorm/services/handlers/module.ts index 6c4f03061..ad1bb5869 100644 --- a/src/addons/mod/scorm/services/handlers/module.ts +++ b/src/addons/mod/scorm/services/handlers/module.ts @@ -17,6 +17,7 @@ import { Injectable, Type } from '@angular/core'; import { CoreModuleHandlerBase } from '@features/course/classes/module-base-handler'; import { CoreCourseModuleHandler } from '@features/course/services/module-delegate'; import { makeSingleton } from '@singletons'; +import { ADDON_MOD_SCORM_PAGE_NAME } from '../../constants'; /** * Handler to support SCORM modules. @@ -24,11 +25,9 @@ import { makeSingleton } from '@singletons'; @Injectable({ providedIn: 'root' }) export class AddonModScormModuleHandlerService extends CoreModuleHandlerBase implements CoreCourseModuleHandler { - static readonly PAGE_NAME = 'mod_scorm'; - name = 'AddonModScorm'; modName = 'scorm'; - protected pageName = AddonModScormModuleHandlerService.PAGE_NAME; + protected pageName = ADDON_MOD_SCORM_PAGE_NAME; supportedFeatures = { [CoreConstants.FEATURE_GROUPS]: true, diff --git a/src/addons/mod/scorm/services/handlers/prefetch.ts b/src/addons/mod/scorm/services/handlers/prefetch.ts index c283e1520..eb5b03f81 100644 --- a/src/addons/mod/scorm/services/handlers/prefetch.ts +++ b/src/addons/mod/scorm/services/handlers/prefetch.ts @@ -24,8 +24,9 @@ import { CoreSites, CoreSitesReadingStrategy } from '@services/sites'; import { CoreUtils } from '@services/utils/utils'; import { CoreWSFile } from '@services/ws'; import { makeSingleton, Translate } from '@singletons'; -import { AddonModScorm, AddonModScormProvider, AddonModScormScorm } from '../scorm'; +import { AddonModScorm, AddonModScormScorm } from '../scorm'; import { AddonModScormSync } from '../scorm-sync'; +import { ADDON_MOD_SCORM_COMPONENT } from '../../constants'; /** * Handler to prefetch SCORMs. @@ -35,7 +36,7 @@ export class AddonModScormPrefetchHandlerService extends CoreCourseActivityPrefe name = 'AddonModScorm'; modName = 'scorm'; - component = AddonModScormProvider.COMPONENT; + component = ADDON_MOD_SCORM_COMPONENT; updatesNames = /^configuration$|^.*files$|^tracks$/; /** diff --git a/src/addons/mod/scorm/services/scorm-helper.ts b/src/addons/mod/scorm/services/scorm-helper.ts index 552b4f373..2986d3b99 100644 --- a/src/addons/mod/scorm/services/scorm-helper.ts +++ b/src/addons/mod/scorm/services/scorm-helper.ts @@ -25,7 +25,6 @@ import { AddonModScormAttemptCountResult, AddonModScormDataValue, AddonModScormGetScosWithDataOptions, - AddonModScormProvider, AddonModScormScoIcon, AddonModScormScorm, AddonModScormScoWithData, @@ -33,6 +32,7 @@ import { AddonModScormUserDataMap, } from './scorm'; import { AddonModScormOffline } from './scorm-offline'; +import { AddonModScormMode } from '../constants'; // List of elements we want to ignore when copying attempts (they're calculated). const elementsToIgnore = [ @@ -229,8 +229,8 @@ export class AddonModScormHelperProvider { options: AddonModScormGetFirstScoOptions = {}, ): Promise { - const mode = options.mode || AddonModScormProvider.MODENORMAL; - const isNormalMode = mode === AddonModScormProvider.MODENORMAL; + const mode = options.mode || AddonModScormMode.NORMAL; + const isNormalMode = mode === AddonModScormMode.NORMAL; let scos = options.toc; if (!scos || !scos.length) { diff --git a/src/addons/mod/scorm/services/scorm-offline.ts b/src/addons/mod/scorm/services/scorm-offline.ts index 907b103ce..4fd951ce9 100644 --- a/src/addons/mod/scorm/services/scorm-offline.ts +++ b/src/addons/mod/scorm/services/scorm-offline.ts @@ -35,7 +35,6 @@ import { import { AddonModScormDataEntry, AddonModScormDataValue, - AddonModScormProvider, AddonModScormScorm, AddonModScormScoUserData, AddonModScormUserDataMap, @@ -45,6 +44,7 @@ import { lazyMap, LazyMap } from '@/core/utils/lazy-map'; import { asyncInstance, AsyncInstance } from '@/core/utils/async-instance'; import { CoreDatabaseTable } from '@classes/database/database-table'; import { CoreDatabaseCachingStrategy } from '@classes/database/database-table-proxy'; +import { ADDON_MOD_SCORM_COMPONENT } from '../constants'; /** * Service to handle offline SCORM. @@ -120,7 +120,7 @@ export class AddonModScormOfflineProvider { this.logger.debug(`Change attempt number from ${attempt} to ${newAttempt} in SCORM ${scormId}`); // Block the SCORM so it can't be synced. - CoreSync.blockOperation(AddonModScormProvider.COMPONENT, scormId, 'changeAttemptNumber', site.id); + CoreSync.blockOperation(ADDON_MOD_SCORM_COMPONENT, scormId, 'changeAttemptNumber', site.id); try { const currentAttemptConditions = { @@ -161,7 +161,7 @@ export class AddonModScormOfflineProvider { } } finally { // Unblock the SCORM. - CoreSync.unblockOperation(AddonModScormProvider.COMPONENT, scormId, 'changeAttemptNumber', site.id); + CoreSync.unblockOperation(ADDON_MOD_SCORM_COMPONENT, scormId, 'changeAttemptNumber', site.id); } } @@ -191,7 +191,7 @@ export class AddonModScormOfflineProvider { this.logger.debug(`Creating new offline attempt ${attempt} in SCORM ${scorm.id}`); // Block the SCORM so it can't be synced. - CoreSync.blockOperation(AddonModScormProvider.COMPONENT, scorm.id, 'createNewAttempt', site.id); + CoreSync.blockOperation(ADDON_MOD_SCORM_COMPONENT, scorm.id, 'createNewAttempt', site.id); // Create attempt in DB. const entry: AddonModScormAttemptDBRecord = { @@ -230,7 +230,7 @@ export class AddonModScormOfflineProvider { await Promise.all(promises); } finally { // Unblock the SCORM. - CoreSync.unblockOperation(AddonModScormProvider.COMPONENT, scorm.id, 'createNewAttempt', site.id); + CoreSync.unblockOperation(ADDON_MOD_SCORM_COMPONENT, scorm.id, 'createNewAttempt', site.id); } } @@ -872,7 +872,7 @@ export class AddonModScormOfflineProvider { userId = userId || site.getUserId(); // Block the SCORM so it can't be synced. - CoreSync.blockOperation(AddonModScormProvider.COMPONENT, scorm.id, 'saveTracksOffline', siteId); + CoreSync.blockOperation(ADDON_MOD_SCORM_COMPONENT, scorm.id, 'saveTracksOffline', siteId); try { // Insert all the tracks. @@ -889,7 +889,7 @@ export class AddonModScormOfflineProvider { ))); } finally { // Unblock the SCORM operation. - CoreSync.unblockOperation(AddonModScormProvider.COMPONENT, scorm.id, 'saveTracksOffline', siteId); + CoreSync.unblockOperation(ADDON_MOD_SCORM_COMPONENT, scorm.id, 'saveTracksOffline', siteId); } } diff --git a/src/addons/mod/scorm/services/scorm-sync.ts b/src/addons/mod/scorm/services/scorm-sync.ts index d7165a41b..3c8ae7bb7 100644 --- a/src/addons/mod/scorm/services/scorm-sync.ts +++ b/src/addons/mod/scorm/services/scorm-sync.ts @@ -27,11 +27,11 @@ import { AddonModScorm, AddonModScormAttemptCountResult, AddonModScormDataEntry, - AddonModScormProvider, AddonModScormScorm, AddonModScormUserDataMap, } from './scorm'; import { AddonModScormOffline } from './scorm-offline'; +import { ADDON_MOD_SCORM_COMPONENT, ADDON_MOD_SCORM_DATA_AUTO_SYNCED } from '../constants'; /** * Service to sync SCORMs. @@ -39,8 +39,6 @@ import { AddonModScormOffline } from './scorm-offline'; @Injectable({ providedIn: 'root' }) export class AddonModScormSyncProvider extends CoreCourseActivitySyncBaseProvider { - static readonly AUTO_SYNCED = 'addon_mod_scorm_autom_synced'; - protected componentTranslatableString = 'scorm'; constructor() { @@ -464,7 +462,7 @@ export class AddonModScormSyncProvider extends CoreCourseActivitySyncBaseProvide // Sync all SCORMs that haven't been synced for a while and that aren't attempted right now. await Promise.all(attempts.map(async (attempt) => { - if (treated[attempt.scormid] || CoreSync.isBlocked(AddonModScormProvider.COMPONENT, attempt.scormid, siteId)) { + if (treated[attempt.scormid] || CoreSync.isBlocked(ADDON_MOD_SCORM_COMPONENT, attempt.scormid, siteId)) { return; } @@ -478,7 +476,7 @@ export class AddonModScormSyncProvider extends CoreCourseActivitySyncBaseProvide if (data !== undefined) { // We tried to sync. Send event. - CoreEvents.trigger(AddonModScormSyncProvider.AUTO_SYNCED, { + CoreEvents.trigger(ADDON_MOD_SCORM_DATA_AUTO_SYNCED, { scormId: scorm.id, attemptFinished: data.attemptFinished, warnings: data.warnings, @@ -586,7 +584,7 @@ export class AddonModScormSyncProvider extends CoreCourseActivitySyncBaseProvide } // Verify that SCORM isn't blocked. - if (CoreSync.isBlocked(AddonModScormProvider.COMPONENT, scorm.id, siteId)) { + if (CoreSync.isBlocked(ADDON_MOD_SCORM_COMPONENT, scorm.id, siteId)) { this.logger.debug('Cannot sync SCORM ' + scorm.id + ' because it is blocked.'); throw new CoreError(Translate.instant('core.errorsyncblocked', { $a: this.componentTranslate })); @@ -612,7 +610,7 @@ export class AddonModScormSyncProvider extends CoreCourseActivitySyncBaseProvide let lastOnlineWasFinished = false; // Sync offline logs. - await CoreUtils.ignoreErrors(CoreCourseLogHelper.syncActivity(AddonModScormProvider.COMPONENT, scorm.id, siteId)); + await CoreUtils.ignoreErrors(CoreCourseLogHelper.syncActivity(ADDON_MOD_SCORM_COMPONENT, scorm.id, siteId)); // Get attempts data. We ignore cache for online attempts, so this call will fail if offline or server down. const attemptsData = await AddonModScorm.getAttemptCount(scorm.id, { diff --git a/src/addons/mod/scorm/services/scorm.ts b/src/addons/mod/scorm/services/scorm.ts index 9c89fcc76..927b59528 100644 --- a/src/addons/mod/scorm/services/scorm.ts +++ b/src/addons/mod/scorm/services/scorm.ts @@ -30,8 +30,21 @@ import { makeSingleton, Translate } from '@singletons'; import { CoreEvents } from '@singletons/events'; import { CorePath } from '@singletons/path'; import { AddonModScormOffline } from './scorm-offline'; -import { AddonModScormAutoSyncEventData, AddonModScormSyncProvider } from './scorm-sync'; +import { AddonModScormAutoSyncEventData } from './scorm-sync'; import { CoreSiteWSPreSets } from '@classes/sites/authenticated-site'; +import { + ADDON_MOD_SCORM_COMPONENT, + AddonModScormForceAttempt, + AddonModScormGradingMethod, + AddonModScormMode, + AddonModScormAttemptsGradingMethod, + ADDON_MOD_SCORM_DATA_SENT_EVENT, + ADDON_MOD_SCORM_GO_OFFLINE_EVENT, + ADDON_MOD_SCORM_LAUNCH_NEXT_SCO_EVENT, + ADDON_MOD_SCORM_LAUNCH_PREV_SCO_EVENT, + ADDON_MOD_SCORM_UPDATE_TOC_EVENT, + ADDON_MOD_SCORM_DATA_AUTO_SYNCED, +} from '../constants'; // Private constants. const VALID_STATUSES = ['notattempted', 'passed', 'completed', 'failed', 'incomplete', 'browsed', 'suspend']; @@ -65,7 +78,6 @@ const STATUS_TO_ICON = { suspend: 'fas-pause', wait: 'far-clock', }; -const ROOT_CACHE_KEY = 'mmaModScorm:'; /** * Service that provides some features for SCORM. @@ -73,37 +85,7 @@ const ROOT_CACHE_KEY = 'mmaModScorm:'; @Injectable({ providedIn: 'root' }) export class AddonModScormProvider { - static readonly COMPONENT = 'mmaModScorm'; - - // Public constants. - static readonly GRADESCOES = 0; - static readonly GRADEHIGHEST = 1; - static readonly GRADEAVERAGE = 2; - static readonly GRADESUM = 3; - - static readonly HIGHESTATTEMPT = 0; - static readonly AVERAGEATTEMPT = 1; - static readonly FIRSTATTEMPT = 2; - static readonly LASTATTEMPT = 3; - - static readonly MODEBROWSE = 'browse'; - static readonly MODENORMAL = 'normal'; - static readonly MODEREVIEW = 'review'; - - static readonly SCORM_FORCEATTEMPT_NO = 0; - static readonly SCORM_FORCEATTEMPT_ONCOMPLETE = 1; - static readonly SCORM_FORCEATTEMPT_ALWAYS = 2; - - static readonly SKIPVIEW_NEVER = 0; - static readonly SKIPVIEW_FIRST = 1; - static readonly SKIPVIEW_ALWAYS = 2; - - // Events. - static readonly LAUNCH_NEXT_SCO_EVENT = 'addon_mod_scorm_launch_next_sco'; - static readonly LAUNCH_PREV_SCO_EVENT = 'addon_mod_scorm_launch_prev_sco'; - static readonly UPDATE_TOC_EVENT = 'addon_mod_scorm_update_toc'; - static readonly GO_OFFLINE_EVENT = 'addon_mod_scorm_go_offline'; - static readonly DATA_SENT_EVENT = 'addon_mod_scorm_data_sent'; + protected static readonly ROOT_CACHE_KEY = 'mmaModScorm:'; /** * Calculates the SCORM grade based on the grading method and the list of attempts scores. @@ -119,10 +101,10 @@ export class AddonModScormProvider { } switch (scorm.whatgrade) { - case AddonModScormProvider.FIRSTATTEMPT: + case AddonModScormAttemptsGradingMethod.FIRSTATTEMPT: return onlineAttempts[1] ? onlineAttempts[1].score : -1; - case AddonModScormProvider.LASTATTEMPT: { + case AddonModScormAttemptsGradingMethod.LASTATTEMPT: { // Search the last completed attempt number. let lastCompleted = 0; for (const attemptNumber in onlineAttempts) { @@ -141,7 +123,7 @@ export class AddonModScormProvider { return -1; } - case AddonModScormProvider.HIGHESTATTEMPT: { + case AddonModScormAttemptsGradingMethod.HIGHESTATTEMPT: { // Search the highest grade. let grade = 0; for (const attemptNumber in onlineAttempts) { @@ -151,7 +133,7 @@ export class AddonModScormProvider { return grade; } - case AddonModScormProvider.AVERAGEATTEMPT: { + case AddonModScormAttemptsGradingMethod.AVERAGEATTEMPT: { // Calculate the average. let sumGrades = 0; let total = 0; @@ -217,24 +199,24 @@ export class AddonModScormProvider { */ determineAttemptAndMode( scorm: AddonModScormScorm, - mode: string, + mode: AddonModScormMode, attempt: number, newAttempt?: boolean, incomplete?: boolean, canSaveTracks = true, - ): {mode: string; attempt: number; newAttempt: boolean} { + ): {mode: AddonModScormMode; attempt: number; newAttempt: boolean} { if (!canSaveTracks) { return { - mode: scorm.hidebrowse ? AddonModScormProvider.MODENORMAL : mode, + mode: scorm.hidebrowse ? AddonModScormMode.NORMAL : mode, attempt, newAttempt: false, }; } - if (mode == AddonModScormProvider.MODEBROWSE) { + if (mode == AddonModScormMode.BROWSE) { if (scorm.hidebrowse) { // Prevent Browse mode if hidebrowse is set. - mode = AddonModScormProvider.MODENORMAL; + mode = AddonModScormMode.NORMAL; } else { // We don't need to check attempts as browse mode is set. if (attempt == 0) { @@ -250,10 +232,10 @@ export class AddonModScormProvider { } } - if (scorm.forcenewattempt == AddonModScormProvider.SCORM_FORCEATTEMPT_ALWAYS) { + if (scorm.forcenewattempt === AddonModScormForceAttempt.ALWAYS) { // This SCORM is configured to force a new attempt on every re-entry. return { - mode: AddonModScormProvider.MODENORMAL, + mode: AddonModScormMode.NORMAL, attempt: attempt + 1, newAttempt: true, }; @@ -273,14 +255,14 @@ export class AddonModScormProvider { if (newAttempt && (!scorm.maxattempt || attempt < scorm.maxattempt)) { // Create a new attempt. Force mode normal. attempt++; - mode = AddonModScormProvider.MODENORMAL; + mode = AddonModScormMode.NORMAL; } else { if (incomplete) { // We can't review an incomplete attempt. - mode = AddonModScormProvider.MODENORMAL; + mode = AddonModScormMode.NORMAL; } else { // We aren't starting a new attempt and the current one is complete, force review mode. - mode = AddonModScormProvider.MODEREVIEW; + mode = AddonModScormMode.REVIEW; } } @@ -415,7 +397,7 @@ export class AddonModScormProvider { return Translate.instant('core.none'); } - if (scorm.grademethod !== AddonModScormProvider.GRADESCOES && scorm.maxgrade) { + if (scorm.grademethod !== AddonModScormGradingMethod.GRADESCOES && scorm.maxgrade) { grade = (grade / scorm.maxgrade) * 100; return Translate.instant('core.percentagenumber', { $a: CoreTextUtils.roundToDecimals(grade, 2) }); @@ -473,7 +455,7 @@ export class AddonModScormProvider { }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getAccessInformationCacheKey(scormId), - component: AddonModScormProvider.COMPONENT, + component: ADDON_MOD_SCORM_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -488,7 +470,7 @@ export class AddonModScormProvider { * @returns Cache key. */ protected getAccessInformationCacheKey(scormId: number): string { - return ROOT_CACHE_KEY + 'accessInfo:' + scormId; + return AddonModScormProvider.ROOT_CACHE_KEY + 'accessInfo:' + scormId; } /** @@ -558,7 +540,7 @@ export class AddonModScormProvider { * @returns Cache key. */ protected getAttemptCountCacheKey(scormId: number, userId: number): string { - return ROOT_CACHE_KEY + 'attemptcount:' + scormId + ':' + userId; + return AddonModScormProvider.ROOT_CACHE_KEY + 'attemptcount:' + scormId + ':' + userId; } /** @@ -580,7 +562,7 @@ export class AddonModScormProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getAttemptCountCacheKey(scormId, userId), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, - component: AddonModScormProvider.COMPONENT, + component: ADDON_MOD_SCORM_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -641,11 +623,11 @@ export class AddonModScormProvider { let score = 0; switch (scorm.grademethod) { - case AddonModScormProvider.GRADEHIGHEST: + case AddonModScormGradingMethod.GRADEHIGHEST: score = attemptScore.max; break; - case AddonModScormProvider.GRADEAVERAGE: + case AddonModScormGradingMethod.GRADEAVERAGE: if (attemptScore.values > 0) { score = attemptScore.sum / attemptScore.values; } else { @@ -653,11 +635,11 @@ export class AddonModScormProvider { } break; - case AddonModScormProvider.GRADESUM: + case AddonModScormGradingMethod.GRADESUM: score = attemptScore.sum; break; - case AddonModScormProvider.GRADESCOES: + case AddonModScormGradingMethod.GRADESCOES: score = attemptScore.scos; break; @@ -797,7 +779,7 @@ export class AddonModScormProvider { * @returns Cache key. */ protected getScormUserDataCommonCacheKey(scormId: number): string { - return ROOT_CACHE_KEY + 'userdata:' + scormId; + return AddonModScormProvider.ROOT_CACHE_KEY + 'userdata:' + scormId; } /** @@ -821,7 +803,7 @@ export class AddonModScormProvider { }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getScormUserDataCacheKey(scormId, attempt), - component: AddonModScormProvider.COMPONENT, + component: ADDON_MOD_SCORM_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -854,7 +836,7 @@ export class AddonModScormProvider { * @returns Cache key. */ protected getScosCacheKey(scormId: number): string { - return ROOT_CACHE_KEY + 'scos:' + scormId; + return AddonModScormProvider.ROOT_CACHE_KEY + 'scos:' + scormId; } /** @@ -876,7 +858,7 @@ export class AddonModScormProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getScosCacheKey(scormId), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, - component: AddonModScormProvider.COMPONENT, + component: ADDON_MOD_SCORM_COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -1091,7 +1073,7 @@ export class AddonModScormProvider { * @returns Cache key. */ protected getScormDataCacheKey(courseId: number): string { - return ROOT_CACHE_KEY + 'scorm:' + courseId; + return AddonModScormProvider.ROOT_CACHE_KEY + 'scorm:' + courseId; } /** @@ -1118,7 +1100,7 @@ export class AddonModScormProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getScormDataCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, - component: AddonModScormProvider.COMPONENT, + component: ADDON_MOD_SCORM_COMPONENT, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; @@ -1185,16 +1167,16 @@ export class AddonModScormProvider { getScormGradeMethod(scorm: AddonModScormScorm): string { if (scorm.maxattempt == 1) { switch (scorm.grademethod) { - case AddonModScormProvider.GRADEHIGHEST: + case AddonModScormGradingMethod.GRADEHIGHEST: return Translate.instant('addon.mod_scorm.gradehighest'); - case AddonModScormProvider.GRADEAVERAGE: + case AddonModScormGradingMethod.GRADEAVERAGE: return Translate.instant('addon.mod_scorm.gradeaverage'); - case AddonModScormProvider.GRADESUM: + case AddonModScormGradingMethod.GRADESUM: return Translate.instant('addon.mod_scorm.gradesum'); - case AddonModScormProvider.GRADESCOES: + case AddonModScormGradingMethod.GRADESCOES: return Translate.instant('addon.mod_scorm.gradescoes'); default: return ''; @@ -1202,16 +1184,16 @@ export class AddonModScormProvider { } switch (scorm.whatgrade) { - case AddonModScormProvider.HIGHESTATTEMPT: + case AddonModScormAttemptsGradingMethod.HIGHESTATTEMPT: return Translate.instant('addon.mod_scorm.highestattempt'); - case AddonModScormProvider.AVERAGEATTEMPT: + case AddonModScormAttemptsGradingMethod.AVERAGEATTEMPT: return Translate.instant('addon.mod_scorm.averageattempt'); - case AddonModScormProvider.FIRSTATTEMPT: + case AddonModScormAttemptsGradingMethod.FIRSTATTEMPT: return Translate.instant('addon.mod_scorm.firstattempt'); - case AddonModScormProvider.LASTATTEMPT: + case AddonModScormAttemptsGradingMethod.LASTATTEMPT: return Translate.instant('addon.mod_scorm.lastattempt'); default: return ''; @@ -1279,7 +1261,7 @@ export class AddonModScormProvider { await Promise.all([ this.invalidateAllScormData(scorm.id, siteId, userId), - CoreFilepool.invalidateFilesByComponent(siteId, AddonModScormProvider.COMPONENT, moduleId, true), + CoreFilepool.invalidateFilesByComponent(siteId, ADDON_MOD_SCORM_COMPONENT, moduleId, true), ]); } @@ -1455,7 +1437,7 @@ export class AddonModScormProvider { return CoreCourseLogHelper.log( 'mod_scorm_launch_sco', params, - AddonModScormProvider.COMPONENT, + ADDON_MOD_SCORM_COMPONENT, scormId, siteId, ); @@ -1476,7 +1458,7 @@ export class AddonModScormProvider { return CoreCourseLogHelper.log( 'mod_scorm_view_scorm', params, - AddonModScormProvider.COMPONENT, + ADDON_MOD_SCORM_COMPONENT, id, siteId, ); @@ -1518,7 +1500,7 @@ export class AddonModScormProvider { // Tracks have been saved, update cached user data. this.updateUserDataAfterSave(scorm.id, attempt, tracks, { cmId: scorm.coursemodule, siteId }); - CoreEvents.trigger(AddonModScormProvider.DATA_SENT_EVENT, { + CoreEvents.trigger(ADDON_MOD_SCORM_DATA_SENT_EVENT, { scormId: scorm.id, scoId: scoId, attempt: attempt, @@ -1554,14 +1536,14 @@ export class AddonModScormProvider { tracks: tracks, }; - CoreSync.blockOperation(AddonModScormProvider.COMPONENT, scormId, 'saveTracksOnline', site.id); + CoreSync.blockOperation(ADDON_MOD_SCORM_COMPONENT, scormId, 'saveTracksOnline', site.id); try { const response = await site.write('mod_scorm_insert_scorm_tracks', params); return response.trackids; } finally { - CoreSync.unblockOperation(AddonModScormProvider.COMPONENT, scormId, 'saveTracksOnline', site.id); + CoreSync.unblockOperation(ADDON_MOD_SCORM_COMPONENT, scormId, 'saveTracksOnline', site.id); } } @@ -1596,7 +1578,7 @@ export class AddonModScormProvider { // Tracks have been saved, update cached user data. this.updateUserDataAfterSave(scorm.id, attempt, tracks, { cmId: scorm.coursemodule }); - CoreEvents.trigger(AddonModScormProvider.DATA_SENT_EVENT, { + CoreEvents.trigger(ADDON_MOD_SCORM_DATA_SENT_EVENT, { scormId: scorm.id, scoId: scoId, attempt: attempt, @@ -1658,7 +1640,7 @@ export class AddonModScormProvider { async shouldDownloadMainFile(scorm: AddonModScormScorm, isOutdated?: boolean, siteId?: string): Promise { siteId = siteId || CoreSites.getCurrentSiteId(); - const component = AddonModScormProvider.COMPONENT; + const component = ADDON_MOD_SCORM_COMPONENT; if (isOutdated === undefined) { // Calculate if it's outdated. @@ -1916,8 +1898,8 @@ export type AddonModScormScormWSData = { packageurl?: string; // SCORM zip package URL. version?: string; // SCORM version (SCORM_12, SCORM_13, SCORM_AICC). maxgrade?: number; // Max grade. - grademethod?: number; // Grade method. - whatgrade?: number; // What grade. + grademethod?: AddonModScormGradingMethod; // Grade method. + whatgrade?: AddonModScormAttemptsGradingMethod; // What grade. maxattempt?: number; // Maximum number of attemtps. forcecompleted?: boolean; // Status current attempt is forced to "completed". forcenewattempt?: number; // Controls re-entry behaviour. @@ -2100,12 +2082,12 @@ declare module '@singletons/events' { * @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation */ export interface CoreEventsData { - [AddonModScormProvider.LAUNCH_NEXT_SCO_EVENT]: AddonModScormCommonEventData; - [AddonModScormProvider.LAUNCH_PREV_SCO_EVENT]: AddonModScormCommonEventData; - [AddonModScormProvider.UPDATE_TOC_EVENT]: AddonModScormCommonEventData; - [AddonModScormProvider.GO_OFFLINE_EVENT]: AddonModScormCommonEventData; - [AddonModScormProvider.DATA_SENT_EVENT]: AddonModScormCommonEventData; - [AddonModScormSyncProvider.AUTO_SYNCED]: AddonModScormAutoSyncEventData; + [ADDON_MOD_SCORM_LAUNCH_NEXT_SCO_EVENT]: AddonModScormCommonEventData; + [ADDON_MOD_SCORM_LAUNCH_PREV_SCO_EVENT]: AddonModScormCommonEventData; + [ADDON_MOD_SCORM_UPDATE_TOC_EVENT]: AddonModScormCommonEventData; + [ADDON_MOD_SCORM_GO_OFFLINE_EVENT]: AddonModScormCommonEventData; + [ADDON_MOD_SCORM_DATA_SENT_EVENT]: AddonModScormCommonEventData; + [ADDON_MOD_SCORM_DATA_AUTO_SYNCED]: AddonModScormAutoSyncEventData; } } From b93dcfb87fd7b47dac076f5b9187e56ef7cce283 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Thu, 11 Jul 2024 22:44:06 +0200 Subject: [PATCH 19/26] MOBILE-4616 resource: Move resource constants to a file --- .../mod/resource/components/index/index.ts | 4 ++-- src/addons/mod/resource/constants.ts | 17 +++++++++++++++++ src/addons/mod/resource/resource-lazy.module.ts | 2 +- src/addons/mod/resource/resource.module.ts | 7 ++++--- .../mod/resource/services/handlers/module.ts | 5 ++--- .../mod/resource/services/handlers/prefetch.ts | 5 +++-- .../mod/resource/services/resource-helper.ts | 7 ++++--- src/addons/mod/resource/services/resource.ts | 13 ++++++------- 8 files changed, 39 insertions(+), 21 deletions(-) create mode 100644 src/addons/mod/resource/constants.ts diff --git a/src/addons/mod/resource/components/index/index.ts b/src/addons/mod/resource/components/index/index.ts index 48a589d75..46e30f194 100644 --- a/src/addons/mod/resource/components/index/index.ts +++ b/src/addons/mod/resource/components/index/index.ts @@ -31,10 +31,10 @@ import { Subscription } from 'rxjs'; import { AddonModResource, AddonModResourceCustomData, - AddonModResourceProvider, } from '../../services/resource'; import { AddonModResourceHelper } from '../../services/resource-helper'; import { CorePlatform } from '@services/platform'; +import { ADDON_MOD_RESOURCE_COMPONENT } from '../../constants'; /** * Component that displays a resource. @@ -46,7 +46,7 @@ import { CorePlatform } from '@services/platform'; }) export class AddonModResourceIndexComponent extends CoreCourseModuleMainResourceComponent implements OnInit, OnDestroy { - component = AddonModResourceProvider.COMPONENT; + component = ADDON_MOD_RESOURCE_COMPONENT; pluginName = 'resource'; mode = ''; diff --git a/src/addons/mod/resource/constants.ts b/src/addons/mod/resource/constants.ts new file mode 100644 index 000000000..336a35fea --- /dev/null +++ b/src/addons/mod/resource/constants.ts @@ -0,0 +1,17 @@ +// (C) Copyright 2015 Moodle Pty Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export const ADDON_MOD_RESOURCE_COMPONENT = 'mmaModResource'; + +export const ADDON_MOD_RESOURCE_PAGE_NAME = 'mod_resource'; diff --git a/src/addons/mod/resource/resource-lazy.module.ts b/src/addons/mod/resource/resource-lazy.module.ts index d04baeef9..6da403f7e 100644 --- a/src/addons/mod/resource/resource-lazy.module.ts +++ b/src/addons/mod/resource/resource-lazy.module.ts @@ -35,4 +35,4 @@ const routes: Routes = [ AddonModResourceIndexPage, ], }) -export class AddonModResourceLazyModule {} +export default class AddonModResourceLazyModule {} diff --git a/src/addons/mod/resource/resource.module.ts b/src/addons/mod/resource/resource.module.ts index d27d47f95..c0eebd30b 100644 --- a/src/addons/mod/resource/resource.module.ts +++ b/src/addons/mod/resource/resource.module.ts @@ -21,14 +21,15 @@ import { CoreMainMenuTabRoutingModule } from '@features/mainmenu/mainmenu-tab-ro import { CorePluginFileDelegate } from '@services/plugin-file-delegate'; import { AddonModResourceIndexLinkHandler } from './services/handlers/index-link'; import { AddonModResourceListLinkHandler } from './services/handlers/list-link'; -import { AddonModResourceModuleHandlerService, AddonModResourceModuleHandler } from './services/handlers/module'; +import { AddonModResourceModuleHandler } from './services/handlers/module'; import { AddonModResourcePluginFileHandler } from './services/handlers/pluginfile'; import { AddonModResourcePrefetchHandler } from './services/handlers/prefetch'; +import { ADDON_MOD_RESOURCE_PAGE_NAME } from './constants'; const routes: Routes = [ { - path: AddonModResourceModuleHandlerService.PAGE_NAME, - loadChildren: () => import('./resource-lazy.module').then(m => m.AddonModResourceLazyModule), + path: ADDON_MOD_RESOURCE_PAGE_NAME, + loadChildren: () => import('./resource-lazy.module'), }, ]; diff --git a/src/addons/mod/resource/services/handlers/module.ts b/src/addons/mod/resource/services/handlers/module.ts index 5c2c2a27b..f94293609 100644 --- a/src/addons/mod/resource/services/handlers/module.ts +++ b/src/addons/mod/resource/services/handlers/module.ts @@ -25,6 +25,7 @@ import { makeSingleton, Translate } from '@singletons'; import { AddonModResource } from '../resource'; import { AddonModResourceHelper } from '../resource-helper'; import { CoreUtils } from '@services/utils/utils'; +import { ADDON_MOD_RESOURCE_PAGE_NAME } from '../../constants'; /** * Handler to support resource modules. @@ -32,11 +33,9 @@ import { CoreUtils } from '@services/utils/utils'; @Injectable({ providedIn: 'root' }) export class AddonModResourceModuleHandlerService extends CoreModuleHandlerBase implements CoreCourseModuleHandler { - static readonly PAGE_NAME = 'mod_resource'; - name = 'AddonModResource'; modName = 'resource'; - protected pageName = AddonModResourceModuleHandlerService.PAGE_NAME; + protected pageName = ADDON_MOD_RESOURCE_PAGE_NAME; supportedFeatures = { [CoreConstants.FEATURE_MOD_ARCHETYPE]: CoreConstants.MOD_ARCHETYPE_RESOURCE, diff --git a/src/addons/mod/resource/services/handlers/prefetch.ts b/src/addons/mod/resource/services/handlers/prefetch.ts index 86c588bdf..502b4fcfb 100644 --- a/src/addons/mod/resource/services/handlers/prefetch.ts +++ b/src/addons/mod/resource/services/handlers/prefetch.ts @@ -20,8 +20,9 @@ import { CoreCourseModuleData } from '@features/course/services/course-helper'; import { CoreFilepool } from '@services/filepool'; import { CoreSites } from '@services/sites'; import { makeSingleton } from '@singletons'; -import { AddonModResource, AddonModResourceProvider } from '../resource'; +import { AddonModResource } from '../resource'; import { AddonModResourceHelper } from '../resource-helper'; +import { ADDON_MOD_RESOURCE_COMPONENT } from '../../constants'; /** * Handler to prefetch resources. @@ -31,7 +32,7 @@ export class AddonModResourcePrefetchHandlerService extends CoreCourseResourcePr name = 'AddonModResource'; modName = 'resource'; - component = AddonModResourceProvider.COMPONENT; + component = ADDON_MOD_RESOURCE_COMPONENT; /** * @inheritdoc diff --git a/src/addons/mod/resource/services/resource-helper.ts b/src/addons/mod/resource/services/resource-helper.ts index c66f0cb16..539616973 100644 --- a/src/addons/mod/resource/services/resource-helper.ts +++ b/src/addons/mod/resource/services/resource-helper.ts @@ -27,10 +27,11 @@ import { CoreMimetypeUtils } from '@services/utils/mimetype'; import { CoreUtilsOpenFileOptions } from '@services/utils/utils'; import { makeSingleton, Translate } from '@singletons'; import { CorePath } from '@singletons/path'; -import { AddonModResource, AddonModResourceCustomData, AddonModResourceProvider } from './resource'; +import { AddonModResource, AddonModResourceCustomData } from './resource'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; import { CoreTextUtils } from '@services/utils/text'; import { CoreTimeUtils } from '@services/utils/time'; +import { ADDON_MOD_RESOURCE_COMPONENT } from '../constants'; /** * Service that provides helper functions for resources. @@ -50,7 +51,7 @@ export class AddonModResourceHelperProvider { const result = await CoreCourseHelper.downloadModuleWithMainFileIfNeeded( module, module.course, - AddonModResourceProvider.COMPONENT, + ADDON_MOD_RESOURCE_COMPONENT, module.id, contents, ); @@ -196,7 +197,7 @@ export class AddonModResourceHelperProvider { await CoreCourseHelper.downloadModuleAndOpenFile( module, courseId, - AddonModResourceProvider.COMPONENT, + ADDON_MOD_RESOURCE_COMPONENT, module.id, module.contents, undefined, diff --git a/src/addons/mod/resource/services/resource.ts b/src/addons/mod/resource/services/resource.ts index 6d9c451a7..3dfaa62dc 100644 --- a/src/addons/mod/resource/services/resource.ts +++ b/src/addons/mod/resource/services/resource.ts @@ -23,8 +23,7 @@ import { CoreSites, CoreSitesCommonWSOptions } from '@services/sites'; import { CoreUtils } from '@services/utils/utils'; import { CoreWSExternalFile, CoreWSExternalWarning } from '@services/ws'; import { makeSingleton, Translate } from '@singletons'; - -const ROOT_CACHE_KEY = 'mmaModResource:'; +import { ADDON_MOD_RESOURCE_COMPONENT } from '../constants'; /** * Service that provides some features for resources. @@ -32,7 +31,7 @@ const ROOT_CACHE_KEY = 'mmaModResource:'; @Injectable({ providedIn: 'root' }) export class AddonModResourceProvider { - static readonly COMPONENT = 'mmaModResource'; + protected static readonly ROOT_CACHE_KEY = 'mmaModResource:'; /** * Get cache key for resource data WS calls. @@ -41,7 +40,7 @@ export class AddonModResourceProvider { * @returns Cache key. */ protected getResourceCacheKey(courseId: number): string { - return ROOT_CACHE_KEY + 'resource:' + courseId; + return AddonModResourceProvider.ROOT_CACHE_KEY + 'resource:' + courseId; } /** @@ -68,7 +67,7 @@ export class AddonModResourceProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getResourceCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, - component: AddonModResourceProvider.COMPONENT, + component: ADDON_MOD_RESOURCE_COMPONENT, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), }; @@ -112,7 +111,7 @@ export class AddonModResourceProvider { const promises: Promise[] = []; promises.push(this.invalidateResourceData(courseId, siteId)); - promises.push(CoreFilepool.invalidateFilesByComponent(siteId, AddonModResourceProvider.COMPONENT, moduleId)); + promises.push(CoreFilepool.invalidateFilesByComponent(siteId, ADDON_MOD_RESOURCE_COMPONENT, moduleId)); promises.push(CoreCourse.invalidateModule(moduleId, siteId, 'resource')); await CoreUtils.allPromises(promises); @@ -158,7 +157,7 @@ export class AddonModResourceProvider { await CoreCourseLogHelper.log( 'mod_resource_view_resource', params, - AddonModResourceProvider.COMPONENT, + ADDON_MOD_RESOURCE_COMPONENT, id, siteId, ); From eb2555e5ad27d62110d3d43d167a1931f8c7671d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Thu, 11 Jul 2024 22:44:14 +0200 Subject: [PATCH 20/26] MOBILE-4616 page: Move page constants to a file --- src/addons/mod/page/components/index/index.ts | 5 +++-- src/addons/mod/page/constants.ts | 16 ++++++++++++++++ src/addons/mod/page/page-lazy.module.ts | 2 +- src/addons/mod/page/page.module.ts | 7 ++++--- src/addons/mod/page/services/handlers/module.ts | 5 ++--- .../mod/page/services/handlers/prefetch.ts | 5 +++-- src/addons/mod/page/services/page-helper.ts | 4 ++-- src/addons/mod/page/services/page.ts | 13 ++++++------- 8 files changed, 37 insertions(+), 20 deletions(-) create mode 100644 src/addons/mod/page/constants.ts diff --git a/src/addons/mod/page/components/index/index.ts b/src/addons/mod/page/components/index/index.ts index d139e0473..fcef8de3f 100644 --- a/src/addons/mod/page/components/index/index.ts +++ b/src/addons/mod/page/components/index/index.ts @@ -18,8 +18,9 @@ import { CoreCourseContentsPage } from '@features/course/pages/contents/contents import { CoreCourse } from '@features/course/services/course'; import { CoreTextUtils } from '@services/utils/text'; import { CoreUtils } from '@services/utils/utils'; -import { AddonModPageProvider, AddonModPagePage, AddonModPage } from '../../services/page'; +import { AddonModPagePage, AddonModPage } from '../../services/page'; import { AddonModPageHelper } from '../../services/page-helper'; +import { ADDON_MOD_PAGE_COMPONENT } from '../../constants'; /** * Component that displays a page. @@ -30,7 +31,7 @@ import { AddonModPageHelper } from '../../services/page-helper'; }) export class AddonModPageIndexComponent extends CoreCourseModuleMainResourceComponent implements OnInit { - component = AddonModPageProvider.COMPONENT; + component = ADDON_MOD_PAGE_COMPONENT; pluginName = 'page'; contents?: string; displayDescription = false; diff --git a/src/addons/mod/page/constants.ts b/src/addons/mod/page/constants.ts new file mode 100644 index 000000000..ba1682706 --- /dev/null +++ b/src/addons/mod/page/constants.ts @@ -0,0 +1,16 @@ +// (C) Copyright 2015 Moodle Pty Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export const ADDON_MOD_PAGE_COMPONENT = 'mmaModPage'; +export const ADDON_MOD_PAGE_PAGE_NAME = 'mod_page'; diff --git a/src/addons/mod/page/page-lazy.module.ts b/src/addons/mod/page/page-lazy.module.ts index e2e52badb..9b9fd02ac 100644 --- a/src/addons/mod/page/page-lazy.module.ts +++ b/src/addons/mod/page/page-lazy.module.ts @@ -36,4 +36,4 @@ const routes: Routes = [ AddonModPageIndexPage, ], }) -export class AddonModPageLazyModule {} +export default class AddonModPageLazyModule {} diff --git a/src/addons/mod/page/page.module.ts b/src/addons/mod/page/page.module.ts index edcd8fd94..ee4545365 100644 --- a/src/addons/mod/page/page.module.ts +++ b/src/addons/mod/page/page.module.ts @@ -21,14 +21,15 @@ import { CoreMainMenuTabRoutingModule } from '@features/mainmenu/mainmenu-tab-ro import { CorePluginFileDelegate } from '@services/plugin-file-delegate'; import { AddonModPageIndexLinkHandler } from './services/handlers/index-link'; import { AddonModPageListLinkHandler } from './services/handlers/list-link'; -import { AddonModPageModuleHandler, AddonModPageModuleHandlerService } from './services/handlers/module'; +import { AddonModPageModuleHandler } from './services/handlers/module'; import { AddonModPagePluginFileHandler } from './services/handlers/pluginfile'; import { AddonModPagePrefetchHandler } from './services/handlers/prefetch'; +import { ADDON_MOD_PAGE_PAGE_NAME } from './constants'; const routes: Routes = [ { - path: AddonModPageModuleHandlerService.PAGE_NAME, - loadChildren: () => import('./page-lazy.module').then(m => m.AddonModPageLazyModule), + path: ADDON_MOD_PAGE_PAGE_NAME, + loadChildren: () => import('./page-lazy.module'), }, ]; diff --git a/src/addons/mod/page/services/handlers/module.ts b/src/addons/mod/page/services/handlers/module.ts index a4868d08e..520c5e1d9 100644 --- a/src/addons/mod/page/services/handlers/module.ts +++ b/src/addons/mod/page/services/handlers/module.ts @@ -18,6 +18,7 @@ import { CoreCourseModuleHandler } from '@features/course/services/module-delega import { CoreConstants, ModPurpose } from '@/core/constants'; import { makeSingleton } from '@singletons'; import { CoreModuleHandlerBase } from '@features/course/classes/module-base-handler'; +import { ADDON_MOD_PAGE_PAGE_NAME } from '../../constants'; /** * Handler to support page modules. @@ -25,11 +26,9 @@ import { CoreModuleHandlerBase } from '@features/course/classes/module-base-hand @Injectable({ providedIn: 'root' }) export class AddonModPageModuleHandlerService extends CoreModuleHandlerBase implements CoreCourseModuleHandler { - static readonly PAGE_NAME = 'mod_page'; - name = 'AddonModPage'; modName = 'page'; - protected pageName = AddonModPageModuleHandlerService.PAGE_NAME; + protected pageName = ADDON_MOD_PAGE_PAGE_NAME; supportedFeatures = { [CoreConstants.FEATURE_MOD_ARCHETYPE]: CoreConstants.MOD_ARCHETYPE_RESOURCE, diff --git a/src/addons/mod/page/services/handlers/prefetch.ts b/src/addons/mod/page/services/handlers/prefetch.ts index 484b0b545..f00fceb80 100644 --- a/src/addons/mod/page/services/handlers/prefetch.ts +++ b/src/addons/mod/page/services/handlers/prefetch.ts @@ -18,7 +18,8 @@ import { CoreCourse, CoreCourseAnyModuleData } from '@features/course/services/c import { CoreCourseModuleData } from '@features/course/services/course-helper'; import { CoreUtils } from '@services/utils/utils'; import { makeSingleton } from '@singletons'; -import { AddonModPage, AddonModPageProvider } from '../page'; +import { AddonModPage } from '../page'; +import { ADDON_MOD_PAGE_COMPONENT } from '../../constants'; /** * Handler to prefetch pages. @@ -28,7 +29,7 @@ export class AddonModPagePrefetchHandlerService extends CoreCourseResourcePrefet name = 'AddonModPage'; modName = 'page'; - component = AddonModPageProvider.COMPONENT; + component = ADDON_MOD_PAGE_COMPONENT; updatesNames = /^configuration$|^.*files$/; /** diff --git a/src/addons/mod/page/services/page-helper.ts b/src/addons/mod/page/services/page-helper.ts index 1845b209e..406c71bcd 100644 --- a/src/addons/mod/page/services/page-helper.ts +++ b/src/addons/mod/page/services/page-helper.ts @@ -13,7 +13,6 @@ // limitations under the License. import { Injectable } from '@angular/core'; -import { AddonModPageProvider } from './page'; import { CoreError } from '@classes/errors/error'; import { CoreTextUtils } from '@services/utils/text'; import { CoreFile } from '@services/file'; @@ -23,6 +22,7 @@ import { CoreWS } from '@services/ws'; import { CoreDomUtils } from '@services/utils/dom'; import { makeSingleton } from '@singletons'; import { CoreCourseModuleContentFile } from '@features/course/services/course'; +import { ADDON_MOD_PAGE_COMPONENT } from '../constants'; /** * Service that provides some features for page. @@ -71,7 +71,7 @@ export class AddonModPageHelperProvider { CoreSites.getCurrentSiteId(), indexUrl, false, - AddonModPageProvider.COMPONENT, + ADDON_MOD_PAGE_COMPONENT, moduleId, ); } else { diff --git a/src/addons/mod/page/services/page.ts b/src/addons/mod/page/services/page.ts index af285f171..cea794dd4 100644 --- a/src/addons/mod/page/services/page.ts +++ b/src/addons/mod/page/services/page.ts @@ -23,8 +23,7 @@ import { CoreUtils } from '@services/utils/utils'; import { CoreCourseLogHelper } from '@features/course/services/log-helper'; import { CoreError } from '@classes/errors/error'; import { CoreSiteWSPreSets } from '@classes/sites/authenticated-site'; - -const ROOT_CACHE_KEY = 'mmaModPage:'; +import { ADDON_MOD_PAGE_COMPONENT } from '../constants'; /** * Service that provides some features for page. @@ -32,7 +31,7 @@ const ROOT_CACHE_KEY = 'mmaModPage:'; @Injectable({ providedIn: 'root' }) export class AddonModPageProvider { - static readonly COMPONENT = 'mmaModPage'; + protected static readonly ROOT_CACHE_KEY = 'mmaModPage:'; /** * Get a page by course module ID. @@ -69,7 +68,7 @@ export class AddonModPageProvider { const preSets: CoreSiteWSPreSets = { cacheKey: this.getPageCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, - component: AddonModPageProvider.COMPONENT, + component: ADDON_MOD_PAGE_COMPONENT, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), }; @@ -90,7 +89,7 @@ export class AddonModPageProvider { * @returns Cache key. */ protected getPageCacheKey(courseId: number): string { - return ROOT_CACHE_KEY + 'page:' + courseId; + return AddonModPageProvider.ROOT_CACHE_KEY + 'page:' + courseId; } /** @@ -107,7 +106,7 @@ export class AddonModPageProvider { const promises: Promise[] = []; promises.push(this.invalidatePageData(courseId, siteId)); - promises.push(CoreFilepool.invalidateFilesByComponent(siteId, AddonModPageProvider.COMPONENT, moduleId)); + promises.push(CoreFilepool.invalidateFilesByComponent(siteId, ADDON_MOD_PAGE_COMPONENT, moduleId)); promises.push(CoreCourse.invalidateModule(moduleId, siteId)); return CoreUtils.allPromises(promises); @@ -153,7 +152,7 @@ export class AddonModPageProvider { return CoreCourseLogHelper.log( 'mod_page_view_page', params, - AddonModPageProvider.COMPONENT, + ADDON_MOD_PAGE_COMPONENT, pageid, siteId, ); From f65d6409990a70badfae680db58eee51822543b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Thu, 11 Jul 2024 16:00:37 +0200 Subject: [PATCH 21/26] MOBILE-4616 choice: Move choice constants to a file --- src/addons/mod/choice/choice-lazy.module.ts | 2 +- src/addons/mod/choice/choice.module.ts | 8 ++++---- src/addons/mod/choice/components/index/index.ts | 10 +++++++--- src/addons/mod/choice/constants.ts | 3 +++ src/addons/mod/choice/services/choice-sync.ts | 6 ++---- src/addons/mod/choice/services/choice.ts | 6 +++--- src/addons/mod/choice/services/handlers/module.ts | 5 ++--- 7 files changed, 22 insertions(+), 18 deletions(-) diff --git a/src/addons/mod/choice/choice-lazy.module.ts b/src/addons/mod/choice/choice-lazy.module.ts index a5a0627e5..bcbcc9c2d 100644 --- a/src/addons/mod/choice/choice-lazy.module.ts +++ b/src/addons/mod/choice/choice-lazy.module.ts @@ -35,4 +35,4 @@ const routes: Routes = [ AddonModChoiceIndexPage, ], }) -export class AddonModChoiceLazyModule {} +export default class AddonModChoiceLazyModule {} diff --git a/src/addons/mod/choice/choice.module.ts b/src/addons/mod/choice/choice.module.ts index b09b8ab97..d681d011d 100644 --- a/src/addons/mod/choice/choice.module.ts +++ b/src/addons/mod/choice/choice.module.ts @@ -25,15 +25,15 @@ import { CORE_SITE_SCHEMAS } from '@services/sites'; import { OFFLINE_SITE_SCHEMA } from './services/database/choice'; import { AddonModChoiceIndexLinkHandler } from './services/handlers/index-link'; import { AddonModChoiceListLinkHandler } from './services/handlers/list-link'; -import { AddonModChoiceModuleHandler, AddonModChoiceModuleHandlerService } from './services/handlers/module'; +import { AddonModChoiceModuleHandler } from './services/handlers/module'; import { AddonModChoicePrefetchHandler } from './services/handlers/prefetch'; import { AddonModChoiceSyncCronHandler } from './services/handlers/sync-cron'; -import { ADDON_MOD_CHOICE_COMPONENT } from './constants'; +import { ADDON_MOD_CHOICE_COMPONENT, ADDON_MOD_CHOICE_PAGE_NAME } from './constants'; const routes: Routes = [ { - path: AddonModChoiceModuleHandlerService.PAGE_NAME, - loadChildren: () => import('./choice-lazy.module').then(m => m.AddonModChoiceLazyModule), + path: ADDON_MOD_CHOICE_PAGE_NAME, + loadChildren: () => import('./choice-lazy.module'), }, ]; diff --git a/src/addons/mod/choice/components/index/index.ts b/src/addons/mod/choice/components/index/index.ts index 69ac15956..a64944d79 100644 --- a/src/addons/mod/choice/components/index/index.ts +++ b/src/addons/mod/choice/components/index/index.ts @@ -32,11 +32,15 @@ import { AddonModChoiceOffline } from '../../services/choice-offline'; import { AddonModChoiceAutoSyncData, AddonModChoiceSync, - AddonModChoiceSyncProvider, AddonModChoiceSyncResult, } from '../../services/choice-sync'; import { AddonModChoicePrefetchHandler } from '../../services/handlers/prefetch'; -import { ADDON_MOD_CHOICE_COMPONENT, ADDON_MOD_CHOICE_PUBLISH_ANONYMOUS, AddonModChoiceShowResults } from '../../constants'; +import { + ADDON_MOD_CHOICE_AUTO_SYNCED, + ADDON_MOD_CHOICE_COMPONENT, + ADDON_MOD_CHOICE_PUBLISH_ANONYMOUS, + AddonModChoiceShowResults, +} from '../../constants'; /** * Component that displays a choice. @@ -64,7 +68,7 @@ export class AddonModChoiceIndexComponent extends CoreCourseModuleMainActivityCo publishInfo?: string; // Message explaining the user what will happen with his choices. protected userId?: number; - protected syncEventName = AddonModChoiceSyncProvider.AUTO_SYNCED; + protected syncEventName = ADDON_MOD_CHOICE_AUTO_SYNCED; protected hasAnsweredOnline = false; protected now = CoreTimeUtils.timestamp(); diff --git a/src/addons/mod/choice/constants.ts b/src/addons/mod/choice/constants.ts index af337952b..9e2be82e4 100644 --- a/src/addons/mod/choice/constants.ts +++ b/src/addons/mod/choice/constants.ts @@ -13,6 +13,7 @@ // limitations under the License. export const ADDON_MOD_CHOICE_COMPONENT = 'mmaModChoice'; +export const ADDON_MOD_CHOICE_PAGE_NAME = 'mod_choice'; /** * Possible show results values. @@ -27,3 +28,5 @@ export const enum AddonModChoiceShowResults { // Possible choice publish values. export const ADDON_MOD_CHOICE_PUBLISH_ANONYMOUS = false; export const ADDON_MOD_CHOICE_PUBLISH_NAMES = true; + +export const ADDON_MOD_CHOICE_AUTO_SYNCED = 'addon_mod_choice_autom_synced'; diff --git a/src/addons/mod/choice/services/choice-sync.ts b/src/addons/mod/choice/services/choice-sync.ts index 7a9cf0040..16adaa888 100644 --- a/src/addons/mod/choice/services/choice-sync.ts +++ b/src/addons/mod/choice/services/choice-sync.ts @@ -26,7 +26,7 @@ import { CoreEvents } from '@singletons/events'; import { AddonModChoice } from './choice'; import { AddonModChoiceOffline } from './choice-offline'; import { AddonModChoicePrefetchHandler } from './handlers/prefetch'; -import { ADDON_MOD_CHOICE_COMPONENT } from '../constants'; +import { ADDON_MOD_CHOICE_AUTO_SYNCED, ADDON_MOD_CHOICE_COMPONENT } from '../constants'; /** * Service to sync choices. @@ -34,8 +34,6 @@ import { ADDON_MOD_CHOICE_COMPONENT } from '../constants'; @Injectable({ providedIn: 'root' }) export class AddonModChoiceSyncProvider extends CoreCourseActivitySyncBaseProvider { - static readonly AUTO_SYNCED = 'addon_mod_choice_autom_synced'; - protected componentTranslatableString = 'choice'; constructor() { @@ -82,7 +80,7 @@ export class AddonModChoiceSyncProvider extends CoreCourseActivitySyncBaseProvid if (result?.updated) { // Sync successful, send event. - CoreEvents.trigger(AddonModChoiceSyncProvider.AUTO_SYNCED, { + CoreEvents.trigger(ADDON_MOD_CHOICE_AUTO_SYNCED, { choiceId: response.choiceid, userId: response.userid, warnings: result.warnings, diff --git a/src/addons/mod/choice/services/choice.ts b/src/addons/mod/choice/services/choice.ts index 8cbe5e197..60f50c26b 100644 --- a/src/addons/mod/choice/services/choice.ts +++ b/src/addons/mod/choice/services/choice.ts @@ -25,9 +25,9 @@ import { CoreUtils } from '@services/utils/utils'; import { CoreStatusWithWarningsWSResponse, CoreWSExternalFile, CoreWSExternalWarning } from '@services/ws'; import { makeSingleton, Translate } from '@singletons'; import { AddonModChoiceOffline } from './choice-offline'; -import { AddonModChoiceAutoSyncData, AddonModChoiceSyncProvider } from './choice-sync'; +import { AddonModChoiceAutoSyncData } from './choice-sync'; import { CoreSiteWSPreSets } from '@classes/sites/authenticated-site'; -import { ADDON_MOD_CHOICE_COMPONENT, AddonModChoiceShowResults } from '../constants'; +import { ADDON_MOD_CHOICE_AUTO_SYNCED, ADDON_MOD_CHOICE_COMPONENT, AddonModChoiceShowResults } from '../constants'; /** * Service that provides some features for choices. @@ -611,7 +611,7 @@ declare module '@singletons/events' { * @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation */ export interface CoreEventsData { - [AddonModChoiceSyncProvider.AUTO_SYNCED]: AddonModChoiceAutoSyncData; + [ADDON_MOD_CHOICE_AUTO_SYNCED]: AddonModChoiceAutoSyncData; } } diff --git a/src/addons/mod/choice/services/handlers/module.ts b/src/addons/mod/choice/services/handlers/module.ts index 035b7832a..1f4523c32 100644 --- a/src/addons/mod/choice/services/handlers/module.ts +++ b/src/addons/mod/choice/services/handlers/module.ts @@ -17,6 +17,7 @@ import { Injectable, Type } from '@angular/core'; import { CoreModuleHandlerBase } from '@features/course/classes/module-base-handler'; import { CoreCourseModuleHandler } from '@features/course/services/module-delegate'; import { makeSingleton } from '@singletons'; +import { ADDON_MOD_CHOICE_PAGE_NAME } from '../../constants'; /** * Handler to support choice modules. @@ -24,11 +25,9 @@ import { makeSingleton } from '@singletons'; @Injectable({ providedIn: 'root' }) export class AddonModChoiceModuleHandlerService extends CoreModuleHandlerBase implements CoreCourseModuleHandler { - static readonly PAGE_NAME = 'mod_choice'; - name = 'AddonModChoice'; modName = 'choice'; - protected pageName = AddonModChoiceModuleHandlerService.PAGE_NAME; + protected pageName = ADDON_MOD_CHOICE_PAGE_NAME; supportedFeatures = { [CoreConstants.FEATURE_GROUPS]: true, From e115e840c12ed399c9128d3c10b6a89c82872913 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Thu, 11 Jul 2024 17:12:53 +0200 Subject: [PATCH 22/26] MOBILE-4616 chat: Move chat constants to a file --- src/addons/mod/chat/chat-lazy.module.ts | 2 +- src/addons/mod/chat/chat.module.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/addons/mod/chat/chat-lazy.module.ts b/src/addons/mod/chat/chat-lazy.module.ts index 60cec6c44..ae3ce0a46 100644 --- a/src/addons/mod/chat/chat-lazy.module.ts +++ b/src/addons/mod/chat/chat-lazy.module.ts @@ -80,4 +80,4 @@ const routes: Routes = [ AddonModChatSessionMessagesPage, ], }) -export class AddonModChatLazyModule {} +export default class AddonModChatLazyModule {} diff --git a/src/addons/mod/chat/chat.module.ts b/src/addons/mod/chat/chat.module.ts index 0a0494558..304dbd409 100644 --- a/src/addons/mod/chat/chat.module.ts +++ b/src/addons/mod/chat/chat.module.ts @@ -28,7 +28,7 @@ import { ADDON_MOD_CHAT_COMPONENT, ADDON_MOD_CHAT_PAGE_NAME } from './constants' const routes: Routes = [ { path: ADDON_MOD_CHAT_PAGE_NAME, - loadChildren: () => import('./chat-lazy.module').then(m => m.AddonModChatLazyModule), + loadChildren: () => import('./chat-lazy.module'), }, ]; From d3b02b07e45401161918749fbee7bb9a835abde6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Fri, 12 Jul 2024 11:39:29 +0200 Subject: [PATCH 23/26] MOBILE-4616 quiz: Move quiz constants to a file --- src/addons/mod/quiz/components/index/index.ts | 16 ++++++++++------ src/addons/mod/quiz/constants.ts | 4 ++++ src/addons/mod/quiz/quiz-lazy.module.ts | 2 +- src/addons/mod/quiz/quiz.module.ts | 8 ++++---- src/addons/mod/quiz/services/handlers/module.ts | 5 ++--- src/addons/mod/quiz/services/quiz-helper.ts | 4 ++-- src/addons/mod/quiz/services/quiz-sync.ts | 6 ++---- src/addons/mod/quiz/services/quiz.ts | 5 +++-- 8 files changed, 28 insertions(+), 22 deletions(-) diff --git a/src/addons/mod/quiz/components/index/index.ts b/src/addons/mod/quiz/components/index/index.ts index 5c571eb9a..0e2d76bd3 100644 --- a/src/addons/mod/quiz/components/index/index.ts +++ b/src/addons/mod/quiz/components/index/index.ts @@ -26,7 +26,6 @@ import { CoreTextUtils } from '@services/utils/text'; import { CoreUtils } from '@services/utils/utils'; import { Translate } from '@singletons'; import { CoreEventObserver, CoreEvents } from '@singletons/events'; -import { AddonModQuizModuleHandlerService } from '../../services/handlers/module'; import { AddonModQuizPrefetchHandler } from '../../services/handlers/prefetch'; import { AddonModQuiz, @@ -42,10 +41,15 @@ import { AddonModQuizAttempt, AddonModQuizHelper, AddonModQuizQuizData } from '. import { AddonModQuizAutoSyncData, AddonModQuizSync, - AddonModQuizSyncProvider, AddonModQuizSyncResult, } from '../../services/quiz-sync'; -import { ADDON_MOD_QUIZ_ATTEMPT_FINISHED_EVENT, ADDON_MOD_QUIZ_COMPONENT, AddonModQuizAttemptStates } from '../../constants'; +import { + ADDON_MOD_QUIZ_ATTEMPT_FINISHED_EVENT, + ADDON_MOD_QUIZ_AUTO_SYNCED, + ADDON_MOD_QUIZ_COMPONENT, + ADDON_MOD_QUIZ_PAGE_NAME, + AddonModQuizAttemptStates, +} from '../../constants'; import { QuestionDisplayOptionsMarks } from '@features/question/constants'; /** @@ -83,7 +87,7 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp bestGrade?: AddonModQuizGetUserBestGradeWSResponse; // Best grade data. protected fetchContentDefaultError = 'addon.mod_quiz.errorgetquiz'; // Default error to show when loading contents. - protected syncEventName = AddonModQuizSyncProvider.AUTO_SYNCED; + protected syncEventName = ADDON_MOD_QUIZ_AUTO_SYNCED; protected autoReview?: AddonModQuizAttemptFinishedData; // Data to auto-review an attempt after finishing. protected quizAccessInfo?: AddonModQuizGetQuizAccessInformationWSResponse; // Quiz access info. @@ -505,7 +509,7 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp this.hasPlayed = true; CoreNavigator.navigateToSitePath( - `${AddonModQuizModuleHandlerService.PAGE_NAME}/${this.courseId}/${this.module.id}/player`, + `${ADDON_MOD_QUIZ_PAGE_NAME}/${this.courseId}/${this.module.id}/player`, { params: { moduleUrl: this.module.url, @@ -657,7 +661,7 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp */ async reviewAttempt(attemptId: number): Promise { await CoreNavigator.navigateToSitePath( - `${AddonModQuizModuleHandlerService.PAGE_NAME}/${this.courseId}/${this.module.id}/review/${attemptId}`, + `${ADDON_MOD_QUIZ_PAGE_NAME}/${this.courseId}/${this.module.id}/review/${attemptId}`, ); } diff --git a/src/addons/mod/quiz/constants.ts b/src/addons/mod/quiz/constants.ts index cc5e687d3..67bd89826 100644 --- a/src/addons/mod/quiz/constants.ts +++ b/src/addons/mod/quiz/constants.ts @@ -14,10 +14,14 @@ export const ADDON_MOD_QUIZ_COMPONENT = 'mmaModQuiz'; +export const ADDON_MOD_QUIZ_PAGE_NAME = 'mod_quiz'; + export const ADDON_MOD_QUIZ_FEATURE_NAME = 'CoreCourseModuleDelegate_AddonModQuiz'; export const ADDON_MOD_QUIZ_ATTEMPT_FINISHED_EVENT = 'addon_mod_quiz_attempt_finished'; +export const ADDON_MOD_QUIZ_AUTO_SYNCED = 'addon_mod_quiz_autom_synced'; + export const ADDON_MOD_QUIZ_SHOW_TIME_BEFORE_DEADLINE = 3600; export const ADDON_MOD_QUIZ_IMMEDIATELY_AFTER_PERIOD = 120; // Time considered 'immedately after the attempt', in seconds. diff --git a/src/addons/mod/quiz/quiz-lazy.module.ts b/src/addons/mod/quiz/quiz-lazy.module.ts index 99f8d8607..1d4c4e0eb 100644 --- a/src/addons/mod/quiz/quiz-lazy.module.ts +++ b/src/addons/mod/quiz/quiz-lazy.module.ts @@ -53,4 +53,4 @@ const routes: Routes = [ AddonModQuizReviewPage, ], }) -export class AddonModQuizLazyModule {} +export default class AddonModQuizLazyModule {} diff --git a/src/addons/mod/quiz/quiz.module.ts b/src/addons/mod/quiz/quiz.module.ts index e51dc8888..c8e465620 100644 --- a/src/addons/mod/quiz/quiz.module.ts +++ b/src/addons/mod/quiz/quiz.module.ts @@ -28,12 +28,12 @@ import { SITE_SCHEMA } from './services/database/quiz'; import { AddonModQuizGradeLinkHandler } from './services/handlers/grade-link'; import { AddonModQuizIndexLinkHandler } from './services/handlers/index-link'; import { AddonModQuizListLinkHandler } from './services/handlers/list-link'; -import { AddonModQuizModuleHandler, AddonModQuizModuleHandlerService } from './services/handlers/module'; +import { AddonModQuizModuleHandler } from './services/handlers/module'; import { AddonModQuizPrefetchHandler } from './services/handlers/prefetch'; import { AddonModQuizPushClickHandler } from './services/handlers/push-click'; import { AddonModQuizReviewLinkHandler } from './services/handlers/review-link'; import { AddonModQuizSyncCronHandler } from './services/handlers/sync-cron'; -import { ADDON_MOD_QUIZ_COMPONENT } from './constants'; +import { ADDON_MOD_QUIZ_COMPONENT, ADDON_MOD_QUIZ_PAGE_NAME } from './constants'; /** * Get mod Quiz services. @@ -69,8 +69,8 @@ export async function getModQuizComponentModules(): Promise { const routes: Routes = [ { - path: AddonModQuizModuleHandlerService.PAGE_NAME, - loadChildren: () => import('./quiz-lazy.module').then(m => m.AddonModQuizLazyModule), + path: ADDON_MOD_QUIZ_PAGE_NAME, + loadChildren: () => import('./quiz-lazy.module'), }, ]; diff --git a/src/addons/mod/quiz/services/handlers/module.ts b/src/addons/mod/quiz/services/handlers/module.ts index 39c563c7d..73c2ca744 100644 --- a/src/addons/mod/quiz/services/handlers/module.ts +++ b/src/addons/mod/quiz/services/handlers/module.ts @@ -18,6 +18,7 @@ import { CoreConstants, ModPurpose } from '@/core/constants'; import { CoreCourseModuleHandler } from '@features/course/services/module-delegate'; import { makeSingleton } from '@singletons'; import { CoreModuleHandlerBase } from '@features/course/classes/module-base-handler'; +import { ADDON_MOD_QUIZ_PAGE_NAME } from '../../constants'; /** * Handler to support quiz modules. @@ -25,11 +26,9 @@ import { CoreModuleHandlerBase } from '@features/course/classes/module-base-hand @Injectable({ providedIn: 'root' }) export class AddonModQuizModuleHandlerService extends CoreModuleHandlerBase implements CoreCourseModuleHandler { - static readonly PAGE_NAME = 'mod_quiz'; - name = 'AddonModQuiz'; modName = 'quiz'; - protected pageName = AddonModQuizModuleHandlerService.PAGE_NAME; + protected pageName = ADDON_MOD_QUIZ_PAGE_NAME; supportedFeatures = { [CoreConstants.FEATURE_GROUPS]: true, diff --git a/src/addons/mod/quiz/services/quiz-helper.ts b/src/addons/mod/quiz/services/quiz-helper.ts index 66432a360..383cf2320 100644 --- a/src/addons/mod/quiz/services/quiz-helper.ts +++ b/src/addons/mod/quiz/services/quiz-helper.ts @@ -23,7 +23,6 @@ import { CoreDomUtils } from '@services/utils/dom'; import { CoreUtils } from '@services/utils/utils'; import { makeSingleton, Translate } from '@singletons'; import { AddonModQuizAccessRuleDelegate } from './access-rules-delegate'; -import { AddonModQuizModuleHandlerService } from './handlers/module'; import { AddonModQuiz, AddonModQuizAttemptWSData, @@ -34,6 +33,7 @@ import { import { AddonModQuizOffline } from './quiz-offline'; import { ADDON_MOD_QUIZ_IMMEDIATELY_AFTER_PERIOD, + ADDON_MOD_QUIZ_PAGE_NAME, AddonModQuizAttemptStates, AddonModQuizDisplayOptionsAttemptStates, } from '../constants'; @@ -349,7 +349,7 @@ export class AddonModQuizHelperProvider { // Go to the review page. await CoreNavigator.navigateToSitePath( - `${AddonModQuizModuleHandlerService.PAGE_NAME}/${module.course}/${module.id}/review/${attemptId}`, + `${ADDON_MOD_QUIZ_PAGE_NAME}/${module.course}/${module.id}/review/${attemptId}`, { params: { page: page == undefined || isNaN(page) ? -1 : page, diff --git a/src/addons/mod/quiz/services/quiz-sync.ts b/src/addons/mod/quiz/services/quiz-sync.ts index 60ef311bd..dd36abfb2 100644 --- a/src/addons/mod/quiz/services/quiz-sync.ts +++ b/src/addons/mod/quiz/services/quiz-sync.ts @@ -31,7 +31,7 @@ import { AddonModQuizAttemptDBRecord } from './database/quiz'; import { AddonModQuizPrefetchHandler } from './handlers/prefetch'; import { AddonModQuiz, AddonModQuizAttemptWSData, AddonModQuizQuizWSData } from './quiz'; import { AddonModQuizOffline, AddonModQuizQuestionsWithAnswers } from './quiz-offline'; -import { ADDON_MOD_QUIZ_COMPONENT } from '../constants'; +import { ADDON_MOD_QUIZ_AUTO_SYNCED, ADDON_MOD_QUIZ_COMPONENT } from '../constants'; /** * Service to sync quizzes. @@ -39,8 +39,6 @@ import { ADDON_MOD_QUIZ_COMPONENT } from '../constants'; @Injectable({ providedIn: 'root' }) export class AddonModQuizSyncProvider extends CoreCourseActivitySyncBaseProvider { - static readonly AUTO_SYNCED = 'addon_mod_quiz_autom_synced'; - protected componentTranslatableString = 'quiz'; constructor() { @@ -221,7 +219,7 @@ export class AddonModQuizSyncProvider extends CoreCourseActivitySyncBaseProvider if (data) { // Sync successful. Send event. - CoreEvents.trigger(AddonModQuizSyncProvider.AUTO_SYNCED, { + CoreEvents.trigger(ADDON_MOD_QUIZ_AUTO_SYNCED, { quizId: quiz.id, attemptFinished: data.attemptFinished, warnings: data.warnings, diff --git a/src/addons/mod/quiz/services/quiz.ts b/src/addons/mod/quiz/services/quiz.ts index 44a948489..07604d170 100644 --- a/src/addons/mod/quiz/services/quiz.ts +++ b/src/addons/mod/quiz/services/quiz.ts @@ -37,7 +37,7 @@ import { makeSingleton, Translate } from '@singletons'; import { CoreLogger } from '@singletons/logger'; import { AddonModQuizAccessRuleDelegate } from './access-rules-delegate'; import { AddonModQuizOffline, AddonModQuizQuestionsWithAnswers } from './quiz-offline'; -import { AddonModQuizAutoSyncData, AddonModQuizSyncProvider } from './quiz-sync'; +import { AddonModQuizAutoSyncData } from './quiz-sync'; import { CoreSiteWSPreSets } from '@classes/sites/authenticated-site'; import { QUESTION_INVALID_STATE_CLASSES, @@ -52,6 +52,7 @@ import { AddonModQuizGradeMethods, AddonModQuizDisplayOptionsAttemptStates, ADDON_MOD_QUIZ_IMMEDIATELY_AFTER_PERIOD, + ADDON_MOD_QUIZ_AUTO_SYNCED, } from '../constants'; import { CoreIonicColorNames } from '@singletons/colors'; @@ -64,7 +65,7 @@ declare module '@singletons/events' { */ export interface CoreEventsData { [ADDON_MOD_QUIZ_ATTEMPT_FINISHED_EVENT]: AddonModQuizAttemptFinishedData; - [AddonModQuizSyncProvider.AUTO_SYNCED]: AddonModQuizAutoSyncData; + [ADDON_MOD_QUIZ_AUTO_SYNCED]: AddonModQuizAutoSyncData; } } From b96b66bedd90f3359b275f2a99e8f2b02a5dceb4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Thu, 11 Jul 2024 13:15:57 +0200 Subject: [PATCH 24/26] MOBILE-4616 core: Move exported constants from module files --- .../learningplans/services/block-handler.ts | 2 +- .../classes/competency-plans-source.ts | 2 +- .../competency-course-details-lazy.module.ts | 2 +- .../competency-learning-plans-lazy.module.ts | 2 +- src/addons/competency/competency.module.ts | 9 +++------ src/addons/competency/constants.ts | 17 +++++++++++++++++ .../pages/competency/competency.page.ts | 2 +- .../competencysummary.page.ts | 2 +- .../coursecompetencies.page.ts | 2 +- .../services/handlers/competency-link.ts | 4 ++-- .../services/handlers/course-option.ts | 2 +- .../competency/services/handlers/plan-link.ts | 2 +- .../competency/services/handlers/plans-link.ts | 2 +- .../competency/services/handlers/push-click.ts | 4 ++-- .../services/handlers/user-competency-link.ts | 2 +- .../competency/services/handlers/user.ts | 6 +++--- src/addons/mod/forum/forum.module.ts | 2 +- src/addons/mod/glossary/glossary.module.ts | 2 +- src/core/features/course/constants.ts | 18 ++++++++++++++++++ src/core/features/course/course-lazy.module.ts | 3 +-- src/core/features/course/course.module.ts | 6 +----- src/core/features/course/pages/index/index.ts | 2 +- src/core/features/grades/grades.module.ts | 5 ++--- .../features/grades/services/handlers/user.ts | 4 ++-- .../classes/settings-sections-source.ts | 2 +- .../features/settings/settings-lazy.module.ts | 2 +- src/core/features/sharedfiles/constants.ts | 15 +++++++++++++++ .../sharedfiles/services/handlers/settings.ts | 2 +- .../sharedfiles/services/sharedfiles-helper.ts | 2 +- .../features/sharedfiles/sharedfiles.module.ts | 3 +-- src/core/features/user/constants.ts | 15 +++++++++++++++ .../user/services/handlers/course-option.ts | 2 +- src/core/features/user/user.module.ts | 6 ++---- 33 files changed, 103 insertions(+), 50 deletions(-) create mode 100644 src/addons/competency/constants.ts create mode 100644 src/core/features/course/constants.ts create mode 100644 src/core/features/sharedfiles/constants.ts create mode 100644 src/core/features/user/constants.ts diff --git a/src/addons/block/learningplans/services/block-handler.ts b/src/addons/block/learningplans/services/block-handler.ts index 39be924ba..652210f4b 100644 --- a/src/addons/block/learningplans/services/block-handler.ts +++ b/src/addons/block/learningplans/services/block-handler.ts @@ -17,7 +17,7 @@ import { CoreBlockHandlerData } from '@features/block/services/block-delegate'; import { CoreBlockOnlyTitleComponent } from '@features/block/components/only-title-block/only-title-block'; import { CoreBlockBaseHandler } from '@features/block/classes/base-block-handler'; import { makeSingleton } from '@singletons'; -import { ADDON_COMPETENCY_LEARNING_PLANS_PAGE } from '@addons/competency/competency.module'; +import { ADDON_COMPETENCY_LEARNING_PLANS_PAGE } from '@addons/competency/constants'; /** * Block handler. diff --git a/src/addons/competency/classes/competency-plans-source.ts b/src/addons/competency/classes/competency-plans-source.ts index 53b7f3c09..fa34eca13 100644 --- a/src/addons/competency/classes/competency-plans-source.ts +++ b/src/addons/competency/classes/competency-plans-source.ts @@ -14,7 +14,7 @@ import { Params } from '@angular/router'; import { CoreRoutedItemsManagerSource } from '@classes/items-management/routed-items-manager-source'; -import { ADDON_COMPETENCY_COMPETENCIES_PAGE } from '../competency.module'; +import { ADDON_COMPETENCY_COMPETENCIES_PAGE } from '../constants'; import { AddonCompetency, AddonCompetencyPlan, AddonCompetencyProvider } from '../services/competency'; import { AddonCompetencyHelper } from '../services/competency-helper'; import { CoreIonicColorNames } from '@singletons/colors'; diff --git a/src/addons/competency/competency-course-details-lazy.module.ts b/src/addons/competency/competency-course-details-lazy.module.ts index 4d9bf9ea7..6d0530ae4 100644 --- a/src/addons/competency/competency-course-details-lazy.module.ts +++ b/src/addons/competency/competency-course-details-lazy.module.ts @@ -17,7 +17,7 @@ import { RouterModule, Routes } from '@angular/router'; import { AddonCompetencyCompetencyPage } from './pages/competency/competency.page'; import { AddonCompetencyCompetencySummaryPage } from './pages/competencysummary/competencysummary.page'; -import { ADDON_COMPETENCY_SUMMARY_PAGE } from './competency.module'; +import { ADDON_COMPETENCY_SUMMARY_PAGE } from './constants'; import { AddonCompetencyCompetencyPageModule } from './pages/competency/competency.module'; import { AddonCompetencyCompetencySummaryPageModule } from './pages/competencysummary/competencysummary.module'; import { AddonCompetencyCourseCompetenciesPage } from './pages/coursecompetencies/coursecompetencies.page'; diff --git a/src/addons/competency/competency-learning-plans-lazy.module.ts b/src/addons/competency/competency-learning-plans-lazy.module.ts index 79dcab799..bf093ed31 100644 --- a/src/addons/competency/competency-learning-plans-lazy.module.ts +++ b/src/addons/competency/competency-learning-plans-lazy.module.ts @@ -22,7 +22,7 @@ import { AddonCompetencyPlanPage } from './pages/plan/plan'; import { AddonCompetencyPlanListPage } from './pages/planlist/planlist'; import { AddonCompetencyCompetencyPage } from './pages/competency/competency.page'; import { AddonCompetencyCompetencySummaryPage } from './pages/competencysummary/competencysummary.page'; -import { ADDON_COMPETENCY_COMPETENCIES_PAGE, ADDON_COMPETENCY_SUMMARY_PAGE } from './competency.module'; +import { ADDON_COMPETENCY_COMPETENCIES_PAGE, ADDON_COMPETENCY_SUMMARY_PAGE } from './constants'; import { AddonCompetencyCompetencyPageModule } from './pages/competency/competency.module'; import { AddonCompetencyCompetencySummaryPageModule } from './pages/competencysummary/competencysummary.module'; import { AddonCompetencyCompetenciesPage } from './pages/competencies/competencies.page'; diff --git a/src/addons/competency/competency.module.ts b/src/addons/competency/competency.module.ts index 373b2b4a0..aa4185579 100644 --- a/src/addons/competency/competency.module.ts +++ b/src/addons/competency/competency.module.ts @@ -27,8 +27,9 @@ import { AddonCompetencyUserHandler } from './services/handlers/user'; import { Routes } from '@angular/router'; import { CoreMainMenuTabRoutingModule } from '@features/mainmenu/mainmenu-tab-routing.module'; import { CoreCourseIndexRoutingModule } from '@features/course/course-routing.module'; -import { COURSE_PAGE_NAME } from '@features/course/course.module'; -import { PARTICIPANTS_PAGE_NAME } from '@features/user/user.module'; +import { PARTICIPANTS_PAGE_NAME } from '@features/user/constants'; +import { COURSE_PAGE_NAME } from '@features/course/constants'; +import { ADDON_COMPETENCY_LEARNING_PLANS_PAGE, ADDON_COMPETENCY_COMPETENCIES_PAGE } from './constants'; /** * Get competency services. @@ -45,10 +46,6 @@ export async function getCompetencyServices(): Promise[]> { ]; } -export const ADDON_COMPETENCY_LEARNING_PLANS_PAGE = 'learning-plans'; -export const ADDON_COMPETENCY_COMPETENCIES_PAGE = 'competencies'; -export const ADDON_COMPETENCY_SUMMARY_PAGE = 'summary'; - const mainMenuChildrenRoutes: Routes = [ { path: ADDON_COMPETENCY_LEARNING_PLANS_PAGE, diff --git a/src/addons/competency/constants.ts b/src/addons/competency/constants.ts new file mode 100644 index 000000000..b6f933f0c --- /dev/null +++ b/src/addons/competency/constants.ts @@ -0,0 +1,17 @@ +// (C) Copyright 2015 Moodle Pty Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export const ADDON_COMPETENCY_LEARNING_PLANS_PAGE = 'learning-plans'; +export const ADDON_COMPETENCY_COMPETENCIES_PAGE = 'competencies'; +export const ADDON_COMPETENCY_SUMMARY_PAGE = 'summary'; diff --git a/src/addons/competency/pages/competency/competency.page.ts b/src/addons/competency/pages/competency/competency.page.ts index f7482a6ee..615a146c2 100644 --- a/src/addons/competency/pages/competency/competency.page.ts +++ b/src/addons/competency/pages/competency/competency.page.ts @@ -32,7 +32,7 @@ import { import { CoreNavigator } from '@services/navigator'; import { ContextLevel } from '@/core/constants'; import { CoreUtils } from '@services/utils/utils'; -import { ADDON_COMPETENCY_SUMMARY_PAGE } from '@addons/competency/competency.module'; +import { ADDON_COMPETENCY_SUMMARY_PAGE } from '@addons/competency/constants'; import { CoreSwipeNavigationItemsManager } from '@classes/items-management/swipe-navigation-items-manager'; import { CoreRoutedItemsManagerSourcesTracker } from '@classes/items-management/routed-items-manager-sources-tracker'; import { AddonCompetencyPlanCompetenciesSource } from '@addons/competency/classes/competency-plan-competencies-source'; diff --git a/src/addons/competency/pages/competencysummary/competencysummary.page.ts b/src/addons/competency/pages/competencysummary/competencysummary.page.ts index 00dd18b0c..8099d303f 100644 --- a/src/addons/competency/pages/competencysummary/competencysummary.page.ts +++ b/src/addons/competency/pages/competencysummary/competencysummary.page.ts @@ -18,7 +18,7 @@ import { AddonCompetencySummary, AddonCompetency } from '@addons/competency/serv import { CoreNavigator } from '@services/navigator'; import { CoreDomUtils } from '@services/utils/dom'; import { CoreUtils } from '@services/utils/utils'; -import { ADDON_COMPETENCY_SUMMARY_PAGE } from '@addons/competency/competency.module'; +import { ADDON_COMPETENCY_SUMMARY_PAGE } from '@addons/competency/constants'; import { CoreTime } from '@singletons/time'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; diff --git a/src/addons/competency/pages/coursecompetencies/coursecompetencies.page.ts b/src/addons/competency/pages/coursecompetencies/coursecompetencies.page.ts index 665842828..f6d4adf12 100644 --- a/src/addons/competency/pages/coursecompetencies/coursecompetencies.page.ts +++ b/src/addons/competency/pages/coursecompetencies/coursecompetencies.page.ts @@ -21,7 +21,7 @@ import { CoreUserProfile } from '@features/user/services/user'; import { CoreNavigator } from '@services/navigator'; import { CoreDomUtils } from '@services/utils/dom'; import { ContextLevel } from '@/core/constants'; -import { ADDON_COMPETENCY_SUMMARY_PAGE } from '@addons/competency/competency.module'; +import { ADDON_COMPETENCY_SUMMARY_PAGE } from '@addons/competency/constants'; import { CoreListItemsManager } from '@classes/items-management/list-items-manager'; import { CoreRoutedItemsManagerSourcesTracker } from '@classes/items-management/routed-items-manager-sources-tracker'; import { AddonCompetencyCourseCompetenciesSource } from '@addons/competency/classes/competency-course-competencies-source'; diff --git a/src/addons/competency/services/handlers/competency-link.ts b/src/addons/competency/services/handlers/competency-link.ts index 6d268c040..69a42f6ee 100644 --- a/src/addons/competency/services/handlers/competency-link.ts +++ b/src/addons/competency/services/handlers/competency-link.ts @@ -12,11 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { ADDON_COMPETENCY_COMPETENCIES_PAGE, ADDON_COMPETENCY_LEARNING_PLANS_PAGE } from '@addons/competency/competency.module'; +import { ADDON_COMPETENCY_COMPETENCIES_PAGE, ADDON_COMPETENCY_LEARNING_PLANS_PAGE } from '@addons/competency/constants'; import { Injectable } from '@angular/core'; import { CoreContentLinksHandlerBase } from '@features/contentlinks/classes/base-handler'; import { CoreContentLinksAction } from '@features/contentlinks/services/contentlinks-delegate'; -import { COURSE_PAGE_NAME } from '@features/course/course.module'; +import { COURSE_PAGE_NAME } from '@features/course/constants'; import { CoreNavigator } from '@services/navigator'; import { makeSingleton } from '@singletons'; import { AddonCompetency } from '../competency'; diff --git a/src/addons/competency/services/handlers/course-option.ts b/src/addons/competency/services/handlers/course-option.ts index f8148c170..1288774df 100644 --- a/src/addons/competency/services/handlers/course-option.ts +++ b/src/addons/competency/services/handlers/course-option.ts @@ -24,7 +24,7 @@ import { AddonCompetency } from '../competency'; import { CoreCourseAnyCourseData, CoreCourseUserAdminOrNavOptionIndexed } from '@features/courses/services/courses'; import { CoreFilterHelper } from '@features/filter/services/filter-helper'; import { ContextLevel } from '@/core/constants'; -import { ADDON_COMPETENCY_COMPETENCIES_PAGE } from '@addons/competency/competency.module'; +import { ADDON_COMPETENCY_COMPETENCIES_PAGE } from '@addons/competency/constants'; /** * Course nav handler. diff --git a/src/addons/competency/services/handlers/plan-link.ts b/src/addons/competency/services/handlers/plan-link.ts index 12eee7afe..7f19e227e 100644 --- a/src/addons/competency/services/handlers/plan-link.ts +++ b/src/addons/competency/services/handlers/plan-link.ts @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { ADDON_COMPETENCY_LEARNING_PLANS_PAGE } from '@addons/competency/competency.module'; +import { ADDON_COMPETENCY_LEARNING_PLANS_PAGE } from '@addons/competency/constants'; import { Injectable } from '@angular/core'; import { CoreContentLinksHandlerBase } from '@features/contentlinks/classes/base-handler'; import { CoreContentLinksAction } from '@features/contentlinks/services/contentlinks-delegate'; diff --git a/src/addons/competency/services/handlers/plans-link.ts b/src/addons/competency/services/handlers/plans-link.ts index 685481b2b..412c226e2 100644 --- a/src/addons/competency/services/handlers/plans-link.ts +++ b/src/addons/competency/services/handlers/plans-link.ts @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { ADDON_COMPETENCY_LEARNING_PLANS_PAGE } from '@addons/competency/competency.module'; +import { ADDON_COMPETENCY_LEARNING_PLANS_PAGE } from '@addons/competency/constants'; import { Injectable } from '@angular/core'; import { CoreContentLinksHandlerBase } from '@features/contentlinks/classes/base-handler'; import { CoreContentLinksAction } from '@features/contentlinks/services/contentlinks-delegate'; diff --git a/src/addons/competency/services/handlers/push-click.ts b/src/addons/competency/services/handlers/push-click.ts index ec3b3d493..b28423ebf 100644 --- a/src/addons/competency/services/handlers/push-click.ts +++ b/src/addons/competency/services/handlers/push-click.ts @@ -12,9 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { ADDON_COMPETENCY_COMPETENCIES_PAGE, ADDON_COMPETENCY_LEARNING_PLANS_PAGE } from '@addons/competency/competency.module'; +import { ADDON_COMPETENCY_COMPETENCIES_PAGE, ADDON_COMPETENCY_LEARNING_PLANS_PAGE } from '@addons/competency/constants'; import { Injectable } from '@angular/core'; -import { COURSE_PAGE_NAME } from '@features/course/course.module'; +import { COURSE_PAGE_NAME } from '@features/course/constants'; import { CorePushNotificationsClickHandler } from '@features/pushnotifications/services/push-delegate'; import { CorePushNotificationsNotificationBasicData } from '@features/pushnotifications/services/pushnotifications'; import { CoreNavigator } from '@services/navigator'; diff --git a/src/addons/competency/services/handlers/user-competency-link.ts b/src/addons/competency/services/handlers/user-competency-link.ts index 3cc83b2b0..74eefc0b9 100644 --- a/src/addons/competency/services/handlers/user-competency-link.ts +++ b/src/addons/competency/services/handlers/user-competency-link.ts @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { ADDON_COMPETENCY_COMPETENCIES_PAGE, ADDON_COMPETENCY_SUMMARY_PAGE } from '@addons/competency/competency.module'; +import { ADDON_COMPETENCY_COMPETENCIES_PAGE, ADDON_COMPETENCY_SUMMARY_PAGE } from '@addons/competency/constants'; import { Injectable } from '@angular/core'; import { CoreContentLinksHandlerBase } from '@features/contentlinks/classes/base-handler'; import { CoreContentLinksAction } from '@features/contentlinks/services/contentlinks-delegate'; diff --git a/src/addons/competency/services/handlers/user.ts b/src/addons/competency/services/handlers/user.ts index bfbce8765..28c06c66e 100644 --- a/src/addons/competency/services/handlers/user.ts +++ b/src/addons/competency/services/handlers/user.ts @@ -12,9 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { ADDON_COMPETENCY_COMPETENCIES_PAGE, ADDON_COMPETENCY_LEARNING_PLANS_PAGE } from '@addons/competency/competency.module'; +import { ADDON_COMPETENCY_COMPETENCIES_PAGE, ADDON_COMPETENCY_LEARNING_PLANS_PAGE } from '@addons/competency/constants'; import { Injectable } from '@angular/core'; -import { COURSE_PAGE_NAME } from '@features/course/course.module'; +import { COURSE_PAGE_NAME } from '@features/course/constants'; import { CoreUserProfile } from '@features/user/services/user'; import { CoreUserProfileHandler, @@ -22,7 +22,7 @@ import { CoreUserProfileHandlerData, CoreUserDelegateContext, } from '@features/user/services/user-delegate'; -import { PARTICIPANTS_PAGE_NAME } from '@features/user/user.module'; +import { PARTICIPANTS_PAGE_NAME } from '@features/user/constants'; import { CoreNavigator } from '@services/navigator'; import { CoreSites } from '@services/sites'; import { makeSingleton } from '@singletons'; diff --git a/src/addons/mod/forum/forum.module.ts b/src/addons/mod/forum/forum.module.ts index c7bfbe804..8dfe77225 100644 --- a/src/addons/mod/forum/forum.module.ts +++ b/src/addons/mod/forum/forum.module.ts @@ -37,7 +37,7 @@ import { CoreTagAreaDelegate } from '@features/tag/services/tag-area-delegate'; import { AddonModForumTagAreaHandler } from './services/handlers/tag-area'; import { CorePushNotificationsDelegate } from '@features/pushnotifications/services/push-delegate'; import { AddonModForumPushClickHandler } from './services/handlers/push-click'; -import { COURSE_CONTENTS_PATH } from '@features/course/course.module'; +import { COURSE_CONTENTS_PATH } from '@features/course/constants'; import { CoreCourseHelper } from '@features/course/services/course-helper'; import { ADDON_MOD_FORUM_COMPONENT, ADDON_MOD_FORUM_PAGE_NAME, ADDON_MOD_FORUM_SEARCH_PAGE_NAME } from './constants'; diff --git a/src/addons/mod/glossary/glossary.module.ts b/src/addons/mod/glossary/glossary.module.ts index 624e71874..e2af50f59 100644 --- a/src/addons/mod/glossary/glossary.module.ts +++ b/src/addons/mod/glossary/glossary.module.ts @@ -16,7 +16,7 @@ import { conditionalRoutes } from '@/app/app-routing.module'; import { APP_INITIALIZER, NgModule } from '@angular/core'; import { Routes } from '@angular/router'; import { CoreContentLinksDelegate } from '@features/contentlinks/services/contentlinks-delegate'; -import { COURSE_CONTENTS_PATH } from '@features/course/course.module'; +import { COURSE_CONTENTS_PATH } from '@features/course/constants'; import { CoreCourseContentsRoutingModule } from '@features/course/course-contents-routing.module'; import { CoreCourseHelper } from '@features/course/services/course-helper'; import { CoreCourseModuleDelegate } from '@features/course/services/module-delegate'; diff --git a/src/core/features/course/constants.ts b/src/core/features/course/constants.ts new file mode 100644 index 000000000..1917eb51e --- /dev/null +++ b/src/core/features/course/constants.ts @@ -0,0 +1,18 @@ +// (C) Copyright 2015 Moodle Pty Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export const COURSE_INDEX_PATH = ':courseId'; +export const COURSE_PAGE_NAME = 'course'; +export const CONTENTS_PAGE_NAME = 'contents'; +export const COURSE_CONTENTS_PATH = `${COURSE_PAGE_NAME}/${COURSE_INDEX_PATH}/${CONTENTS_PAGE_NAME}`; diff --git a/src/core/features/course/course-lazy.module.ts b/src/core/features/course/course-lazy.module.ts index d89541958..e77e5637f 100644 --- a/src/core/features/course/course-lazy.module.ts +++ b/src/core/features/course/course-lazy.module.ts @@ -22,8 +22,7 @@ import { CoreCourseIndexPage } from '@features/course/pages/index'; import { CoreCourseListModTypePage } from '@features/course/pages/list-mod-type/list-mod-type'; import { CoreCourseModulePreviewPage } from '@features/course/pages/module-preview/module-preview'; import { CoreCourseHelper } from './services/course-helper'; - -export const COURSE_INDEX_PATH = ':courseId'; +import { COURSE_INDEX_PATH } from './constants'; /** * Build module routes. diff --git a/src/core/features/course/course.module.ts b/src/core/features/course/course.module.ts index 7533a65cb..a3b1a83da 100644 --- a/src/core/features/course/course.module.ts +++ b/src/core/features/course/course.module.ts @@ -29,9 +29,9 @@ import { CoreTagAreaDelegate } from '@features/tag/services/tag-area-delegate'; import { CoreCourseTagAreaHandler } from './services/handlers/course-tag-area'; import { CoreCourseModulesTagAreaHandler } from './services/handlers/modules-tag-area'; import { CoreCourse } from './services/course'; -import { COURSE_INDEX_PATH } from '@features/course/course-lazy.module'; import { buildRegExpUrlMatcher } from '@/app/app-routing.module'; import { CoreCourseIndexRoutingModule } from '@features/course/course-routing.module'; +import { COURSE_PAGE_NAME, CONTENTS_PAGE_NAME } from './constants'; /** * Get course services. @@ -87,10 +87,6 @@ export async function getCourseExportedObjects(): Promise[]> { ]; } -export const SHAREDFILES_PAGE_NAME = 'sharedfiles'; - const routes: Routes = [ { path: SHAREDFILES_PAGE_NAME, diff --git a/src/core/features/user/constants.ts b/src/core/features/user/constants.ts new file mode 100644 index 000000000..82edcc1d5 --- /dev/null +++ b/src/core/features/user/constants.ts @@ -0,0 +1,15 @@ +// (C) Copyright 2015 Moodle Pty Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export const PARTICIPANTS_PAGE_NAME = 'participants'; diff --git a/src/core/features/user/services/handlers/course-option.ts b/src/core/features/user/services/handlers/course-option.ts index 322799f5f..431668217 100644 --- a/src/core/features/user/services/handlers/course-option.ts +++ b/src/core/features/user/services/handlers/course-option.ts @@ -20,7 +20,7 @@ import { CoreCourseOptionsHandlerData, } from '@features/course/services/course-options-delegate'; import { CoreCourseAnyCourseData, CoreCourseUserAdminOrNavOptionIndexed } from '@features/courses/services/courses'; -import { PARTICIPANTS_PAGE_NAME } from '@features/user/user.module'; +import { PARTICIPANTS_PAGE_NAME } from '@features/user/constants'; import { makeSingleton } from '@singletons'; import { CoreUser } from '../user'; diff --git a/src/core/features/user/user.module.ts b/src/core/features/user/user.module.ts index 893a456b0..b40bce2bb 100644 --- a/src/core/features/user/user.module.ts +++ b/src/core/features/user/user.module.ts @@ -33,9 +33,9 @@ import { CoreUserCourseOptionHandler } from './services/handlers/course-option'; import { CoreUserHelper } from './services/user-helper'; import { AppRoutingModule, conditionalRoutes } from '@/app/app-routing.module'; import { CoreScreen } from '@services/screen'; -import { COURSE_PAGE_NAME } from '@features/course/course.module'; -import { COURSE_INDEX_PATH } from '@features/course/course-lazy.module'; import { CoreEvents } from '@singletons/events'; +import { COURSE_PAGE_NAME, COURSE_INDEX_PATH } from '@features/course/constants'; +import { PARTICIPANTS_PAGE_NAME } from './constants'; /** * Get user services. @@ -60,8 +60,6 @@ export async function getUsersServices(): Promise[]> { ]; } -export const PARTICIPANTS_PAGE_NAME = 'participants'; - const appRoutes: Routes = [ { path: 'user', From 746e60f51ed1dc6acc800731f747b9301a5cb4b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Fri, 12 Jul 2024 13:53:14 +0200 Subject: [PATCH 25/26] MOBILE-4616 login: Fix text on behat --- src/core/features/login/tests/behat/basic_usage.feature | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/features/login/tests/behat/basic_usage.feature b/src/core/features/login/tests/behat/basic_usage.feature index ee070c9bb..43490dabd 100755 --- a/src/core/features/login/tests/behat/basic_usage.feature +++ b/src/core/features/login/tests/behat/basic_usage.feature @@ -135,7 +135,7 @@ Feature: Test basic usage of login in app When I set the field "Current password" to "student1" And I set the field "New password" to "NewPassword1*" And I set the field "New password (again)" to "NewPassword1*" - And I click on "Sign out everywhere" "checkbox" + And I click on "Log out of all web apps" "checkbox" And I click on "Save changes" "button" Then I should see "Password has been changed" From a9f4a48356749e306fc2fd025d257c9fbd6326cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Fri, 12 Jul 2024 16:20:43 +0200 Subject: [PATCH 26/26] MOBILE-4616 keyboard: Fix dom-app circular dep by separating keyboard --- .../messages/pages/contacts-35/contacts.ts | 12 +- .../messages/pages/discussion/discussion.ts | 4 +- .../pages/discussions-35/discussions.ts | 4 +- src/addons/messages/pages/search/search.ts | 4 +- src/addons/mod/chat/pages/chat/chat.ts | 4 +- src/addons/notes/components/add/add-modal.ts | 4 +- .../features/comments/pages/viewer/viewer.ts | 4 +- .../login/pages/credentials/credentials.ts | 3 +- .../login/pages/reconnect/reconnect.ts | 4 +- src/core/features/login/pages/site/site.ts | 4 +- src/core/features/tag/pages/search/search.ts | 4 +- .../pages/participants/participants.page.ts | 4 +- .../subscribe-to-keyboard-events.ts | 11 +- src/core/services/app.ts | 62 ++++----- src/core/services/config.ts | 2 +- src/core/services/utils/dom.ts | 4 +- src/core/singletons/keyboard.ts | 123 ++++++++++++++++++ 17 files changed, 185 insertions(+), 72 deletions(-) create mode 100644 src/core/singletons/keyboard.ts diff --git a/src/addons/messages/pages/contacts-35/contacts.ts b/src/addons/messages/pages/contacts-35/contacts.ts index d69838ec0..a75496fb5 100644 --- a/src/addons/messages/pages/contacts-35/contacts.ts +++ b/src/addons/messages/pages/contacts-35/contacts.ts @@ -22,13 +22,13 @@ import { AddonMessages, } from '../../services/messages'; import { CoreDomUtils } from '@services/utils/dom'; -import { CoreApp } from '@services/app'; import { CoreEventObserver, CoreEvents } from '@singletons/events'; import { ActivatedRoute } from '@angular/router'; import { Translate } from '@singletons'; import { CoreScreen } from '@services/screen'; import { CoreNavigator } from '@services/navigator'; import { CoreSplitViewComponent } from '@components/split-view/split-view'; +import { CoreKeyboard } from '@singletons/keyboard'; /** * Page that displays the list of contacts. @@ -205,15 +205,17 @@ export class AddonMessagesContacts35Page implements OnInit, OnDestroy { * @param query Text to search for. * @returns Resolved when done. */ - search(query: string): Promise { - CoreApp.closeKeyboard(); + async search(query: string): Promise { + CoreKeyboard.close(); this.loaded = false; this.loadingMessage = this.searchingMessages; - return this.performSearch(query).finally(() => { + try { + await this.performSearch(query); + } finally { this.loaded = true; - }); + } } /** diff --git a/src/addons/messages/pages/discussion/discussion.ts b/src/addons/messages/pages/discussion/discussion.ts index fe11d4c22..dbc9c0ca4 100644 --- a/src/addons/messages/pages/discussion/discussion.ts +++ b/src/addons/messages/pages/discussion/discussion.ts @@ -34,7 +34,6 @@ import { CoreDomUtils } from '@services/utils/dom'; import { CoreUtils } from '@services/utils/utils'; import { CoreTextUtils } from '@services/utils/text'; import { CoreLogger } from '@singletons/logger'; -import { CoreApp } from '@services/app'; import { CoreInfiniteLoadingComponent } from '@components/infinite-loading/infinite-loading'; import { Md5 } from 'ts-md5/dist/md5'; import moment from 'moment-timezone'; @@ -45,6 +44,7 @@ import { CoreIonLoadingElement } from '@classes/ion-loading'; import { ActivatedRoute } from '@angular/router'; import { CoreConstants } from '@/core/constants'; import { CoreDom } from '@singletons/dom'; +import { CoreKeyboard } from '@singletons/keyboard'; /** * Page that displays a message discussion page. @@ -1177,7 +1177,7 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView // Only close the keyboard if an error happens. // We want the user to be able to send multiple messages without the keyboard being closed. - CoreApp.closeKeyboard(); + CoreKeyboard.close(); CoreDomUtils.showErrorModalDefault(error, 'addon.messages.messagenotsent', true); this.removeMessage(message.hash!); diff --git a/src/addons/messages/pages/discussions-35/discussions.ts b/src/addons/messages/pages/discussions-35/discussions.ts index 5dfa7cac3..c44a252ad 100644 --- a/src/addons/messages/pages/discussions-35/discussions.ts +++ b/src/addons/messages/pages/discussions-35/discussions.ts @@ -23,7 +23,6 @@ import { } from '../../services/messages'; import { CoreDomUtils } from '@services/utils/dom'; import { CoreUtils } from '@services/utils/utils'; -import { CoreApp } from '@services/app'; import { ActivatedRoute, Params } from '@angular/router'; import { CorePushNotificationsNotificationBasicData } from '@features/pushnotifications/services/pushnotifications'; import { CorePushNotificationsDelegate } from '@features/pushnotifications/services/push-delegate'; @@ -34,6 +33,7 @@ import { CoreScreen } from '@services/screen'; import { CoreMainMenuDeepLinkManager } from '@features/mainmenu/classes/deep-link-manager'; import { CorePlatform } from '@services/platform'; import { CoreSplitViewComponent } from '@components/split-view/split-view'; +import { CoreKeyboard } from '@singletons/keyboard'; /** * Page that displays the list of discussions. @@ -234,7 +234,7 @@ export class AddonMessagesDiscussions35Page implements OnInit, OnDestroy { * @returns Resolved when done. */ async searchMessage(query: string): Promise { - CoreApp.closeKeyboard(); + CoreKeyboard.close(); this.loaded = false; this.loadingMessage = this.search.loading; diff --git a/src/addons/messages/pages/search/search.ts b/src/addons/messages/pages/search/search.ts index 8d309a17a..501d50ca8 100644 --- a/src/addons/messages/pages/search/search.ts +++ b/src/addons/messages/pages/search/search.ts @@ -22,10 +22,10 @@ import { AddonMessages, } from '../../services/messages'; import { CoreDomUtils } from '@services/utils/dom'; -import { CoreApp } from '@services/app'; import { CoreNavigator } from '@services/navigator'; import { CoreScreen } from '@services/screen'; import { CoreSplitViewComponent } from '@components/split-view/split-view'; +import { CoreKeyboard } from '@singletons/keyboard'; /** * Page for searching users. @@ -124,7 +124,7 @@ export class AddonMessagesSearchPage implements OnDestroy { * @returns Resolved when done. */ async search(query: string, loadMore?: 'contacts' | 'noncontacts' | 'messages', infiniteComplete?: () => void): Promise { - CoreApp.closeKeyboard(); + CoreKeyboard.close(); this.query = query; this.disableSearch = true; diff --git a/src/addons/mod/chat/pages/chat/chat.ts b/src/addons/mod/chat/pages/chat/chat.ts index 2c0d46706..cbffd3a3a 100644 --- a/src/addons/mod/chat/pages/chat/chat.ts +++ b/src/addons/mod/chat/pages/chat/chat.ts @@ -16,7 +16,6 @@ import { Component, ViewChild, OnInit, OnDestroy } from '@angular/core'; import { CoreSendMessageFormComponent } from '@components/send-message-form/send-message-form'; import { CanLeave } from '@guards/can-leave'; import { IonContent } from '@ionic/angular'; -import { CoreApp } from '@services/app'; import { CoreNetwork } from '@services/network'; import { CoreNavigator } from '@services/navigator'; import { CoreSites } from '@services/sites'; @@ -30,6 +29,7 @@ import { AddonModChat, AddonModChatUser } from '../../services/chat'; import { AddonModChatFormattedMessage, AddonModChatHelper } from '../../services/chat-helper'; import { CoreTime } from '@singletons/time'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; +import { CoreKeyboard } from '@singletons/keyboard'; /** * Page that displays a chat session. @@ -323,7 +323,7 @@ export class AddonModChatChatPage implements OnInit, OnDestroy, CanLeave { } catch (error) { // Only close the keyboard if an error happens, we want the user to be able to send multiple // messages without the keyboard being closed. - CoreApp.closeKeyboard(); + CoreKeyboard.close(); this.newMessage = text; CoreDomUtils.showErrorModalDefault(error, 'addon.mod_chat.errorwhilesendingmessage', true); diff --git a/src/addons/notes/components/add/add-modal.ts b/src/addons/notes/components/add/add-modal.ts index ae840fd41..be47b9be6 100644 --- a/src/addons/notes/components/add/add-modal.ts +++ b/src/addons/notes/components/add/add-modal.ts @@ -14,11 +14,11 @@ import { AddonNotes, AddonNotesPublishState } from '@addons/notes/services/notes'; import { Component, ViewChild, ElementRef, Input } from '@angular/core'; -import { CoreApp } from '@services/app'; import { CoreSites } from '@services/sites'; import { CoreDomUtils, ToastDuration } from '@services/utils/dom'; import { CoreForms } from '@singletons/form'; import { ModalController } from '@singletons'; +import { CoreKeyboard } from '@singletons/keyboard'; /** * Component that displays a text area for composing a note. @@ -45,7 +45,7 @@ export class AddonNotesAddComponent { e.preventDefault(); e.stopPropagation(); - CoreApp.closeKeyboard(); + CoreKeyboard.close(); const loadingModal = await CoreDomUtils.showModalLoading('core.sending', true); // Freeze the add note button. diff --git a/src/core/features/comments/pages/viewer/viewer.ts b/src/core/features/comments/pages/viewer/viewer.ts index b5f4d3c4e..e1a077947 100644 --- a/src/core/features/comments/pages/viewer/viewer.ts +++ b/src/core/features/comments/pages/viewer/viewer.ts @@ -38,11 +38,11 @@ import { CoreError } from '@classes/errors/error'; import { CoreCommentsOffline } from '@features/comments/services/comments-offline'; import { CoreCommentsDBRecord } from '@features/comments/services/database/comments'; import { CoreTimeUtils } from '@services/utils/time'; -import { CoreApp } from '@services/app'; import { CoreNetwork } from '@services/network'; import moment from 'moment-timezone'; import { Subscription } from 'rxjs'; import { CoreAnimations } from '@components/animations'; +import { CoreKeyboard } from '@singletons/keyboard'; /** * Page that displays comments. @@ -309,7 +309,7 @@ export class CoreCommentsViewerPage implements OnInit, OnDestroy { * @param text Comment text to add. */ async addComment(text: string): Promise { - CoreApp.closeKeyboard(); + CoreKeyboard.close(); const loadingModal = await CoreDomUtils.showModalLoading('core.sending', true); // Freeze the add comment button. this.sending = true; diff --git a/src/core/features/login/pages/credentials/credentials.ts b/src/core/features/login/pages/credentials/credentials.ts index 2f936c812..aad90fa57 100644 --- a/src/core/features/login/pages/credentials/credentials.ts +++ b/src/core/features/login/pages/credentials/credentials.ts @@ -36,6 +36,7 @@ import { CoreSitesFactory } from '@services/sites-factory'; import { EMAIL_SIGNUP_FEATURE_NAME, FORGOTTEN_PASSWORD_FEATURE_NAME } from '@features/login/constants'; import { CoreCustomURLSchemes } from '@services/urlschemes'; import { CoreSiteError } from '@classes/errors/siteerror'; +import { CoreKeyboard } from '@singletons/keyboard'; /** * Page to enter the user credentials. @@ -253,7 +254,7 @@ export class CoreLoginCredentialsPage implements OnInit, OnDestroy { e?.preventDefault(); e?.stopPropagation(); - CoreApp.closeKeyboard(); + CoreKeyboard.close(); // Get input data. const siteUrl = this.site.getURL(); diff --git a/src/core/features/login/pages/reconnect/reconnect.ts b/src/core/features/login/pages/reconnect/reconnect.ts index 62215d0d5..642831241 100644 --- a/src/core/features/login/pages/reconnect/reconnect.ts +++ b/src/core/features/login/pages/reconnect/reconnect.ts @@ -15,7 +15,6 @@ import { Component, OnInit, OnDestroy, ViewChild, ElementRef } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; -import { CoreApp } from '@services/app'; import { CoreNetwork } from '@services/network'; import { CoreSiteBasicInfo, CoreSites, CoreSitesReadingStrategy } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; @@ -33,6 +32,7 @@ import { Translate } from '@singletons'; import { SafeHtml } from '@angular/platform-browser'; import { CoreSitePublicConfigResponse } from '@classes/sites/unauthenticated-site'; import { FORGOTTEN_PASSWORD_FEATURE_NAME } from '@features/login/constants'; +import { CoreKeyboard } from '@singletons/keyboard'; /** * Page to enter the user password to reconnect to a site. @@ -217,7 +217,7 @@ export class CoreLoginReconnectPage implements OnInit, OnDestroy { e.preventDefault(); e.stopPropagation(); - CoreApp.closeKeyboard(); + CoreKeyboard.close(); // Get input data. const password = this.credForm.value.password; diff --git a/src/core/features/login/pages/site/site.ts b/src/core/features/login/pages/site/site.ts index fdb6b28eb..0d7d06bf1 100644 --- a/src/core/features/login/pages/site/site.ts +++ b/src/core/features/login/pages/site/site.ts @@ -15,7 +15,6 @@ import { Component, OnInit, ViewChild, ElementRef } from '@angular/core'; import { FormBuilder, FormGroup, ValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms'; -import { CoreApp } from '@services/app'; import { CoreNetwork } from '@services/network'; import { CoreConfig } from '@services/config'; import { CoreSites, CoreSiteCheckResponse, CoreLoginSiteInfo, CoreSitesDemoSiteData } from '@services/sites'; @@ -49,6 +48,7 @@ import { CoreReferrer } from '@services/referrer'; import { CoreSitesFactory } from '@services/sites-factory'; import { ONBOARDING_DONE } from '@features/login/constants'; import { CoreUnauthenticatedSite } from '@classes/sites/unauthenticated-site'; +import { CoreKeyboard } from '@singletons/keyboard'; /** * Site (url) chooser when adding a new site. @@ -285,7 +285,7 @@ export class CoreLoginSitePage implements OnInit { e?.preventDefault(); e?.stopPropagation(); - CoreApp.closeKeyboard(); + CoreKeyboard.close(); if (!url) { CoreDomUtils.showErrorModal('core.login.siteurlrequired', true); diff --git a/src/core/features/tag/pages/search/search.ts b/src/core/features/tag/pages/search/search.ts index f6ce23666..eeeed8eef 100644 --- a/src/core/features/tag/pages/search/search.ts +++ b/src/core/features/tag/pages/search/search.ts @@ -14,7 +14,6 @@ import { Component, OnInit } from '@angular/core'; -import { CoreApp } from '@services/app'; import { CoreDomUtils } from '@services/utils/dom'; import { CoreUtils } from '@services/utils/utils'; import { CoreTextUtils } from '@services/utils/text'; @@ -25,6 +24,7 @@ import { CoreNavigator } from '@services/navigator'; import { CoreMainMenuDeepLinkManager } from '@features/mainmenu/classes/deep-link-manager'; import { CoreTime } from '@singletons/time'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; +import { CoreKeyboard } from '@singletons/keyboard'; /** * Page that displays most used tags and allows searching. @@ -153,7 +153,7 @@ export class CoreTagSearchPage implements OnInit { } this.logSearch = CoreTime.once(() => this.performLogSearch()); - CoreApp.closeKeyboard(); + CoreKeyboard.close(); return this.fetchTags().catch((error) => { CoreDomUtils.showErrorModalDefault(error, 'Error loading tags.'); diff --git a/src/core/features/user/pages/participants/participants.page.ts b/src/core/features/user/pages/participants/participants.page.ts index 12aff7f44..c8d93275e 100644 --- a/src/core/features/user/pages/participants/participants.page.ts +++ b/src/core/features/user/pages/participants/participants.page.ts @@ -14,7 +14,6 @@ import { AfterViewInit, Component, OnDestroy, OnInit, ViewChild } from '@angular/core'; -import { CoreApp } from '@services/app'; import { CoreDomUtils } from '@services/utils/dom'; import { CoreNavigator } from '@services/navigator'; import { CoreListItemsManager } from '@classes/items-management/list-items-manager'; @@ -25,6 +24,7 @@ import { CoreUserParticipantsSource } from '@features/user/classes/participants- import { CoreRoutedItemsManagerSourcesTracker } from '@classes/items-management/routed-items-manager-sources-tracker'; import { CoreAnalytics, CoreAnalyticsEventType } from '@services/analytics'; import { Translate } from '@singletons'; +import { CoreKeyboard } from '@singletons/keyboard'; /** * Page that displays the list of course participants. @@ -114,7 +114,7 @@ export class CoreUserParticipantsPage implements OnInit, AfterViewInit, OnDestro * @param query Text to search for. */ async search(query: string): Promise { - CoreApp.closeKeyboard(); + CoreKeyboard.close(); const newSource = CoreRoutedItemsManagerSourcesTracker.getOrCreateSource( CoreUserParticipantsSource, diff --git a/src/core/initializers/subscribe-to-keyboard-events.ts b/src/core/initializers/subscribe-to-keyboard-events.ts index 56728d493..a160dabc0 100644 --- a/src/core/initializers/subscribe-to-keyboard-events.ts +++ b/src/core/initializers/subscribe-to-keyboard-events.ts @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { CoreApp } from '@services/app'; +import { CoreKeyboard } from '@singletons/keyboard'; import { NgZone, Keyboard } from '@singletons'; /** @@ -20,12 +20,11 @@ import { NgZone, Keyboard } from '@singletons'; */ export default function(): void { const zone = NgZone.instance; - const app = CoreApp.instance; const keyboard = Keyboard.instance; // Execute callbacks in the Angular zone, so change detection doesn't stop working. - keyboard.onKeyboardShow().subscribe(data => zone.run(() => app.onKeyboardShow(data.keyboardHeight))); - keyboard.onKeyboardHide().subscribe(() => zone.run(() => app.onKeyboardHide())); - keyboard.onKeyboardWillShow().subscribe(() => zone.run(() => app.onKeyboardWillShow())); - keyboard.onKeyboardWillHide().subscribe(() => zone.run(() => app.onKeyboardWillHide())); + keyboard.onKeyboardShow().subscribe(data => zone.run(() => CoreKeyboard.onKeyboardShow(data.keyboardHeight))); + keyboard.onKeyboardHide().subscribe(() => zone.run(() => CoreKeyboard.onKeyboardHide())); + keyboard.onKeyboardWillShow().subscribe(() => zone.run(() => CoreKeyboard.onKeyboardWillShow())); + keyboard.onKeyboardWillHide().subscribe(() => zone.run(() => CoreKeyboard.onKeyboardWillHide())); } diff --git a/src/core/services/app.ts b/src/core/services/app.ts index a71d7b8f7..e980222b2 100644 --- a/src/core/services/app.ts +++ b/src/core/services/app.ts @@ -18,7 +18,7 @@ import { CoreDB } from '@services/db'; import { CoreEventObserver, CoreEvents } from '@singletons/events'; import { SQLiteDB, SQLiteDBTableSchema } from '@classes/sqlitedb'; -import { makeSingleton, Keyboard, StatusBar } from '@singletons'; +import { makeSingleton, StatusBar } from '@singletons'; import { CoreLogger } from '@singletons/logger'; import { CoreColors } from '@singletons/colors'; import { DBNAME, SCHEMA_VERSIONS_TABLE_NAME, SCHEMA_VERSIONS_TABLE_SCHEMA, SchemaVersionsDBEntry } from '@services/database/app'; @@ -32,6 +32,7 @@ import { Subscription } from 'rxjs'; import { CorePlatform } from '@services/platform'; import { CoreNetwork, CoreNetworkConnection } from '@services/network'; import { CoreMainMenuProvider } from '@features/mainmenu/services/mainmenu'; +import { CoreKeyboard } from '@singletons/keyboard'; /** * Factory to provide some global functionalities, like access to the global app database. @@ -52,9 +53,6 @@ export class CoreAppProvider { protected db?: SQLiteDB; protected logger: CoreLogger; protected ssoAuthenticationDeferred?: CorePromisedValue; - protected isKeyboardShown = false; - protected keyboardOpening = false; - protected keyboardClosing = false; protected redirect?: CoreRedirectData; protected schemaVersionsTable = asyncInstance>(); protected mainMenuListener?: CoreEventObserver; @@ -129,11 +127,11 @@ export class CoreAppProvider { /** * Closes the keyboard. + * + * @deprecated sinde 4.5.0. Use CoreKeyboard.closeKeyboard instead. */ closeKeyboard(): void { - if (CorePlatform.isMobile()) { - Keyboard.hide(); - } + CoreKeyboard.close(); } /** @@ -246,27 +244,30 @@ export class CoreAppProvider { * Check if the keyboard is closing. * * @returns Whether keyboard is closing (animating). + * @deprecated since 4.5.0. Use CoreKeyboard.isKeyboardClosing instead. */ isKeyboardClosing(): boolean { - return this.keyboardClosing; + return CoreKeyboard.isKeyboardClosing(); } /** * Check if the keyboard is being opened. * * @returns Whether keyboard is opening (animating). + * @deprecated since 4.5.0. Use CoreKeyboard.isKeyboardOpening instead. */ isKeyboardOpening(): boolean { - return this.keyboardOpening; + return CoreKeyboard.isKeyboardOpening(); } /** * Check if the keyboard is visible. * * @returns Whether keyboard is visible. + * @deprecated since 4.5.0. Use CoreKeyboard.isKeyboardVisible instead. */ isKeyboardVisible(): boolean { - return this.isKeyboardShown; + return CoreKeyboard.isKeyboardVisible(); } /** @@ -320,61 +321,48 @@ export class CoreAppProvider { /** * Open the keyboard. + * + * @deprecated since 4.5.0. Use CoreKeyboard.openKeyboard instead. */ openKeyboard(): void { - // Open keyboard is not supported in desktop and in iOS. - if (CorePlatform.isAndroid()) { - Keyboard.show(); - } + CoreKeyboard.open(); } /** * Notify that Keyboard has been shown. * * @param keyboardHeight Keyboard height. + * @deprecated since 4.5.0. Use CoreKeyboard.onKeyboardShow instead. */ onKeyboardShow(keyboardHeight: number): void { - document.body.classList.add('keyboard-is-open'); - this.setKeyboardShown(true); - // Error on iOS calculating size. - // More info: https://github.com/ionic-team/ionic-plugin-keyboard/issues/276 . - CoreEvents.trigger(CoreEvents.KEYBOARD_CHANGE, keyboardHeight); + CoreKeyboard.onKeyboardShow(keyboardHeight); } /** * Notify that Keyboard has been hidden. + * + * @deprecated since 4.5.0. Use CoreKeyboard.onKeyboardHide instead. */ onKeyboardHide(): void { - document.body.classList.remove('keyboard-is-open'); - this.setKeyboardShown(false); - CoreEvents.trigger(CoreEvents.KEYBOARD_CHANGE, 0); + CoreKeyboard.onKeyboardHide(); } /** * Notify that Keyboard is about to be shown. + * + * @deprecated since 4.5.0. Use CoreKeyboard.onKeyboardWillShow instead. */ onKeyboardWillShow(): void { - this.keyboardOpening = true; - this.keyboardClosing = false; + CoreKeyboard.onKeyboardWillShow(); } /** * Notify that Keyboard is about to be hidden. + * + * @deprecated since 4.5.0. Use CoreKeyboard.onKeyboardWillHide instead. */ onKeyboardWillHide(): void { - this.keyboardOpening = false; - this.keyboardClosing = true; - } - - /** - * Set keyboard shown or hidden. - * - * @param shown Whether the keyboard is shown or hidden. - */ - protected setKeyboardShown(shown: boolean): void { - this.isKeyboardShown = shown; - this.keyboardOpening = false; - this.keyboardClosing = false; + CoreKeyboard.onKeyboardWillHide(); } /** diff --git a/src/core/services/config.ts b/src/core/services/config.ts index f1872ba32..754678584 100644 --- a/src/core/services/config.ts +++ b/src/core/services/config.ts @@ -75,7 +75,7 @@ export class CoreConfigProvider { async initializeDatabase(): Promise { try { await CoreApp.createTablesFromSchema(APP_SCHEMA); - } catch (e) { + } catch { // Ignore errors. } diff --git a/src/core/services/utils/dom.ts b/src/core/services/utils/dom.ts index 47a37c03d..a1797cf7f 100644 --- a/src/core/services/utils/dom.ts +++ b/src/core/services/utils/dom.ts @@ -17,7 +17,6 @@ import { IonContent } from '@ionic/angular'; import { ModalOptions, PopoverOptions, AlertOptions, AlertButton, TextFieldTypes, ToastOptions } from '@ionic/core'; import { Md5 } from 'ts-md5'; -import { CoreApp } from '@services/app'; import { CoreConfig } from '@services/config'; import { CoreFile } from '@services/file'; import { CoreWSExternalWarning } from '@services/ws'; @@ -60,6 +59,7 @@ import { CoreLang } from '@services/lang'; import { CorePasswordModalParams, CorePasswordModalResponse } from '@components/password-modal/password-modal'; import { CoreWSError } from '@classes/errors/wserror'; import { CoreErrorLogs } from '@singletons/error-logs'; +import { CoreKeyboard } from '@singletons/keyboard'; /* * "Utils" service with helper functions for UI, DOM elements and HTML code. @@ -337,7 +337,7 @@ export class CoreDomUtilsProvider { await CoreUtils.nextTick(); if (CorePlatform.isAndroid() && this.supportsInputKeyboard(elementToFocus)) { // On some Android versions the keyboard doesn't open automatically. - CoreApp.openKeyboard(); + CoreKeyboard.open(); } break; } diff --git a/src/core/singletons/keyboard.ts b/src/core/singletons/keyboard.ts new file mode 100644 index 000000000..bb44c0d43 --- /dev/null +++ b/src/core/singletons/keyboard.ts @@ -0,0 +1,123 @@ +// (C) Copyright 2015 Moodle Pty Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { CorePlatform } from '@services/platform'; +import { Keyboard } from '@singletons'; +import { CoreEvents } from '@singletons/events'; + +/** + * Singleton with helper functions for keybard management. + */ +export class CoreKeyboard { + + protected static isKeyboardShown = false; + protected static keyboardOpening = false; + protected static keyboardClosing = false; + + /** + * Closes the keyboard. + */ + static close(): void { + if (CorePlatform.isMobile()) { + Keyboard.hide(); + } + } + + /** + * Open the keyboard. + */ + static open(): void { + // Open keyboard is not supported in desktop and in iOS. + if (CorePlatform.isAndroid()) { + Keyboard.show(); + } + } + + /** + * Notify that Keyboard has been shown. + * + * @param keyboardHeight Keyboard height. + */ + static onKeyboardShow(keyboardHeight: number): void { + document.body.classList.add('keyboard-is-open'); + this.setKeyboardShown(true); + // Error on iOS calculating size. + // More info: https://github.com/ionic-team/ionic-plugin-keyboard/issues/276 . + CoreEvents.trigger(CoreEvents.KEYBOARD_CHANGE, keyboardHeight); + } + + /** + * Notify that Keyboard has been hidden. + */ + static onKeyboardHide(): void { + document.body.classList.remove('keyboard-is-open'); + this.setKeyboardShown(false); + CoreEvents.trigger(CoreEvents.KEYBOARD_CHANGE, 0); + } + + /** + * Notify that Keyboard is about to be shown. + */ + static onKeyboardWillShow(): void { + CoreKeyboard.keyboardOpening = true; + CoreKeyboard.keyboardClosing = false; + } + + /** + * Notify that Keyboard is about to be hidden. + */ + static onKeyboardWillHide(): void { + CoreKeyboard.keyboardOpening = false; + CoreKeyboard.keyboardClosing = true; + } + + /** + * Set keyboard shown or hidden. + * + * @param shown Whether the keyboard is shown or hidden. + */ + protected static setKeyboardShown(shown: boolean): void { + CoreKeyboard.isKeyboardShown = shown; + CoreKeyboard.keyboardOpening = false; + CoreKeyboard.keyboardClosing = false; + } + + /** + * Check if the keyboard is closing. + * + * @returns Whether keyboard is closing (animating). + */ + static isKeyboardClosing(): boolean { + return CoreKeyboard.keyboardClosing; + } + + /** + * Check if the keyboard is being opened. + * + * @returns Whether keyboard is opening (animating). + */ + static isKeyboardOpening(): boolean { + return CoreKeyboard.keyboardOpening; + } + + /** + * Check if the keyboard is visible. + * + * @returns Whether keyboard is visible. + */ + static isKeyboardVisible(): boolean { + return CoreKeyboard.isKeyboardShown; + } + +}