From aee9ada1b8394f8b09266e59382c3a8ae7cf412c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Tue, 6 Mar 2018 12:47:51 +0100 Subject: [PATCH 1/3] MOBILE-2347 page: Page activity implementation --- .../mod/page/components/components.module.ts | 45 ++++ .../mod/page/components/index/index.html | 21 ++ src/addon/mod/page/components/index/index.ts | 194 ++++++++++++++++++ src/addon/mod/page/lang/en.json | 3 + src/addon/mod/page/page.module.ts | 53 +++++ src/addon/mod/page/pages/index/index.html | 16 ++ .../mod/page/pages/index/index.module.ts | 33 +++ src/addon/mod/page/pages/index/index.ts | 48 +++++ src/addon/mod/page/providers/helper.ts | 114 ++++++++++ src/addon/mod/page/providers/link-handler.ts | 30 +++ .../mod/page/providers/module-handler.ts | 71 +++++++ src/addon/mod/page/providers/page.ts | 158 ++++++++++++++ .../mod/page/providers/pluginfile-handler.ts | 49 +++++ .../mod/page/providers/prefetch-handler.ts | 85 ++++++++ src/app/app.module.ts | 2 + src/directives/format-text.ts | 2 +- 16 files changed, 923 insertions(+), 1 deletion(-) create mode 100644 src/addon/mod/page/components/components.module.ts create mode 100644 src/addon/mod/page/components/index/index.html create mode 100644 src/addon/mod/page/components/index/index.ts create mode 100644 src/addon/mod/page/lang/en.json create mode 100644 src/addon/mod/page/page.module.ts create mode 100644 src/addon/mod/page/pages/index/index.html create mode 100644 src/addon/mod/page/pages/index/index.module.ts create mode 100644 src/addon/mod/page/pages/index/index.ts create mode 100644 src/addon/mod/page/providers/helper.ts create mode 100644 src/addon/mod/page/providers/link-handler.ts create mode 100644 src/addon/mod/page/providers/module-handler.ts create mode 100644 src/addon/mod/page/providers/page.ts create mode 100644 src/addon/mod/page/providers/pluginfile-handler.ts create mode 100644 src/addon/mod/page/providers/prefetch-handler.ts diff --git a/src/addon/mod/page/components/components.module.ts b/src/addon/mod/page/components/components.module.ts new file mode 100644 index 000000000..05b57e010 --- /dev/null +++ b/src/addon/mod/page/components/components.module.ts @@ -0,0 +1,45 @@ +// (C) Copyright 2015 Martin Dougiamas +// +// 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 { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { IonicModule } from 'ionic-angular'; +import { TranslateModule } from '@ngx-translate/core'; +import { CoreComponentsModule } from '@components/components.module'; +import { CoreDirectivesModule } from '@directives/directives.module'; +import { CoreCourseComponentsModule } from '@core/course/components/components.module'; +import { AddonModPageIndexComponent } from './index/index'; + +@NgModule({ + declarations: [ + AddonModPageIndexComponent + ], + imports: [ + CommonModule, + IonicModule, + TranslateModule.forChild(), + CoreComponentsModule, + CoreDirectivesModule, + CoreCourseComponentsModule + ], + providers: [ + ], + exports: [ + AddonModPageIndexComponent + ], + entryComponents: [ + AddonModPageIndexComponent + ] +}) +export class AddonModPageComponentsModule {} diff --git a/src/addon/mod/page/components/index/index.html b/src/addon/mod/page/components/index/index.html new file mode 100644 index 000000000..1c4b04a58 --- /dev/null +++ b/src/addon/mod/page/components/index/index.html @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + +
+ +
+ +
diff --git a/src/addon/mod/page/components/index/index.ts b/src/addon/mod/page/components/index/index.ts new file mode 100644 index 000000000..30420a5c4 --- /dev/null +++ b/src/addon/mod/page/components/index/index.ts @@ -0,0 +1,194 @@ +// (C) Copyright 2015 Martin Dougiamas +// +// 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 { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { CoreAppProvider } from '@providers/app'; +import { CoreDomUtilsProvider } from '@providers/utils/dom'; +import { CoreTextUtilsProvider } from '@providers/utils/text'; +import { CoreCourseProvider } from '@core/course/providers/course'; +import { CoreCourseHelperProvider } from '@core/course/providers/helper'; +import { CoreCourseModuleMainComponent } from '@core/course/providers/module-delegate'; +import { AddonModPageProvider } from '../../providers/page'; +import { AddonModPageHelperProvider } from '../../providers/helper'; +import { AddonModPagePrefetchHandler } from '../../providers/prefetch-handler'; + +/** + * Component that displays a page. + */ +@Component({ + selector: 'addon-mod-page-index', + templateUrl: 'index.html', +}) +export class AddonModPageIndexComponent implements OnInit, OnDestroy, CoreCourseModuleMainComponent { + @Input() module: any; // The module of the page. + @Input() courseId: number; // Course ID the page belongs to. + @Output() pageRetrieved?: EventEmitter; + + loaded: boolean; + component = AddonModPageProvider.COMPONENT; + componentId: number; + canGetPage: boolean; + contents: any; + + // Data for context menu. + externalUrl: string; + description: string; + refreshIcon: string; + prefetchStatusIcon: string; + prefetchText: string; + size: string; + + protected isDestroyed; + protected statusObserver; + + constructor(private pageProvider: AddonModPageProvider, private courseProvider: CoreCourseProvider, + private domUtils: CoreDomUtilsProvider, private appProvider: CoreAppProvider, private textUtils: CoreTextUtilsProvider, + private courseHelper: CoreCourseHelperProvider, private translate: TranslateService, + private pageHelper: AddonModPageHelperProvider, private pagePrefetch: AddonModPagePrefetchHandler) { + this.pageRetrieved = new EventEmitter(); + } + + /** + * Component being initialized. + */ + ngOnInit(): void { + this.description = this.module.description; + this.componentId = this.module.id; + this.externalUrl = this.module.url; + this.loaded = false; + this.refreshIcon = 'spinner'; + + this.canGetPage = this.pageProvider.isGetPageWSAvailable(); + + this.fetchContent().then(() => { + this.pageProvider.logView(this.module.instance).then(() => { + this.courseProvider.checkModuleCompletion(this.courseId, this.module.completionstatus); + }); + }); + } + + /** + * Refresh the data. + * + * @param {any} [refresher] Refresher. + * @param {Function} [done] Function to call when done. + * @return {Promise} Promise resolved when done. + */ + doRefresh(refresher?: any, done?: () => void): Promise { + if (this.loaded) { + this.refreshIcon = 'spinner'; + + return this.pageProvider.invalidateContent(this.module.id, this.courseId).catch(() => { + // Ignore errors. + }).then(() => { + return this.fetchContent(true); + }).finally(() => { + this.refreshIcon = 'refresh'; + refresher && refresher.complete(); + done && done(); + }); + } + + return Promise.resolve(); + } + + /** + * Expand the description. + */ + expandDescription(): void { + this.textUtils.expandText(this.translate.instant('core.description'), this.description, this.component, this.module.id); + } + + /** + * Prefetch the module. + */ + prefetch(): void { + this.courseHelper.contextMenuPrefetch(this, this.module, this.courseId); + } + + /** + * Confirm and remove downloaded files. + */ + removeFiles(): void { + this.courseHelper.confirmAndRemoveFiles(this.module, this.courseId); + } + + /** + * Download page contents. + * + * @param {boolean} [refresh] Whether we're refreshing data. + * @return {Promise} Promise resolved when done. + */ + protected fetchContent(refresh?: boolean): Promise { + let downloadFailed = false; + + // Download content. This function also loads module contents if needed. + return this.pagePrefetch.download(this.module, this.courseId).catch(() => { + // Mark download as failed but go on since the main files could have been downloaded. + downloadFailed = true; + }).then(() => { + if (!this.module.contents.length) { + // Try to load module contents for offline usage. + return this.courseProvider.loadModuleContents(this.module, this.courseId); + } + }).then(() => { + const promises = []; + + let getPagePromise; + + // Get the module to get the latest title and description. Data should've been updated in download. + if (this.canGetPage) { + getPagePromise = this.pageProvider.getPageData(this.courseId, this.module.id); + } else { + getPagePromise = this.courseProvider.getModule(this.module.id, this.courseId); + } + + promises.push(getPagePromise.then((page) => { + if (page) { + this.description = page.intro || page.description; + this.pageRetrieved.emit(page); + } + }).catch(() => { + // Ignore errors. + })); + + // Get the page HTML. + promises.push(this.pageHelper.getPageHtml(this.module.contents, this.module.id).then((content) => { + // All data obtained, now fill the context menu. + this.courseHelper.fillContextMenu(this, this.module, this.courseId, refresh, this.component); + + this.contents = content; + + if (downloadFailed && this.appProvider.isOnline()) { + // We could load the main file but the download failed. Show error message. + this.domUtils.showErrorModal('core.errordownloadingsomefiles', true); + } + })); + + return Promise.all(promises); + }).catch((error) => { + // Error getting data, fail. + this.domUtils.showErrorModalDefault(error, 'addon.mod_page.errorwhileloadingthepage', true); + }).finally(() => { + this.loaded = true; + this.refreshIcon = 'refresh'; + }); + } + + ngOnDestroy(): void { + this.isDestroyed = true; + this.statusObserver && this.statusObserver.off(); + } +} diff --git a/src/addon/mod/page/lang/en.json b/src/addon/mod/page/lang/en.json new file mode 100644 index 000000000..4dd39dc19 --- /dev/null +++ b/src/addon/mod/page/lang/en.json @@ -0,0 +1,3 @@ +{ + "errorwhileloadingthepage": "Error while loading the page content." +} \ No newline at end of file diff --git a/src/addon/mod/page/page.module.ts b/src/addon/mod/page/page.module.ts new file mode 100644 index 000000000..a009e6531 --- /dev/null +++ b/src/addon/mod/page/page.module.ts @@ -0,0 +1,53 @@ +// (C) Copyright 2015 Martin Dougiamas +// +// 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 { NgModule } from '@angular/core'; +import { AddonModPageComponentsModule } from './components/components.module'; +import { AddonModPageModuleHandler } from './providers/module-handler'; +import { AddonModPageProvider } from './providers/page'; +import { AddonModPagePrefetchHandler } from './providers/prefetch-handler'; +import { AddonModPageLinkHandler } from './providers/link-handler'; +import { AddonModPagePluginFileHandler } from './providers/pluginfile-handler'; +import { AddonModPageHelperProvider } from './providers/helper'; +import { CoreContentLinksDelegate } from '@core/contentlinks/providers/delegate'; +import { CoreCourseModuleDelegate } from '@core/course/providers/module-delegate'; +import { CoreCourseModulePrefetchDelegate } from '@core/course/providers/module-prefetch-delegate'; +import { CorePluginFileDelegate } from '@providers/plugin-file-delegate'; + +@NgModule({ + declarations: [ + ], + imports: [ + AddonModPageComponentsModule + ], + providers: [ + AddonModPageProvider, + AddonModPageModuleHandler, + AddonModPageHelperProvider, + AddonModPagePrefetchHandler, + AddonModPageLinkHandler, + AddonModPagePluginFileHandler + ] +}) +export class AddonModPageModule { + constructor(moduleDelegate: CoreCourseModuleDelegate, moduleHandler: AddonModPageModuleHandler, + prefetchDelegate: CoreCourseModulePrefetchDelegate, prefetchHandler: AddonModPagePrefetchHandler, + contentLinksDelegate: CoreContentLinksDelegate, linkHandler: AddonModPageLinkHandler, + pluginfileDelegate: CorePluginFileDelegate, pluginfileHandler: AddonModPagePluginFileHandler) { + moduleDelegate.registerHandler(moduleHandler); + prefetchDelegate.registerHandler(prefetchHandler); + contentLinksDelegate.registerHandler(linkHandler); + pluginfileDelegate.registerHandler(pluginfileHandler); + } +} diff --git a/src/addon/mod/page/pages/index/index.html b/src/addon/mod/page/pages/index/index.html new file mode 100644 index 000000000..88b576c88 --- /dev/null +++ b/src/addon/mod/page/pages/index/index.html @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/src/addon/mod/page/pages/index/index.module.ts b/src/addon/mod/page/pages/index/index.module.ts new file mode 100644 index 000000000..b4d02aab9 --- /dev/null +++ b/src/addon/mod/page/pages/index/index.module.ts @@ -0,0 +1,33 @@ +// (C) Copyright 2015 Martin Dougiamas +// +// 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 { NgModule } from '@angular/core'; +import { IonicPageModule } from 'ionic-angular'; +import { TranslateModule } from '@ngx-translate/core'; +import { CoreDirectivesModule } from '@directives/directives.module'; +import { AddonModPageComponentsModule } from '../../components/components.module'; +import { AddonModPageIndexPage } from './index'; + +@NgModule({ + declarations: [ + AddonModPageIndexPage, + ], + imports: [ + CoreDirectivesModule, + AddonModPageComponentsModule, + IonicPageModule.forChild(AddonModPageIndexPage), + TranslateModule.forChild() + ], +}) +export class AddonModPageIndexPageModule {} diff --git a/src/addon/mod/page/pages/index/index.ts b/src/addon/mod/page/pages/index/index.ts new file mode 100644 index 000000000..089c14afb --- /dev/null +++ b/src/addon/mod/page/pages/index/index.ts @@ -0,0 +1,48 @@ +// (C) Copyright 2015 Martin Dougiamas +// +// 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 { Component, ViewChild } from '@angular/core'; +import { IonicPage, NavParams } from 'ionic-angular'; +import { AddonModPageIndexComponent } from '../../components/index/index'; + +/** + * Page that displays a page. + */ +@IonicPage({ segment: 'addon-mod-page-index' }) +@Component({ + selector: 'page-addon-mod-page-index', + templateUrl: 'index.html', +}) +export class AddonModPageIndexPage { + @ViewChild(AddonModPageIndexComponent) pageComponent: AddonModPageIndexComponent; + + title: string; + module: any; + courseId: number; + + constructor(navParams: NavParams) { + this.module = navParams.get('module') || {}; + this.courseId = navParams.get('courseId'); + this.title = this.module.name; + } + + /** + * Update some data based on the page instance. + * + * @param {any} page Page instance. + */ + updateData(page: any): void { + this.title = page.name || this.title; + } +} diff --git a/src/addon/mod/page/providers/helper.ts b/src/addon/mod/page/providers/helper.ts new file mode 100644 index 000000000..0c15ecdff --- /dev/null +++ b/src/addon/mod/page/providers/helper.ts @@ -0,0 +1,114 @@ +// (C) Copyright 2015 Martin Dougiamas +// +// 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 { Injectable } from '@angular/core'; +import { CoreLoggerProvider } from '@providers/logger'; +import { CoreDomUtilsProvider } from '@providers/utils/dom'; +import { CoreTextUtilsProvider } from '@providers/utils/text'; +import { CoreFilepoolProvider } from '@providers/filepool'; +import { AddonModPageProvider } from './page'; +import { CoreFileProvider } from '@providers/file'; +import { CoreSitesProvider } from '@providers/sites'; +import { Http, Response } from '@angular/http'; + +/** + * Service that provides some features for page. + */ +@Injectable() +export class AddonModPageHelperProvider { + + protected logger; + + constructor(logger: CoreLoggerProvider, private domUtils: CoreDomUtilsProvider, private filepoolProvider: CoreFilepoolProvider, + private fileProvider: CoreFileProvider, private textUtils: CoreTextUtilsProvider, private http: Http, + private sitesProvider: CoreSitesProvider) { + this.logger = logger.getInstance('AddonModPageHelperProvider'); + } + + /** + * Gets the page HTML. + * + * @param {any} contents The module contents. + * @param {number} moduleId The module ID. + * @return {Promise} The HTML of the page. + */ + getPageHtml(contents: any, moduleId: number): Promise { + let indexUrl, + promise; + const paths = {}; + + // Extract the information about paths from the module contents. + contents.forEach((content) => { + const url = content.fileurl; + + if (this.isMainPage(content)) { + // This seems to be the most reliable way to spot the index page. + indexUrl = url; + } else { + let key = content.filename; + if (content.filepath !== '/') { + // Add the folders without the leading slash. + key = content.filepath.substr(1) + key; + } + paths[this.textUtils.decodeURIComponent(key)] = url; + } + }); + + // Promise handling when we are in a browser. + if (!indexUrl) { + // If ever that happens. + this.logger.debug('Could not locate the index page'); + promise = Promise.reject(null); + } else if (this.fileProvider.isAvailable()) { + // The file system is available. + promise = this.filepoolProvider.downloadUrl(this.sitesProvider.getCurrentSiteId(), indexUrl, false, + AddonModPageProvider.COMPONENT, moduleId); + } else { + // We return the live URL. + promise = Promise.resolve(this.sitesProvider.getCurrentSite().fixPluginfileURL(indexUrl)); + } + + return promise.then((url) => { + + // Fetch the URL content. + const promise = this.http.get(url).toPromise(); + + return promise.then((response: Response): any => { + const content = response.text(); + if (typeof content !== 'string') { + return Promise.reject(null); + } + + // Now that we have the content, we update the SRC to point back to the external resource. + // That will be caught by core-format-text. + return this.domUtils.restoreSourcesInHtml(content, paths); + }); + }); + } + + /** + * Returns whether the file is the main page of the module. + * + * @param {any} file An object returned from WS containing file info. + * @return {boolean} Whether the file is the main page or not. + */ + protected isMainPage(file: any): boolean { + const filename = file.filename || '', + fileurl = file.fileurl || '', + url = '/mod_page/content/index.html', + encodedUrl = encodeURIComponent(url); + + return (filename === 'index.html' && (fileurl.indexOf(url) > 0 || fileurl.indexOf(encodedUrl) > 0 )); + } +} diff --git a/src/addon/mod/page/providers/link-handler.ts b/src/addon/mod/page/providers/link-handler.ts new file mode 100644 index 000000000..73f2ca507 --- /dev/null +++ b/src/addon/mod/page/providers/link-handler.ts @@ -0,0 +1,30 @@ +// (C) Copyright 2015 Martin Dougiamas +// +// 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 { Injectable } from '@angular/core'; +import { CoreContentLinksModuleIndexHandler } from '@core/contentlinks/classes/module-index-handler'; +import { CoreCourseHelperProvider } from '@core/course/providers/helper'; +import { AddonModPageProvider } from './page'; + +/** + * Handler to treat links to resource. + */ +@Injectable() +export class AddonModPageLinkHandler extends CoreContentLinksModuleIndexHandler { + name = 'AddonModPageLinkHandler'; + + constructor(courseHelper: CoreCourseHelperProvider) { + super(courseHelper, AddonModPageProvider.COMPONENT, 'page'); + } +} diff --git a/src/addon/mod/page/providers/module-handler.ts b/src/addon/mod/page/providers/module-handler.ts new file mode 100644 index 000000000..88d14ebd5 --- /dev/null +++ b/src/addon/mod/page/providers/module-handler.ts @@ -0,0 +1,71 @@ +// (C) Copyright 2015 Martin Dougiamas +// +// 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 { Injectable } from '@angular/core'; +import { NavController, NavOptions } from 'ionic-angular'; +import { AddonModPageProvider } from './page'; +import { AddonModPageIndexComponent } from '../components/index/index'; +import { CoreCourseModuleHandler, CoreCourseModuleHandlerData } from '@core/course/providers/module-delegate'; +import { CoreCourseProvider } from '@core/course/providers/course'; + +/** + * Handler to support page modules. + */ +@Injectable() +export class AddonModPageModuleHandler implements CoreCourseModuleHandler { + name = 'page'; + + constructor(private courseProvider: CoreCourseProvider, protected pageProvider: AddonModPageProvider) { } + + /** + * Check if the handler is enabled on a site level. + * + * @return {boolean|Promise} Whether or not the handler is enabled on a site level. + */ + isEnabled(): boolean | Promise { + return this.pageProvider.isPluginEnabled(); + } + + /** + * Get the data required to display the module in the course contents view. + * + * @param {any} module The module object. + * @param {number} courseId The course ID. + * @param {number} sectionId The section ID. + * @return {CoreCourseModuleHandlerData} Data to render the module. + */ + getData(module: any, courseId: number, sectionId: number): CoreCourseModuleHandlerData { + return { + icon: this.courseProvider.getModuleIconSrc('page'), + title: module.name, + class: 'addon-mod_page-handler', + showDownloadButton: true, + action(event: Event, navCtrl: NavController, module: any, courseId: number, options: NavOptions): void { + navCtrl.push('AddonModPageIndexPage', {module: module, courseId: courseId}, options); + } + }; + } + + /** + * Get the component to render the module. This is needed to support singleactivity course format. + * The component returned must implement CoreCourseModuleMainComponent. + * + * @param {any} course The course object. + * @param {any} module The module object. + * @return {any} The component to use, undefined if not found. + */ + getMainComponent(course: any, module: any): any { + return AddonModPageIndexComponent; + } +} diff --git a/src/addon/mod/page/providers/page.ts b/src/addon/mod/page/providers/page.ts new file mode 100644 index 000000000..aa9e68a18 --- /dev/null +++ b/src/addon/mod/page/providers/page.ts @@ -0,0 +1,158 @@ +// (C) Copyright 2015 Martin Dougiamas +// +// 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 { Injectable } from '@angular/core'; +import { CoreLoggerProvider } from '@providers/logger'; +import { CoreSitesProvider } from '@providers/sites'; +import { CoreUtilsProvider } from '@providers/utils/utils'; +import { CoreCourseProvider } from '@core/course/providers/course'; +import { CoreFilepoolProvider } from '@providers/filepool'; + +/** + * Service that provides some features for page. + */ +@Injectable() +export class AddonModPageProvider { + static COMPONENT = 'mmaModPage'; + + protected ROOT_CACHE_KEY = 'mmaModPage:'; + protected logger; + + constructor(logger: CoreLoggerProvider, private sitesProvider: CoreSitesProvider, private courseProvider: CoreCourseProvider, + private utils: CoreUtilsProvider, private filepoolProvider: CoreFilepoolProvider) { + this.logger = logger.getInstance('mmaModPageProvider'); + } + + /** + * Get a page by course module ID. + * + * @param {number} courseId Course ID. + * @param {number} cmId Course module ID. + * @param {string} [siteId] Site ID. If not defined, current site. + * @return {Promise} Promise resolved when the book is retrieved. + */ + getPageData(courseId: number, cmId: number, siteId?: string): Promise { + return this.getPageByKey(courseId, 'coursemodule', cmId, siteId); + } + + /** + * Get a page. + * + * @param {number} courseId Course ID. + * @param {string} key Name of the property to check. + * @param {any} value Value to search. + * @param {string} [siteId] Site ID. If not defined, current site. + * @return {Promise} Promise resolved when the book is retrieved. + */ + protected getPageByKey(courseId: number, key: string, value: any, siteId?: string): Promise { + return this.sitesProvider.getSite(siteId).then((site) => { + const params = { + courseids: [courseId] + }, + preSets = { + cacheKey: this.getPageCacheKey(courseId) + }; + + return site.read('mod_page_get_pages_by_courses', params, preSets).then((response) => { + if (response && response.pages) { + const currentPage = response.pages.find((page) => { + return page[key] == value; + }); + if (currentPage) { + return currentPage; + } + } + + return Promise.reject(null); + }); + }); + } + + /** + * Get cache key for page data WS calls. + * + * @param {number} courseId Course ID. + * @return {string} Cache key. + */ + protected getPageCacheKey(courseId: number): string { + return this.ROOT_CACHE_KEY + 'page:' + courseId; + } + + /** + * Invalidate the prefetched content. + * + * @param {number} moduleId The module ID. + * @param {number} courseId Course ID of the module. + * @param {string} [siteId] Site ID. If not defined, current site. + * @return {Promise} + */ + invalidateContent(moduleId: number, courseId: number, siteId?: string): Promise { + const promises = []; + + promises.push(this.invalidatePageData(courseId, siteId)); + promises.push(this.filepoolProvider.invalidateFilesByComponent(siteId, AddonModPageProvider.COMPONENT, moduleId)); + promises.push(this.courseProvider.invalidateModule(moduleId, siteId)); + + return this.utils.allPromises(promises); + } + + /** + * Invalidates page data. + * + * @param {number} courseId Course ID. + * @param {string} [siteId] Site ID. If not defined, current site. + * @return {Promise} Promise resolved when the data is invalidated. + */ + invalidatePageData(courseId: number, siteId?: string): Promise { + return this.sitesProvider.getSite(siteId).then((site) => { + return site.invalidateWsCacheForKey(this.getPageCacheKey(courseId)); + }); + } + + /** + * Returns whether or not getPage WS available or not. + * + * @return {boolean} If WS is avalaible. + * @since 3.3 + */ + isGetPageWSAvailable(): boolean { + return this.sitesProvider.wsAvailableInCurrentSite('mod_page_get_pages_by_courses'); + } + + /** + * Return whether or not the plugin is enabled. + * + * @param {string} [siteId] Site ID. If not defined, current site. + * @return {Promise} Promise resolved with true if plugin is enabled, rejected or resolved with false otherwise. + */ + isPluginEnabled(siteId?: string): Promise { + return this.sitesProvider.getSite(siteId).then((site) => { + return site.canDownloadFiles(); + }); + } + + /** + * Report a page as being viewed. + * + * @param {number} id Module ID. + * @return {Promise} Promise resolved when the WS call is successful. + */ + logView(id: number): Promise { + const params = { + pageid: id + }; + + return this.sitesProvider.getCurrentSite().write('mod_page_view_page', params); + } +} diff --git a/src/addon/mod/page/providers/pluginfile-handler.ts b/src/addon/mod/page/providers/pluginfile-handler.ts new file mode 100644 index 000000000..63719c389 --- /dev/null +++ b/src/addon/mod/page/providers/pluginfile-handler.ts @@ -0,0 +1,49 @@ +// (C) Copyright 2015 Martin Dougiamas +// +// 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 { Injectable } from '@angular/core'; +import { CorePluginFileHandler } from '@providers/plugin-file-delegate'; + +/** + * Handler to treat links to page. + */ +@Injectable() +export class AddonModPagePluginFileHandler implements CorePluginFileHandler { + name = 'AddonModPagePluginFileHandler'; + + /** + * Return the RegExp to match the revision on pluginfile URLs. + * + * @param {string[]} args Arguments of the pluginfile URL defining component and filearea at least. + * @return {RegExp} RegExp to match the revision on pluginfile URLs. + */ + getComponentRevisionRegExp(args: string[]): RegExp { + // Check filearea. + if (args[2] == 'content') { + // Component + Filearea + Revision + return new RegExp('/mod_page/content/([0-9]+)/'); + } + } + + /** + * Should return the string to remove the revision on pluginfile url. + * + * @param {string[]} args Arguments of the pluginfile URL defining component and filearea at least. + * @return {string} String to remove the revision on pluginfile url. + */ + getComponentRevisionReplace(args: string[]): string { + // Component + Filearea + Revision + return '/mod_page/content/0/'; + } +} diff --git a/src/addon/mod/page/providers/prefetch-handler.ts b/src/addon/mod/page/providers/prefetch-handler.ts new file mode 100644 index 000000000..8ee99b75a --- /dev/null +++ b/src/addon/mod/page/providers/prefetch-handler.ts @@ -0,0 +1,85 @@ +// (C) Copyright 2015 Martin Dougiamas +// +// 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 { Injectable, Injector } from '@angular/core'; +import { CoreCourseModulePrefetchHandlerBase } from '@core/course/classes/module-prefetch-handler'; +import { CoreUtilsProvider } from '@providers/utils/utils'; +import { AddonModPageProvider } from './page'; +import { AddonModPageHelperProvider } from './helper'; + +/** + * Handler to prefetch pages. + */ +@Injectable() +export class AddonModPagePrefetchHandler extends CoreCourseModulePrefetchHandlerBase { + name = 'page'; + component = AddonModPageProvider.COMPONENT; + updatesNames = /^configuration$|^.*files$/; + isResource = true; + + constructor(injector: Injector, protected pageProvider: AddonModPageProvider, protected utils: CoreUtilsProvider, + protected pageHelper: AddonModPageHelperProvider) { + super(injector); + } + + /** + * Download or prefetch the content. + * + * @param {any} module The module object returned by WS. + * @param {number} courseId Course ID. + * @param {boolean} [prefetch] True to prefetch, false to download right away. + * @param {string} [dirPath] Path of the directory where to store all the content files. This is to keep the files + * relative paths and make the package work in an iframe. Undefined to download the files + * in the filepool root page. + * @return {Promise} Promise resolved when all content is downloaded. Data returned is not reliable. + */ + downloadOrPrefetch(module: any, courseId: number, prefetch?: boolean, dirPath?: string): Promise { + const promises = []; + + promises.push(super.downloadOrPrefetch(module, courseId, prefetch)); + + if (this.pageProvider.isGetPageWSAvailable()) { + promises.push(this.pageProvider.getPageData(courseId, module.id)); + } + + return Promise.all(promises); + } + + /** + * Invalidate the prefetched content. + * + * @param {number} moduleId The module ID. + * @param {number} courseId Course ID the module belongs to. + * @return {Promise} Promise resolved when the data is invalidated. + */ + invalidateContent(moduleId: number, courseId: number): Promise { + return this.pageProvider.invalidateContent(moduleId, courseId); + } + + /** + * Invalidate WS calls needed to determine module status. + * + * @param {any} module Module. + * @param {number} courseId Course ID the module belongs to. + * @return {Promise} Promise resolved when invalidated. + */ + invalidateModule(module: any, courseId: number): Promise { + const promises = []; + + promises.push(this.pageProvider.invalidatePageData(courseId)); + promises.push(this.courseProvider.invalidateModule(module.id)); + + return this.utils.allPromises(promises); + } +} diff --git a/src/app/app.module.ts b/src/app/app.module.ts index 1ae090cd9..943ea88fb 100644 --- a/src/app/app.module.ts +++ b/src/app/app.module.ts @@ -77,6 +77,7 @@ import { AddonModBookModule } from '@addon/mod/book/book.module'; import { AddonModLabelModule } from '@addon/mod/label/label.module'; import { AddonModResourceModule } from '@addon/mod/resource/resource.module'; import { AddonModFolderModule } from '@addon/mod/folder/folder.module'; +import { AddonModPageModule } from '@addon/mod/page/page.module'; import { AddonMessagesModule } from '@addon/messages/messages.module'; import { AddonPushNotificationsModule } from '@addon/pushnotifications/pushnotifications.module'; import { AddonRemoteThemesModule } from '@addon/remotethemes/remotethemes.module'; @@ -158,6 +159,7 @@ export const CORE_PROVIDERS: any[] = [ AddonModLabelModule, AddonModResourceModule, AddonModFolderModule, + AddonModPageModule, AddonMessagesModule, AddonPushNotificationsModule, AddonRemoteThemesModule diff --git a/src/directives/format-text.ts b/src/directives/format-text.ts index 330712d1f..aa6b2e678 100644 --- a/src/directives/format-text.ts +++ b/src/directives/format-text.ts @@ -177,7 +177,7 @@ export class CoreFormatTextDirective implements OnChanges { return; } - this.text = this.text.trim(); + this.text = this.text ? this.text.trim() : ''; this.formatContents().then((div: HTMLElement) => { // Disable media adapt to correctly calculate the height. From 3b7c55e23d89d37b4a90079a14b4596b427a71ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Thu, 15 Mar 2018 16:14:54 +0100 Subject: [PATCH 2/3] MOBILE-2347 core: Create a template class to create resource modules --- src/addon/mod/book/components/index/index.ts | 101 ++--------- src/addon/mod/book/pages/index/index.html | 2 +- .../mod/folder/components/index/index.ts | 104 ++--------- src/addon/mod/folder/pages/index/index.html | 2 +- src/addon/mod/page/components/index/index.ts | 101 ++--------- src/addon/mod/page/pages/index/index.html | 2 +- .../mod/resource/components/index/index.ts | 100 ++--------- src/addon/mod/resource/pages/index/index.html | 2 +- .../course/classes/main-resource-component.ts | 167 ++++++++++++++++++ 9 files changed, 239 insertions(+), 342 deletions(-) create mode 100644 src/core/course/classes/main-resource-component.ts diff --git a/src/addon/mod/book/components/index/index.ts b/src/addon/mod/book/components/index/index.ts index 1183a04e4..c4b4f815e 100644 --- a/src/addon/mod/book/components/index/index.ts +++ b/src/addon/mod/book/components/index/index.ts @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { Component, OnInit, OnDestroy, Input, Output, EventEmitter, Optional } from '@angular/core'; +import { Component, Optional } from '@angular/core'; import { Content, PopoverController } from 'ionic-angular'; import { TranslateService } from '@ngx-translate/core'; import { CoreAppProvider } from '@providers/app'; @@ -20,7 +20,7 @@ import { CoreDomUtilsProvider } from '@providers/utils/dom'; import { CoreTextUtilsProvider } from '@providers/utils/text'; import { CoreCourseProvider } from '@core/course/providers/course'; import { CoreCourseHelperProvider } from '@core/course/providers/helper'; -import { CoreCourseModuleMainComponent } from '@core/course/providers/module-delegate'; +import { CoreCourseModuleMainResourceComponent } from '@core/course/classes/main-resource-component'; import { AddonModBookProvider, AddonModBookContentsMap, AddonModBookTocChapter } from '../../providers/book'; import { AddonModBookPrefetchHandler } from '../../providers/prefetch-handler'; import { AddonModBookTocPopoverComponent } from '../../components/toc-popover/toc-popover'; @@ -32,71 +32,31 @@ import { AddonModBookTocPopoverComponent } from '../../components/toc-popover/to selector: 'addon-mod-book-index', templateUrl: 'index.html', }) -export class AddonModBookIndexComponent implements OnInit, OnDestroy, CoreCourseModuleMainComponent { - @Input() module: any; // The module of the book. - @Input() courseId: number; // Course ID the book belongs to. - @Output() bookRetrieved?: EventEmitter; - - loaded: boolean; +export class AddonModBookIndexComponent extends CoreCourseModuleMainResourceComponent { component = AddonModBookProvider.COMPONENT; - componentId: number; chapterContent: string; previousChapter: string; nextChapter: string; - // Data for context menu. - externalUrl: string; - description: string; - refreshIcon: string; - prefetchStatusIcon: string; - prefetchText: string; - size: string; - protected chapters: AddonModBookTocChapter[]; protected currentChapter: string; protected contentsMap: AddonModBookContentsMap; - protected isDestroyed = false; - protected statusObserver; constructor(private bookProvider: AddonModBookProvider, private courseProvider: CoreCourseProvider, - private domUtils: CoreDomUtilsProvider, private appProvider: CoreAppProvider, private textUtils: CoreTextUtilsProvider, - private courseHelper: CoreCourseHelperProvider, private prefetchDelegate: AddonModBookPrefetchHandler, - private popoverCtrl: PopoverController, private translate: TranslateService, @Optional() private content: Content) { - this.bookRetrieved = new EventEmitter(); + protected domUtils: CoreDomUtilsProvider, private appProvider: CoreAppProvider, + protected textUtils: CoreTextUtilsProvider, protected courseHelper: CoreCourseHelperProvider, + private prefetchDelegate: AddonModBookPrefetchHandler, private popoverCtrl: PopoverController, + protected translate: TranslateService, @Optional() private content: Content) { + super(textUtils, courseHelper, translate, domUtils); } /** * Component being initialized. */ ngOnInit(): void { - this.description = this.module.description; - this.componentId = this.module.id; - this.externalUrl = this.module.url; - this.loaded = false; - this.refreshIcon = 'spinner'; + super.ngOnInit(); - this.fetchContent(); - } - - /** - * Refresh the data. - * - * @param {any} [refresher] Refresher. - * @param {Function} [done] Function to call when done. - * @return {Promise} Promise resolved when done. - */ - doRefresh(refresher?: any, done?: () => void): Promise { - this.refreshIcon = 'spinner'; - - return this.bookProvider.invalidateContent(this.module.id, this.courseId).catch(() => { - // Ignore errors. - }).then(() => { - return this.fetchContent(this.currentChapter, true); - }).finally(() => { - this.refreshIcon = 'refresh'; - refresher && refresher.complete(); - done && done(); - }); + this.loadContent(); } /** @@ -133,40 +93,27 @@ export class AddonModBookIndexComponent implements OnInit, OnDestroy, CoreCourse } /** - * Expand the description. + * Perform the invalidate content function. + * + * @return {Promise} Resolved when done. */ - expandDescription(): void { - this.textUtils.expandText(this.translate.instant('core.description'), this.description, this.component, this.module.id); - } - - /** - * Prefetch the module. - */ - prefetch(): void { - this.courseHelper.contextMenuPrefetch(this, this.module, this.courseId); - } - - /** - * Confirm and remove downloaded files. - */ - removeFiles(): void { - this.courseHelper.confirmAndRemoveFiles(this.module, this.courseId); + protected invalidateContent(): Promise { + return this.bookProvider.invalidateContent(this.module.id, this.courseId); } /** * Download book contents and load the current chapter. * - * @param {string} [chapterId] Chapter to load. * @param {boolean} [refresh] Whether we're refreshing data. * @return {Promise} Promise resolved when done. */ - protected fetchContent(chapterId?: string, refresh?: boolean): Promise { + protected fetchContent(refresh?: boolean): Promise { const promises = []; let downloadFailed = false; // Try to get the book data. promises.push(this.bookProvider.getBook(this.courseId, this.module.id).then((book) => { - this.bookRetrieved.emit(book); + this.dataRetrieved.emit(book); this.description = book.intro || this.description; }).catch(() => { // Ignore errors since this WS isn't available in some Moodle versions. @@ -192,22 +139,17 @@ export class AddonModBookIndexComponent implements OnInit, OnDestroy, CoreCourse } // Show chapter. - return this.loadChapter(chapterId || this.currentChapter).then(() => { + return this.loadChapter(this.currentChapter).then(() => { if (downloadFailed && this.appProvider.isOnline()) { // We could load the main file but the download failed. Show error message. this.domUtils.showErrorModal('core.errordownloadingsomefiles', true); } // All data obtained, now fill the context menu. - this.courseHelper.fillContextMenu(this, this.module, this.courseId, refresh, this.component); + this.fillContextMenu(refresh); }).catch(() => { // Ignore errors, they're handled inside the loadChapter function. }); - }).catch((error) => { - // Error getting data, fail. - this.loaded = true; - this.refreshIcon = 'refresh'; - this.domUtils.showErrorModalDefault(error, 'core.course.errorgetmodule', true); }); } @@ -242,9 +184,4 @@ export class AddonModBookIndexComponent implements OnInit, OnDestroy, CoreCourse this.refreshIcon = 'refresh'; }); } - - ngOnDestroy(): void { - this.isDestroyed = true; - this.statusObserver && this.statusObserver.off(); - } } diff --git a/src/addon/mod/book/pages/index/index.html b/src/addon/mod/book/pages/index/index.html index c0a0d5fa3..906d857d7 100644 --- a/src/addon/mod/book/pages/index/index.html +++ b/src/addon/mod/book/pages/index/index.html @@ -12,5 +12,5 @@ - + diff --git a/src/addon/mod/folder/components/index/index.ts b/src/addon/mod/folder/components/index/index.ts index 910988501..e109b87c0 100644 --- a/src/addon/mod/folder/components/index/index.ts +++ b/src/addon/mod/folder/components/index/index.ts @@ -12,14 +12,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core'; +import { Component, Input } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { CoreAppProvider } from '@providers/app'; import { CoreDomUtilsProvider } from '@providers/utils/dom'; import { CoreTextUtilsProvider } from '@providers/utils/text'; import { CoreCourseProvider } from '@core/course/providers/course'; import { CoreCourseHelperProvider } from '@core/course/providers/helper'; -import { CoreCourseModuleMainComponent } from '@core/course/providers/module-delegate'; +import { CoreCourseModuleMainResourceComponent } from '@core/course/classes/main-resource-component'; import { AddonModFolderProvider } from '../../providers/folder'; import { AddonModFolderHelperProvider } from '../../providers/helper'; @@ -32,47 +32,25 @@ import { AddonModFolderHelperProvider } from '../../providers/helper'; selector: 'addon-mod-folder-index', templateUrl: 'index.html', }) -export class AddonModFolderIndexComponent implements OnInit, OnDestroy, CoreCourseModuleMainComponent { - @Input() module: any; // The module of the folder. - @Input() courseId: number; // Course ID the folder belongs to. +export class AddonModFolderIndexComponent extends CoreCourseModuleMainResourceComponent { @Input() path: string; // For subfolders. Use the path instead of a boolean so Angular detects them as different states. - @Output() folderRetrieved?: EventEmitter; - loaded: boolean; - canReload: boolean; component = AddonModFolderProvider.COMPONENT; - componentId: number; canGetFolder: boolean; contents: any; - // Data for context menu. - externalUrl: string; - description: string; - refreshIcon: string; - prefetchStatusIcon: string; - prefetchText: string; - size: string; - - protected isDestroyed; - protected statusObserver; - constructor(private folderProvider: AddonModFolderProvider, private courseProvider: CoreCourseProvider, - private domUtils: CoreDomUtilsProvider, private appProvider: CoreAppProvider, private textUtils: CoreTextUtilsProvider, - private courseHelper: CoreCourseHelperProvider, private translate: TranslateService, - private folderHelper: AddonModFolderHelperProvider) { - this.folderRetrieved = new EventEmitter(); + protected domUtils: CoreDomUtilsProvider, private appProvider: CoreAppProvider, + protected textUtils: CoreTextUtilsProvider, protected courseHelper: CoreCourseHelperProvider, + protected translate: TranslateService, private folderHelper: AddonModFolderHelperProvider) { + super(textUtils, courseHelper, translate, domUtils); } /** * Component being initialized. */ ngOnInit(): void { - this.description = this.module.description; - this.componentId = this.module.id; - this.externalUrl = this.module.url; - this.loaded = false; - this.canReload = false; - this.refreshIcon = 'spinner'; + super.ngOnInit(); this.canGetFolder = this.folderProvider.isGetFolderWSAvailable(); @@ -80,65 +58,26 @@ export class AddonModFolderIndexComponent implements OnInit, OnDestroy, CoreCour // Subfolder. Use module param. this.showModuleData(this.module); this.loaded = true; - this.canReload = false; this.refreshIcon = 'refresh'; } else { - this.fetchContent().then(() => { + this.loadContent().then(() => { this.folderProvider.logView(this.module.instance).then(() => { this.courseProvider.checkModuleCompletion(this.courseId, this.module.completionstatus); }); }).finally(() => { this.loaded = true; - this.canReload = true; this.refreshIcon = 'refresh'; }); } } /** - * Refresh the data. + * Perform the invalidate content function. * - * @param {any} [refresher] Refresher. - * @param {Function} [done] Function to call when done. - * @return {Promise} Promise resolved when done. + * @return {Promise} Resolved when done. */ - doRefresh(refresher?: any, done?: () => void): Promise { - if (this.canReload) { - this.refreshIcon = 'spinner'; - - this.folderProvider.invalidateContent(this.module.id, this.courseId).catch(() => { - // Ignore errors. - }).then(() => { - return this.fetchContent(true); - }).finally(() => { - this.refreshIcon = 'refresh'; - refresher && refresher.complete(); - done && done(); - }); - } - - return Promise.resolve(); - } - - /** - * Expand the description. - */ - expandDescription(): void { - this.textUtils.expandText(this.translate.instant('core.description'), this.description, this.component, this.module.id); - } - - /** - * Prefetch the module. - */ - prefetch(): void { - this.courseHelper.contextMenuPrefetch(this, this.module, this.courseId); - } - - /** - * Confirm and remove downloaded files. - */ - removeFiles(): void { - this.courseHelper.confirmAndRemoveFiles(this.module, this.courseId); + protected invalidateContent(): Promise { + return this.folderProvider.invalidateContent(this.module.id, this.courseId); } /** @@ -148,7 +87,7 @@ export class AddonModFolderIndexComponent implements OnInit, OnDestroy, CoreCour protected showModuleData(module: any): void { this.description = module.intro || module.description; - this.folderRetrieved.emit(module); + this.dataRetrieved.emit(module); if (this.path) { // Subfolder. @@ -190,24 +129,13 @@ export class AddonModFolderIndexComponent implements OnInit, OnDestroy, CoreCour return promise.then((folder) => { if (folder) { this.description = folder.intro || folder.description; - this.folderRetrieved.emit(folder); + this.dataRetrieved.emit(folder); } this.showModuleData(folder); // All data obtained, now fill the context menu. - this.courseHelper.fillContextMenu(this, this.module, this.courseId, refresh, this.component); - }).catch((error) => { - // Error getting data, fail. - this.domUtils.showErrorModalDefault(error, 'core.course.errorgetmodule', true); - }).finally(() => { - this.loaded = true; - this.refreshIcon = 'refresh'; + this.fillContextMenu(refresh); }); } - - ngOnDestroy(): void { - this.isDestroyed = true; - this.statusObserver && this.statusObserver.off(); - } } diff --git a/src/addon/mod/folder/pages/index/index.html b/src/addon/mod/folder/pages/index/index.html index 9830c28cf..b9548a972 100644 --- a/src/addon/mod/folder/pages/index/index.html +++ b/src/addon/mod/folder/pages/index/index.html @@ -12,5 +12,5 @@ - + diff --git a/src/addon/mod/page/components/index/index.ts b/src/addon/mod/page/components/index/index.ts index 30420a5c4..f4cfcf92f 100644 --- a/src/addon/mod/page/components/index/index.ts +++ b/src/addon/mod/page/components/index/index.ts @@ -12,14 +12,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core'; +import { Component } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { CoreAppProvider } from '@providers/app'; import { CoreDomUtilsProvider } from '@providers/utils/dom'; import { CoreTextUtilsProvider } from '@providers/utils/text'; import { CoreCourseProvider } from '@core/course/providers/course'; import { CoreCourseHelperProvider } from '@core/course/providers/helper'; -import { CoreCourseModuleMainComponent } from '@core/course/providers/module-delegate'; +import { CoreCourseModuleMainResourceComponent } from '@core/course/classes/main-resource-component'; import { AddonModPageProvider } from '../../providers/page'; import { AddonModPageHelperProvider } from '../../providers/helper'; import { AddonModPagePrefetchHandler } from '../../providers/prefetch-handler'; @@ -31,48 +31,29 @@ import { AddonModPagePrefetchHandler } from '../../providers/prefetch-handler'; selector: 'addon-mod-page-index', templateUrl: 'index.html', }) -export class AddonModPageIndexComponent implements OnInit, OnDestroy, CoreCourseModuleMainComponent { - @Input() module: any; // The module of the page. - @Input() courseId: number; // Course ID the page belongs to. - @Output() pageRetrieved?: EventEmitter; - - loaded: boolean; +export class AddonModPageIndexComponent extends CoreCourseModuleMainResourceComponent { component = AddonModPageProvider.COMPONENT; - componentId: number; canGetPage: boolean; contents: any; - - // Data for context menu. - externalUrl: string; - description: string; - refreshIcon: string; - prefetchStatusIcon: string; - prefetchText: string; - size: string; - - protected isDestroyed; - protected statusObserver; + protected fetchContentDefaultError = 'addon.mod_page.errorwhileloadingthepage'; constructor(private pageProvider: AddonModPageProvider, private courseProvider: CoreCourseProvider, - private domUtils: CoreDomUtilsProvider, private appProvider: CoreAppProvider, private textUtils: CoreTextUtilsProvider, - private courseHelper: CoreCourseHelperProvider, private translate: TranslateService, - private pageHelper: AddonModPageHelperProvider, private pagePrefetch: AddonModPagePrefetchHandler) { - this.pageRetrieved = new EventEmitter(); + protected domUtils: CoreDomUtilsProvider, private appProvider: CoreAppProvider, + protected textUtils: CoreTextUtilsProvider, protected courseHelper: CoreCourseHelperProvider, + protected translate: TranslateService, private pageHelper: AddonModPageHelperProvider, + private pagePrefetch: AddonModPagePrefetchHandler) { + super(textUtils, courseHelper, translate, domUtils); } /** * Component being initialized. */ ngOnInit(): void { - this.description = this.module.description; - this.componentId = this.module.id; - this.externalUrl = this.module.url; - this.loaded = false; - this.refreshIcon = 'spinner'; + super.ngOnInit(); this.canGetPage = this.pageProvider.isGetPageWSAvailable(); - this.fetchContent().then(() => { + this.loadContent().then(() => { this.pageProvider.logView(this.module.instance).then(() => { this.courseProvider.checkModuleCompletion(this.courseId, this.module.completionstatus); }); @@ -80,49 +61,12 @@ export class AddonModPageIndexComponent implements OnInit, OnDestroy, CoreCourse } /** - * Refresh the data. + * Perform the invalidate content function. * - * @param {any} [refresher] Refresher. - * @param {Function} [done] Function to call when done. - * @return {Promise} Promise resolved when done. + * @return {Promise} Resolved when done. */ - doRefresh(refresher?: any, done?: () => void): Promise { - if (this.loaded) { - this.refreshIcon = 'spinner'; - - return this.pageProvider.invalidateContent(this.module.id, this.courseId).catch(() => { - // Ignore errors. - }).then(() => { - return this.fetchContent(true); - }).finally(() => { - this.refreshIcon = 'refresh'; - refresher && refresher.complete(); - done && done(); - }); - } - - return Promise.resolve(); - } - - /** - * Expand the description. - */ - expandDescription(): void { - this.textUtils.expandText(this.translate.instant('core.description'), this.description, this.component, this.module.id); - } - - /** - * Prefetch the module. - */ - prefetch(): void { - this.courseHelper.contextMenuPrefetch(this, this.module, this.courseId); - } - - /** - * Confirm and remove downloaded files. - */ - removeFiles(): void { - this.courseHelper.confirmAndRemoveFiles(this.module, this.courseId); + protected invalidateContent(): Promise { + return this.pageProvider.invalidateContent(this.module.id, this.courseId); } /** @@ -158,7 +102,7 @@ export class AddonModPageIndexComponent implements OnInit, OnDestroy, CoreCourse promises.push(getPagePromise.then((page) => { if (page) { this.description = page.intro || page.description; - this.pageRetrieved.emit(page); + this.dataRetrieved.emit(page); } }).catch(() => { // Ignore errors. @@ -167,7 +111,7 @@ export class AddonModPageIndexComponent implements OnInit, OnDestroy, CoreCourse // Get the page HTML. promises.push(this.pageHelper.getPageHtml(this.module.contents, this.module.id).then((content) => { // All data obtained, now fill the context menu. - this.courseHelper.fillContextMenu(this, this.module, this.courseId, refresh, this.component); + this.fillContextMenu(refresh); this.contents = content; @@ -178,17 +122,6 @@ export class AddonModPageIndexComponent implements OnInit, OnDestroy, CoreCourse })); return Promise.all(promises); - }).catch((error) => { - // Error getting data, fail. - this.domUtils.showErrorModalDefault(error, 'addon.mod_page.errorwhileloadingthepage', true); - }).finally(() => { - this.loaded = true; - this.refreshIcon = 'refresh'; }); } - - ngOnDestroy(): void { - this.isDestroyed = true; - this.statusObserver && this.statusObserver.off(); - } } diff --git a/src/addon/mod/page/pages/index/index.html b/src/addon/mod/page/pages/index/index.html index 88b576c88..a11d726c5 100644 --- a/src/addon/mod/page/pages/index/index.html +++ b/src/addon/mod/page/pages/index/index.html @@ -12,5 +12,5 @@ - + diff --git a/src/addon/mod/resource/components/index/index.ts b/src/addon/mod/resource/components/index/index.ts index 04e96c2de..e52881649 100644 --- a/src/addon/mod/resource/components/index/index.ts +++ b/src/addon/mod/resource/components/index/index.ts @@ -12,14 +12,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core'; +import { Component } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { CoreAppProvider } from '@providers/app'; import { CoreDomUtilsProvider } from '@providers/utils/dom'; import { CoreTextUtilsProvider } from '@providers/utils/text'; import { CoreCourseProvider } from '@core/course/providers/course'; import { CoreCourseHelperProvider } from '@core/course/providers/helper'; -import { CoreCourseModuleMainComponent } from '@core/course/providers/module-delegate'; +import { CoreCourseModuleMainResourceComponent } from '@core/course/classes/main-resource-component'; import { AddonModResourceProvider } from '../../providers/resource'; import { AddonModResourcePrefetchHandler } from '../../providers/prefetch-handler'; import { AddonModResourceHelperProvider } from '../../providers/helper'; @@ -31,36 +31,20 @@ import { AddonModResourceHelperProvider } from '../../providers/helper'; selector: 'addon-mod-resource-index', templateUrl: 'index.html', }) -export class AddonModResourceIndexComponent implements OnInit, OnDestroy, CoreCourseModuleMainComponent { - @Input() module: any; // The module of the resource. - @Input() courseId: number; // Course ID the resource belongs to. - @Output() resourceRetrieved?: EventEmitter; - - loaded: boolean; +export class AddonModResourceIndexComponent extends CoreCourseModuleMainResourceComponent { component = AddonModResourceProvider.COMPONENT; - componentId: number; canGetResource: boolean; mode: string; src: string; contentText: string; - // Data for context menu. - externalUrl: string; - description: string; - refreshIcon: string; - prefetchStatusIcon: string; - prefetchText: string; - size: string; - - protected isDestroyed = false; - protected statusObserver; - constructor(private resourceProvider: AddonModResourceProvider, private courseProvider: CoreCourseProvider, - private domUtils: CoreDomUtilsProvider, private appProvider: CoreAppProvider, private textUtils: CoreTextUtilsProvider, - private courseHelper: CoreCourseHelperProvider, private translate: TranslateService, - private prefetchHandler: AddonModResourcePrefetchHandler, private resourceHelper: AddonModResourceHelperProvider) { - this.resourceRetrieved = new EventEmitter(); + protected domUtils: CoreDomUtilsProvider, private appProvider: CoreAppProvider, + protected textUtils: CoreTextUtilsProvider, protected courseHelper: CoreCourseHelperProvider, + protected translate: TranslateService, private prefetchHandler: AddonModResourcePrefetchHandler, + private resourceHelper: AddonModResourceHelperProvider) { + super(textUtils, courseHelper, translate, domUtils); } @@ -68,15 +52,11 @@ export class AddonModResourceIndexComponent implements OnInit, OnDestroy, CoreCo * Component being initialized. */ ngOnInit(): void { - this.description = this.module.description; - this.componentId = this.module.id; - this.externalUrl = this.module.url; - this.loaded = false; - this.refreshIcon = 'spinner'; + super.ngOnInit(); this.canGetResource = this.resourceProvider.isGetResourceWSAvailable(); - this.fetchContent().then(() => { + this.loadContent().then(() => { this.resourceProvider.logView(this.module.instance).then(() => { this.courseProvider.checkModuleCompletion(this.courseId, this.module.completionstatus); }); @@ -84,49 +64,12 @@ export class AddonModResourceIndexComponent implements OnInit, OnDestroy, CoreCo } /** - * Refresh the data. + * Perform the invalidate content function. * - * @param {any} [refresher] Refresher. - * @param {Function} [done] Function to call when done. - * @return {Promise} Promise resolved when done. + * @return {Promise} Resolved when done. */ - doRefresh(refresher?: any, done?: () => void): Promise { - if (this.loaded) { - this.refreshIcon = 'spinner'; - - return this.resourceProvider.invalidateContent(this.module.id, this.courseId).catch(() => { - // Ignore errors. - }).then(() => { - return this.fetchContent(true); - }).finally(() => { - this.refreshIcon = 'refresh'; - refresher && refresher.complete(); - done && done(); - }); - } - - return Promise.resolve(); - } - - /** - * Expand the description. - */ - expandDescription(): void { - this.textUtils.expandText(this.translate.instant('core.description'), this.description, this.component, this.module.id); - } - - /** - * Prefetch the module. - */ - prefetch(): void { - this.courseHelper.contextMenuPrefetch(this, this.module, this.courseId); - } - - /** - * Confirm and remove downloaded files. - */ - removeFiles(): void { - this.courseHelper.confirmAndRemoveFiles(this.module, this.courseId); + protected invalidateContent(): Promise { + return this.resourceProvider.invalidateContent(this.module.id, this.courseId); } /** @@ -155,7 +98,7 @@ export class AddonModResourceIndexComponent implements OnInit, OnDestroy, CoreCo }).then((resource) => { if (resource) { this.description = resource.intro || resource.description; - this.resourceRetrieved.emit(resource); + this.dataRetrieved.emit(resource); } if (this.resourceHelper.isDisplayedInIframe(this.module)) { @@ -196,13 +139,7 @@ export class AddonModResourceIndexComponent implements OnInit, OnDestroy, CoreCo } }).then(() => { // All data obtained, now fill the context menu. - this.courseHelper.fillContextMenu(this, this.module, this.courseId, refresh, this.component); - }).catch((error) => { - // Error getting data, fail. - this.domUtils.showErrorModalDefault(error, 'core.course.errorgetmodule', true); - }).finally(() => { - this.loaded = true; - this.refreshIcon = 'refresh'; + this.fillContextMenu(refresh); }); } @@ -212,9 +149,4 @@ export class AddonModResourceIndexComponent implements OnInit, OnDestroy, CoreCo open(): void { this.resourceHelper.openModuleFile(this.module, this.courseId); } - - ngOnDestroy(): void { - this.isDestroyed = true; - this.statusObserver && this.statusObserver.off(); - } } diff --git a/src/addon/mod/resource/pages/index/index.html b/src/addon/mod/resource/pages/index/index.html index dad3b8a4b..e129d7356 100644 --- a/src/addon/mod/resource/pages/index/index.html +++ b/src/addon/mod/resource/pages/index/index.html @@ -12,5 +12,5 @@ - + diff --git a/src/core/course/classes/main-resource-component.ts b/src/core/course/classes/main-resource-component.ts new file mode 100644 index 000000000..370720736 --- /dev/null +++ b/src/core/course/classes/main-resource-component.ts @@ -0,0 +1,167 @@ +// (C) Copyright 2015 Martin Dougiamas +// +// 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 { OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { CoreDomUtilsProvider } from '@providers/utils/dom'; +import { CoreTextUtilsProvider } from '@providers/utils/text'; +import { CoreCourseHelperProvider } from '@core/course/providers/helper'; +import { CoreCourseModuleMainComponent } from '@core/course/providers/module-delegate'; + +/** + * Template class to easily create CoreCourseModuleMainComponent of resources (or activities without syncing). + */ +export class CoreCourseModuleMainResourceComponent implements OnInit, OnDestroy, CoreCourseModuleMainComponent { + @Input() module: any; // The module of the component. + @Input() courseId: number; // Course ID the component belongs to. + @Output() dataRetrieved?: EventEmitter; // Called to notify changes the index page from the main component. + + loaded: boolean; // If the component has been loaded. + component: string; // Component name. + componentId: number; // Component ID. + + // Data for context menu. + externalUrl: string; // External URL to open in browser. + description: string; // Module description. + refreshIcon: string; // Refresh icon, normally spinner or refresh. + prefetchStatusIcon: string; // Used when calling fillContextMenu. + prefetchText: string; // Used when calling fillContextMenu. + size: string; // Used when calling fillContextMenu. + + protected isDestroyed; // Whether the component is destroyed, used when calling fillContextMenu. + protected statusObserver; // Observer of package status changed, used when calling fillContextMenu. + protected fetchContentDefaultError = 'core.course.errorgetmodule'; // Default error to show when loading contents. + + constructor(protected textUtils: CoreTextUtilsProvider, protected courseHelper: CoreCourseHelperProvider, + protected translate: TranslateService, protected domUtils: CoreDomUtilsProvider) { + this.dataRetrieved = new EventEmitter(); + } + + /** + * Component being initialized. + */ + ngOnInit(): void { + this.description = this.module.description; + this.componentId = this.module.id; + this.externalUrl = this.module.url; + this.loaded = false; + this.refreshIcon = 'spinner'; + } + + /** + * Refresh the data. + * + * @param {any} [refresher] Refresher. + * @param {Function} [done] Function to call when done. + * @return {Promise} Promise resolved when done. + */ + doRefresh(refresher?: any, done?: () => void): Promise { + if (this.loaded) { + this.refreshIcon = 'spinner'; + + return this.refreshContent().finally(() => { + this.refreshIcon = 'refresh'; + refresher && refresher.complete(); + done && done(); + }); + } + + return Promise.resolve(); + } + + /** + * Perform the refresh content function. + * + * @return {Promise} Resolved when done. + */ + protected refreshContent(): Promise { + return this.invalidateContent().catch(() => { + // Ignore errors. + }).then(() => { + return this.loadContent(true); + }); + } + + /** + * Perform the invalidate content function. + * + * @return {Promise} Resolved when done. + */ + protected invalidateContent(): Promise { + return Promise.resolve(); + } + + /** + * Download the component contents. + * + * @param {boolean} [refresh] Whether we're refreshing data. + * @return {Promise} Promise resolved when done. + */ + protected fetchContent(refresh?: boolean): Promise { + return Promise.resolve(); + } + + /** + * Loads the component contents and shows the corresponding error. + * + * @param {boolean} [refresh] Whether we're refreshing data. + * @return {Promise} Promise resolved when done. + */ + protected loadContent(refresh?: boolean): Promise { + return this.fetchContent(refresh).catch((error) => { + // Error getting data, fail. + this.domUtils.showErrorModalDefault(error, this.fetchContentDefaultError, true); + }).finally(() => { + this.loaded = true; + this.refreshIcon = 'refresh'; + }); + } + + /** + * Fill the context menu options + */ + protected fillContextMenu(refresh: boolean = false): void { + // All data obtained, now fill the context menu. + this.courseHelper.fillContextMenu(this, this.module, this.courseId, refresh, this.component); + } + + /** + * Expand the description. + */ + expandDescription(): void { + this.textUtils.expandText(this.translate.instant('core.description'), this.description, this.component, this.module.id); + } + + /** + * Prefetch the module. + */ + prefetch(): void { + this.courseHelper.contextMenuPrefetch(this, this.module, this.courseId); + } + + /** + * Confirm and remove downloaded files. + */ + removeFiles(): void { + this.courseHelper.confirmAndRemoveFiles(this.module, this.courseId); + } + + /** + * Component being destroyed. + */ + ngOnDestroy(): void { + this.isDestroyed = true; + this.statusObserver && this.statusObserver.off(); + } +} From 604d0e9d9e936f02472a8322dec83b8fcbe39085 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Fri, 16 Mar 2018 10:22:08 +0100 Subject: [PATCH 3/3] MOBILE-2347 messages: Fix scrolling errors on message discussions --- src/addon/messages/components/contacts/contacts.html | 2 +- src/addon/messages/pages/discussion/discussion.ts | 12 ++++++++++-- src/components/search-box/search-box.ts | 2 +- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/addon/messages/components/contacts/contacts.html b/src/addon/messages/components/contacts/contacts.html index a722ca171..06123d70c 100644 --- a/src/addon/messages/components/contacts/contacts.html +++ b/src/addon/messages/components/contacts/contacts.html @@ -3,7 +3,7 @@ - + diff --git a/src/addon/messages/pages/discussion/discussion.ts b/src/addon/messages/pages/discussion/discussion.ts index f164273f8..d29d7b0ea 100644 --- a/src/addon/messages/pages/discussion/discussion.ts +++ b/src/addon/messages/pages/discussion/discussion.ts @@ -65,6 +65,7 @@ export class AddonMessagesDiscussionPage implements OnDestroy { showDelete = false; canDelete = false; scrollBottom = true; + viewDestroyed = false; constructor(private eventsProvider: CoreEventsProvider, sitesProvider: CoreSitesProvider, navParams: NavParams, private userProvider: CoreUserProvider, private navCtrl: NavController, private messagesSync: AddonMessagesSyncProvider, @@ -220,6 +221,10 @@ export class AddonMessagesDiscussionPage implements OnDestroy { }).then(() => { return this.getDiscussion(this.pagesLoaded); }).then((messages) => { + if (this.viewDestroyed) { + return Promise.resolve(); + } + // Check if we are at the bottom to scroll it after render. this.scrollBottom = this.content.scrollHeight - this.content.scrollTop === this.content.contentHeight; @@ -558,7 +563,7 @@ export class AddonMessagesDiscussionPage implements OnDestroy { // Wait for new content height to be calculated. setTimeout(() => { // Visible content size changed, maintain the bottom position. - if (this.content && this.content.contentHeight != this.oldContentHeight) { + if (!this.viewDestroyed && this.content && this.content.contentHeight != this.oldContentHeight) { if (!top) { top = this.content.getContentDimensions().scrollTop; } @@ -579,7 +584,9 @@ export class AddonMessagesDiscussionPage implements OnDestroy { if (this.scrollBottom) { // Need a timeout to leave time to the view to be rendered. setTimeout(() => { - this.content.scrollToBottom(0); + if (!this.viewDestroyed) { + this.content.scrollToBottom(0); + } }); this.scrollBottom = false; } @@ -685,5 +692,6 @@ export class AddonMessagesDiscussionPage implements OnDestroy { // Unset again, just in case. this.unsetPolling(); this.syncObserver && this.syncObserver.off(); + this.viewDestroyed = true; } } diff --git a/src/components/search-box/search-box.ts b/src/components/search-box/search-box.ts index dabae223c..2e2e9a117 100644 --- a/src/components/search-box/search-box.ts +++ b/src/components/search-box/search-box.ts @@ -40,7 +40,7 @@ export class CoreSearchBoxComponent implements OnInit { @Input() showClear = true; // Show/hide clear button. @Input() disabled = false; // Disables the input text. @Output() onSubmit: EventEmitter; // Send data when submitting the search form. - @Output() onClear?: EventEmitter; // Send event when clearing the search form. + @Output() onClear: EventEmitter; // Send event when clearing the search form. searched = false; searchText = '';